This repository has been archived by the owner on Feb 7, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 3
/
auth.py
86 lines (67 loc) · 2.8 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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
from datetime import datetime
from functools import wraps
import jwt
from flask import request
from werkzeug.exceptions import Forbidden
def _get_claims(audience, ttl):
from server import app
return {
# Expiration Time Claim
'exp': datetime.utcnow() + ttl,
# Not Before Time Claim
'nbf': datetime.utcnow(),
# Issuer Claim
'iss': app.config['ISSUER'],
# Audience Claim
'aud': audience,
# Issued At Claim
'iat': datetime.utcnow()
}
def sign_start_registration(data):
from server import app
payload = {**data, **_get_claims(app.config['REGISTRATION_AUDIENCE'],
app.config['REGISTRATION_TOKEN_LIFE_TIME'])}
return jwt.encode(payload, app.config['HMAC_KEY'],
algorithm=app.config['REGISTRATION_ALGORITHM'])
def sign_challenge(data):
from server import app
payload = {**data, **_get_claims(app.config['CHALLENGE_AUDIENCE'],
app.config['CHALLENGE_TOKEN_LIFE_TIME'])}
return jwt.encode(payload, app.config['HMAC_KEY'], algorithm=app.config['CHALLENGE_ALGORITHM'])
def sign_login_credentials(data):
from server import app
payload = {**data,
**_get_claims(app.config['MS2_AUDIENCE'], app.config["LOGIN_TOKEN_LIFE_TIME"])}
return jwt.encode(payload, app.config['PRIVATE_ECDSA_KEY'],
algorithm=app.config['LOGIN_ALGORITHM'])
def verify_registration_started(token):
from server import app
return jwt.decode(token, app.config['HMAC_KEY'],
audience=app.config['REGISTRATION_AUDIENCE'],
issuer=app.config['ISSUER'],
algorithms=app.config['REGISTRATION_ALGORITHM'])
def verify_logged_in(token):
from server import app
return jwt.decode(token, app.config['PUBLIC_ECDSA_KEY'],
audience=app.config['MS2_AUDIENCE'],
issuer=app.config['ISSUER'],
algorithms=app.config['LOGIN_ALGORITHM'])
def verify_challenged(token):
from server import app
return jwt.decode(token, app.config['HMAC_KEY'],
audience=app.config['CHALLENGE_AUDIENCE'],
issuer=app.config['ISSUER'],
algorithms=app.config['CHALLENGE_ALGORITHM'])
def verify_jwt(check=None):
def decorator(f):
@wraps(f)
def wrapped(*args, **kwargs):
auth_header = request.headers.get('Authorization')
auth_type, auth_value = auth_header.split()
if auth_type != "JWT":
return Forbidden("JWT required")
auth_data = check(auth_value)
request.authorization = auth_data
return f(*args, **kwargs)
return wrapped
return decorator