-
Notifications
You must be signed in to change notification settings - Fork 2
/
decorator.py
51 lines (43 loc) · 1.59 KB
/
decorator.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
import logging
from functools import wraps
from jwt import JWTValidationError, JWTToken
def need_auth(basic_auth, *permissions):
def decorator(func):
@wraps(func)
def wrapper(handler, *args, **kwargs):
auth_header = basic_auth
if auth_header == "null":
# no header
logging.info("Authorization header is blank")
return
try:
# trying to get token from `Bearer <token>` string
token = auth_header.split(" ")[1]
except IndexError:
logging.info("Cannot parse header. header: {}"
.format(auth_header))
return
# Start JWT validation
try:
# parsing
jwt_token = JWTToken(token)
except JWTValidationError:
logging.info("Cannot parse header. header: {}"
.format(auth_header))
return
try:
# validation
jwt_token.is_valid()
except JWTValidationError:
logging.info("JWT Token invalid. header: {}"
.format(auth_header))
return
try:
# permissions
jwt_token.has_permissions(*permissions)
return func(handler, *args, **kwargs)
except JWTValidationError:
logging.info("No permissions. header: {}"
.format(auth_header))
return wrapper
return decorator