-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapi.py
170 lines (134 loc) · 4.06 KB
/
api.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
import datetime
from enum import Enum, IntEnum, auto
from http import HTTPStatus
import json
import traceback
import sys
from flask import Blueprint, request, jsonify, session
import core
api = Blueprint('api', __name__, url_prefix='/api/v1')
def get_model():
try:
token = None
if request.authorization:
token = request.authorization.token
else:
try:
token = session['user_session']['token']
except (KeyError, TypeError):
token = None
return core.Model(token)
except core.RemovedSessionError as e:
# TODO: Return an error
return core.Model()
class Status(IntEnum):
ok = HTTPStatus.OK.value
created = HTTPStatus.CREATED.value
no_content = HTTPStatus.NO_CONTENT.value
bad_request = HTTPStatus.BAD_REQUEST.value
error = bad_request
unauthorized = HTTPStatus.UNAUTHORIZED.value
forbidden = HTTPStatus.FORBIDDEN.value
not_found = HTTPStatus.NOT_FOUND.value
conflict = HTTPStatus.CONFLICT.value
gone = HTTPStatus.GONE.value
def is_ok(self):
return self.value < 400
def as_http_status(self):
if 100 <= self.value < 600:
return self.value
elif self.value < 100:
return HTTPStatus.OK.value
else:
return HTTPStatus.BAD_REQUEST.value
"""
{
"status": "ok" | "error",
"result": Any,
"details": {
"code": Integer,
"message": String
}
}
"""
def api_response(status: Status, data=None):
status_type = "ok" if status.is_ok() else "error"
return {
"status": status_type,
"details": {
"code": status.value,
"message": status.name
},
"result": data,
}, status.as_http_status()
@api.route('/users')
def get_users():
model = get_model()
return api_response(Status.ok, model.get_users())
@api.post('/login')
def login():
data = request.get_json()
username = data['username']
password = data['password']
model = get_model()
if user := model.login(username, password):
return api_response(Status.ok, user)
else:
return api_response(Status.not_found, "Invalid username or password")
@api.post('/create-account')
def create_account():
data = request.get_json()
username = data['username']
password = data['password']
pin = data['pin']
model = get_model()
if model.create_account(username, password, pin):
return api_response(Status.created)
else:
return api_response(Status.conflict, "User already exists")
@api.post('/recovery')
def recovery():
data = request.get_json()
username = data['username']
pin = data['pin']
new_password = data['new_password']
model = get_model()
if model.recover_account(username, pin, new_password):
return api_response(Status.ok)
else:
return api_response(Status.not_found)
@api.patch('/user')
def update_user():
data = request.get_json()
model = get_model()
if password := data.get("password"):
model.change_password(password)
if pin := data.get("pin"):
model.change_pin(pin)
return api_response(Status.ok)
@api.post('/score')
def insert_score():
data = request.get_json()
model = get_model()
date_str: str = data['date']
# Python <= 3.10 can't parse Z in ISO timestamps
if sys.version_info.major == 3 and sys.version_info.minor <= 10:
if date_str.endswith('Z'):
date_str = date_str.replace('Z', '+00:00')
date = datetime.datetime.fromisoformat(date_str).astimezone()
id = model.insert_score(
data['seed'],
data['version'],
date,
data['score'],
data['time_ms'],
data['success'],
json.dumps(data['details'])
)
return api_response(Status.created, id)
@api.errorhandler(Exception)
def catch_all_handler(e):
return api_response(Status.error, str(e) + "\n\n" + traceback.format_exc())
@api.errorhandler(404)
def not_found_handler(e):
return api_response(Status.not_found, e.description)