Skip to content

tokens

routes.utils.tokens

SECRET_KEY_TOKEN module-attribute

SECRET_KEY_TOKEN = token_hex(256)

SECRET_KEY_TOKEN_REFRESH module-attribute

SECRET_KEY_TOKEN_REFRESH = token_hex(256)

decode_auth_token

decode_auth_token(
    token, is_refresh=False, payload_key_to_return="sub"
)

Function decoding the token

Source code in yaptide/routes/utils/tokens.py
56
57
58
59
60
61
62
63
64
65
66
67
68
69
def decode_auth_token(token: str, is_refresh: bool = False, payload_key_to_return="sub") -> Union[int, str]:
    """Function decoding the token"""
    if is_refresh:
        secret = SECRET_KEY_TOKEN_REFRESH
    else:
        secret = SECRET_KEY_TOKEN

    try:
        payload = jwt.decode(token, secret, algorithms=['HS256'])
        return payload[payload_key_to_return]
    except jwt.ExpiredSignatureError:
        return 'Signature expired.'
    except jwt.InvalidTokenError:
        return 'Invalid token.'

encode_auth_token

encode_auth_token(
    user_id, is_refresh=False, is_keycloak=False
)

Function encoding the token

Source code in yaptide/routes/utils/tokens.py
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
def encode_auth_token(user_id: int,
                      is_refresh: bool = False,
                      is_keycloak: bool = False) -> tuple[Union[str, Exception], datetime]:  # skipcq: FLK-E101
    """Function encoding the token"""
    if is_refresh:
        secret = SECRET_KEY_TOKEN_REFRESH
        exp_time_minutes = _Refresh_Token_Expiration_Time
    else:
        secret = SECRET_KEY_TOKEN
        exp_time_minutes = _Keycloak_Token_Expiration_Time if is_keycloak else _Access_Token_Expiration_Time

    exp = datetime.utcnow() + timedelta(minutes=exp_time_minutes)

    try:
        # For a description of the payload fields, take look
        # at JSON Web Token RFC https://datatracker.ietf.org/doc/html/rfc7519
        payload = {
            'exp': exp,  # Token Expiration Time
            'iat': datetime.utcnow(),  # Issued At Time
            'sub': user_id  # Subject
        }
        return jwt.encode(payload, secret, algorithm='HS256'), exp
    except Exception as e:  # skipcq: PYL-W0703
        return e, exp

encode_simulation_auth_token

encode_simulation_auth_token(simulation_id)

Function that encodes JWT token for simulation 'update_key'

Source code in yaptide/routes/utils/tokens.py
41
42
43
44
45
46
47
48
49
50
51
52
53
def encode_simulation_auth_token(simulation_id: int):
    """Function that encodes JWT token for simulation 'update_key'"""
    secret = SECRET_KEY_TOKEN
    exp = datetime.utcnow() + timedelta(minutes=_Simulation_Token_Expiration_time)
    try:
        payload = {
            'exp': exp,  # Token Expiration Time
            'iat': datetime.utcnow(),  # Issued At Time
            'simulation_id': simulation_id  # Subject
        }
        return jwt.encode(payload, secret, algorithm='HS256')
    except Exception as e:  # skipcq: PYL-W0703
        return e, exp