Add keygen and token fetching

This commit is contained in:
Corder Guy 2018-04-25 13:51:11 -05:00
parent 01ac4264c9
commit 393fd42064

View file

@ -4,6 +4,8 @@ Handle API requests to the database
''' '''
import json import json
import random
import string
import sqlite3 import sqlite3
from os import path from os import path
@ -13,6 +15,39 @@ if not path.exists(DATABASE):
# TODO: Add ability to store and retrieve avatars (as image files?) # TODO: Add ability to store and retrieve avatars (as image files?)
# TODO: Add authentication generation
# TODO: Allow updating data with authorization
def make_new_account(username):
'''
Returns a new API key if the provided username is unique
'''
conn = sqlite3.connect(DATABASE)
conn.row_factory = sqlite3.Row
cursor = conn.cursor()
output = cursor.execute(
'SELECT user_id FROM users ORDER BY user_id DESC').fetchall()
existing_ids = [str(dict(row)['user_id']) for row in output]
user_id = str(random.randint(1, 1000000))
while user_id in existing_ids:
user_id = str(random.randint(1, 1000000))
score = 0
token = ''.join([
random.choice(string.ascii_letters + string.digits + '+=')
for _ in range(30)
])
cursor.execute(
'INSERT INTO users (user_id, username, score, token) VALUES (?,\'?\',?,?)',
(user_id, username, score, token))
return json.dumps([{'key': token}])
def fetch_users(user_ids): def fetch_users(user_ids):
''' '''
@ -24,7 +59,9 @@ def fetch_users(user_ids):
cursor = conn.cursor() cursor = conn.cursor()
output = [] output = []
for user_id in user_ids: for user_id in user_ids:
cursor.execute('SELECT * FROM users WHERE user_id=(?)', (user_id, )) cursor.execute(
'SELECT user_id, username, score FROM users WHERE user_id=(?)',
(user_id, ))
output += cursor.fetchall() output += cursor.fetchall()
output = json.dumps([dict(row) for row in output]) output = json.dumps([dict(row) for row in output])
@ -73,10 +110,11 @@ def fetch_user(user_id):
cursor = conn.cursor() cursor = conn.cursor()
if user_id != '*': # must use (?), (item,) format if user_id != '*': # must use (?), (item,) format
cursor.execute( cursor.execute(
'SELECT * FROM users WHERE user_id=(?) ORDER BY score DESC', 'SELECT user_id, username, score FROM users WHERE user_id=(?) ORDER BY score DESC',
(user_id, )) (user_id, ))
else: else:
cursor.execute('SELECT * FROM users ORDER BY score DESC') cursor.execute(
'SELECT user_id, username, score FROM users ORDER BY score DESC')
output = cursor.fetchall() output = cursor.fetchall()
output = json.dumps([dict(row) for row in output]) output = json.dumps([dict(row) for row in output])
@ -96,7 +134,8 @@ def fetch_top_n(num):
conn = sqlite3.connect(DATABASE) conn = sqlite3.connect(DATABASE)
conn.row_factory = sqlite3.Row conn.row_factory = sqlite3.Row
cursor = conn.cursor() cursor = conn.cursor()
cursor.execute('SELECT username, score FROM users ORDER BY score DESC') cursor.execute(
'SELECT user_id, username, score FROM users ORDER BY score DESC')
output = cursor.fetchall() output = cursor.fetchall()
num = int(num) num = int(num)
@ -114,8 +153,10 @@ def process_request(uri):
''' '''
Handles the API endpoint. Handles the API endpoint.
Currently supports: Currently supports:
- /mocha/users/{user_id} Returns JSON of the specified user - /mocha/users/{user_id} Returns JSON of the specified user
- /mocha/users/* Returns JSON list of all users - /mocha/users/* Returns JSON list of all users
- /mocha/top/n Returns JSON list of top n users by score
- /mocha/add/{username} Returns JSON of token for new user
''' '''
parts = uri.split('/')[1:] parts = uri.split('/')[1:]
assert parts[0] == 'mocha' assert parts[0] == 'mocha'
@ -129,6 +170,8 @@ def process_request(uri):
output = fetch_user(parts[2]) output = fetch_user(parts[2])
elif parts[1] == 'top' and len(parts) > 2: elif parts[1] == 'top' and len(parts) > 2:
output = fetch_top_n(parts[2]) output = fetch_top_n(parts[2])
elif parts[1] == 'add' and len(parts) > 2:
output = make_new_account(parts[2])
else: else:
output = None output = None
@ -157,6 +200,6 @@ def application(environ, start_response):
if __name__ == '__main__': if __name__ == '__main__':
print(fetch_user('*')) print(fetch_top_n(2))
# vim: tabstop=4 shiftwidth=4 softtabstop=4 expandtab # vim: tabstop=4 shiftwidth=4 softtabstop=4 expandtab