-
Notifications
You must be signed in to change notification settings - Fork 2
/
wrappers.py
69 lines (63 loc) · 1.9 KB
/
wrappers.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
from flask import jsonify, request
from functools import wraps
import jwt
from config import CONFIG
admin = False
SECRET_KEY = CONFIG['SECRET_KEY']
def admin_require(f):
@wraps(f)
def decorated_function(*args, **kwargs):
if admin:
return f(*args, **kwargs)
else:
return jsonify({
"status": {
"code": 403,
"message": "Forbidden",
},
"data": None
}), 403
return decorated_function
def token_required(f):
@wraps(f)
def decorator(*args, **kwargs):
token = request.headers.get('Authorization', None)
if not token:
return jsonify({
"status": {
"code": 401,
"message": "Invalid token",
},
"data": None
}), 401
try:
token_prefix, token_value = token.split()
if token_prefix.lower() != 'bearer':
raise ValueError('Invalid token prefix')
data = jwt.decode(token_value, SECRET_KEY, algorithms=['HS256'])
except jwt.ExpiredSignatureError:
return jsonify({
"status": {
"code": 401,
"message": "Token has expired",
},
"data": None
}), 401
except jwt.InvalidTokenError:
return jsonify({
"status": {
"code": 401,
"message": "Invalid token"
},
"data": None,
}), 401
except ValueError:
return jsonify({
"status": {
"code": 401,
"message": "Invalid token format",
},
"data": None
}), 401
return f(data, *args, **kwargs)
return decorator