FitTrackee/fittrackee/users/utils/token.py

48 lines
1.2 KiB
Python
Raw Normal View History

from datetime import datetime, timedelta
2021-01-02 19:28:03 +01:00
from typing import Optional
import jwt
from flask import current_app
2021-01-02 19:28:03 +01:00
def get_user_token(
user_id: int, password_reset: Optional[bool] = False
) -> str:
"""
Return authentication token for a given user.
Token expiration time depends on token type (authentication or password
reset)
"""
expiration_days: float = (
0.0 if password_reset else current_app.config['TOKEN_EXPIRATION_DAYS']
)
2021-01-02 19:28:03 +01:00
expiration_seconds: float = (
current_app.config['PASSWORD_TOKEN_EXPIRATION_SECONDS']
if password_reset
2021-01-02 19:28:03 +01:00
else current_app.config['TOKEN_EXPIRATION_SECONDS']
)
2022-08-03 20:38:26 +02:00
now = datetime.utcnow()
payload = {
2022-08-03 20:38:26 +02:00
'exp': now
+ timedelta(days=expiration_days, seconds=expiration_seconds),
2022-08-03 20:38:26 +02:00
'iat': now,
'sub': user_id,
}
return jwt.encode(
2020-09-16 11:09:32 +02:00
payload,
2021-01-02 19:28:03 +01:00
current_app.config['SECRET_KEY'],
2020-09-16 11:09:32 +02:00
algorithm='HS256',
)
2021-01-02 19:28:03 +01:00
def decode_user_token(auth_token: str) -> int:
"""
Return user id from token
"""
payload = jwt.decode(
auth_token,
2021-01-02 19:28:03 +01:00
current_app.config['SECRET_KEY'],
algorithms=['HS256'],
)
return payload['sub']