-
Notifications
You must be signed in to change notification settings - Fork 0
/
utils.py
97 lines (81 loc) · 2.66 KB
/
utils.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
import re
from functools import wraps
from flask_restful import reqparse, abort
from sqlalchemy import text
import json
import hashlib
import time
import datetime
#
from db import db
token_parser = reqparse.RequestParser()
token_parser.add_argument('Authorization', type=str, location='headers', required=True)
def check_user_exist(stuID):
res = db.session.execute(
text('SELECT uid FROM `user` WHERE username=:user'), {'user': stuID}
)
return res.returns_rows and res.rowcount >= 1
def check_token(stuID, token):
res = db.session.execute(
text('SELECT token FROM `user` WHERE username=:user'), {'user': stuID}
)
if res.returns_rows and res.rowcount == 1:
act_token = res.fetchone()[0]
return act_token == token
else:
raise RuntimeError
def check_null(data):
if len(str(data)) == 0:
return ''
else:
return data
def token_required(func):
@wraps(func)
def wrapper(*args, **kwargs):
header = token_parser.parse_args()
try:
t, h = header['Authorization'].split()
except ValueError as e:
print(e)
abort(400, message='Bad token')
stuID = kwargs['stuID']
# check user
if not check_user_exist(stuID):
abort(404, message='User not found')
if not re.match('^[a-f0-9]{32}$', h):
abort(400, message='Bad token')
if t != 'Digest':
abort(400, message='Bad token')
if not check_token(stuID, h):
abort(400, message='Bad token')
return func(*args, **kwargs)
return wrapper
def result_msg(s):
return {'message': s}
def api_prefix(s):
return '/db/v1' + s
def md5(s, salt=''):
if isinstance(s, str):
s = s.encode('utf-8')
elif isinstance(s, dict):
json_dic = json.dumps(s, sort_keys=True)
return md5(json_dic)
return hashlib.md5(s).hexdigest()
# https://stackoverflow.com/questions/475074/regex-to-parse-or-validate-base64-data
B64_REGEX = re.compile('^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=|[A-Za-z0-9+/]{4})$')
def datetime_from_timestamp(ts):
"""Return a datetime converted from a timestamp"""
return datetime.datetime.fromtimestamp(ts)
def datetime_now():
return datetime.datetime.now()
def time_from_datetime(dt):
raise NotImplementedError
def time_now():
return time.time()
def time_limit_check(last, limit):
"""Check if the time limit is excceeded.\n
Return: `bool`
- `True`: the time delta is less than the limit
- `False`: expired"""
print('[*] time_limit_check(): {}'.format(datetime_now() - last))
return datetime_now() - last < limit