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)

Function decoding the token

Source code in yaptide/routes/utils/tokens.py
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
def decode_auth_token(token: str,
                      is_refresh: bool = False) -> 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['sub']
    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
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
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