-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathauth.py
63 lines (51 loc) · 1.94 KB
/
auth.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
import jwt
import sys
secret_key = "my_secret_key"
def jwtauth(handler_class):
''' Handle Tornado JWT Auth '''
def wrap_execute(handler_execute):
def require_auth(handler, kwargs):
auth = handler.request.headers.get('Authorization')
if auth:
parts = auth.split()
if parts[0].lower() != 'bearer':
handler._transforms = []
handler.set_status(401)
handler.write("invalid header authorization")
handler.finish()
elif len(parts) == 1:
handler._transforms = []
handler.set_status(401)
handler.write("invalid header authorization")
handler.finish()
elif len(parts) > 2:
handler._transforms = []
handler.set_status(401)
handler.write("invalid header authorization")
handler.finish()
token = parts[1]
try:
jwt.decode(
token,
secret_key,
algorithm='HS256'
)
except Exception as e:
handler._transforms = []
handler.set_status(401)
handler.write(e.message)
handler.finish()
else:
handler._transforms = []
handler.write("Missing authorization")
handler.finish()
return True
def _execute(self, transforms, *args, **kwargs):
try:
require_auth(self, kwargs)
except Exception:
return False
return handler_execute(self, transforms, *args, **kwargs)
return _execute
handler_class._execute = wrap_execute(handler_class._execute)
return handler_class