48 lines
1.6 KiB
Python
48 lines
1.6 KiB
Python
import os
|
|
import jwt
|
|
import datetime
|
|
import secrets
|
|
|
|
def create_api_key():
|
|
return secrets.token_urlsafe(16)
|
|
|
|
def generate_jwt(payload, lifetime=None):
|
|
"""
|
|
creates an encoded token, which is based on the 'SECRET_KEY' environment variable. The environment variable
|
|
is set when the .wsgi application is started or can theoretically be set on system-level.
|
|
|
|
args:
|
|
payload:
|
|
json-dictionary with key:value pairs.
|
|
|
|
lifetime:
|
|
When a 'lifetime' (integer) is provided, the payload will be extended by an expiration key 'exp', which is
|
|
valid for the next {lifetime} minutes.
|
|
|
|
returns: token, a JWT-encoded string
|
|
"""
|
|
if lifetime:
|
|
payload['exp'] = (datetime.datetime.now() + datetime.timedelta(minutes=lifetime)).timestamp()
|
|
return jwt.encode(payload, os.environ.get('SECRET_KEY'), algorithm="HS256")
|
|
|
|
def decode_jwt(token):
|
|
"""
|
|
this function reverts the {generate_jwt} function. An encoded JWT token is decoded into a JSON dictionary.
|
|
The function is commonly used to decode a login-token and obtain a 'user_data' variable, which is a dictionary.
|
|
|
|
Example of 'user_data':
|
|
{
|
|
'id': 1,
|
|
'participant_id': 1,
|
|
'first_name': 'Firstname',
|
|
'last_name': 'Lastname',
|
|
'user_name': 'xUsername01',
|
|
'user_phone': '+01 123 456 7890',
|
|
'user_email': 'firstname.lastname@internet.com',
|
|
'exp': 1716881626.056438 # expiration timestamp
|
|
}
|
|
"""
|
|
return jwt.decode(token, os.environ.get('SECRET_KEY'), algorithms=["HS256"])
|
|
|
|
|