-
Notifications
You must be signed in to change notification settings - Fork 0
/
token_utils.py
52 lines (42 loc) · 1.65 KB
/
token_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
import jwt
import os
from dotenv import load_dotenv
from time import time
from secrets import token_hex
from uuid import uuid4
load_dotenv()
key = os.getenv("HS256_KEY")
class AuthorizationCode:
"""Handles the authorization code."""
def __init__(self):
"""Initializes authorization code attributes."""
self.value = None
self.client_id = None
self.email = None
self.iat = None
self.exp = None
def generate(self, client_id, email, exp):
"""Generates a new authorization code valid for a specific client and user combination."""
self.client_id = client_id
self.value = f"{token_hex(32)}"
self.email = email
self.iat = int(time())
self.exp = exp
def validate(self, client_id, value):
"""Verifies if an authorization code is correct, issued for the requesting client, and not expired."""
if (client_id != self.client_id) or (value != self.value) or (int(time()) > self.iat + self.exp):
return False
else:
return True
def generate_jwt(audience, subject):
"""Generates a JWT for use as the access token."""
now = time()
duration = 3600
expiration = now + duration
payload = {"aud": audience, "exp": expiration, "iat": now, "sub": subject, "jti": str(uuid4())}
encoded_token = jwt.encode(payload, key, algorithm="HS256")
return {"value": encoded_token, "duration": duration}
def verify_jwt(encoded_token):
"""Verifies the validity of a provided JWT access token."""
decoded_token = jwt.decode(encoded_token, key, algorithms="HS256", options={"verify_aud": False})
return decoded_token