2020-05-10 17:08:18 +02:00
|
|
|
from datetime import datetime, timedelta
|
2021-01-02 19:28:03 +01:00
|
|
|
from typing import Optional
|
2020-05-10 17:08:18 +02:00
|
|
|
|
|
|
|
import jwt
|
|
|
|
from flask import current_app
|
|
|
|
|
2022-09-15 13:14:55 +02:00
|
|
|
from fittrackee.utils import clean
|
|
|
|
|
2020-05-10 17:08:18 +02:00
|
|
|
|
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']
|
2020-05-10 17:08:18 +02:00
|
|
|
)
|
2021-01-02 19:28:03 +01:00
|
|
|
expiration_seconds: float = (
|
|
|
|
current_app.config['PASSWORD_TOKEN_EXPIRATION_SECONDS']
|
2020-05-10 17:08:18 +02:00
|
|
|
if password_reset
|
2021-01-02 19:28:03 +01:00
|
|
|
else current_app.config['TOKEN_EXPIRATION_SECONDS']
|
2020-05-10 17:08:18 +02:00
|
|
|
)
|
2022-08-03 20:38:26 +02:00
|
|
|
now = datetime.utcnow()
|
2020-05-10 17:08:18 +02:00
|
|
|
payload = {
|
2022-08-03 20:38:26 +02:00
|
|
|
'exp': now
|
2020-05-10 17:08:18 +02:00
|
|
|
+ timedelta(days=expiration_days, seconds=expiration_seconds),
|
2022-08-03 20:38:26 +02:00
|
|
|
'iat': now,
|
2020-05-10 17:08:18 +02:00
|
|
|
'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',
|
2020-05-10 17:08:18 +02:00
|
|
|
)
|
|
|
|
|
|
|
|
|
2021-01-02 19:28:03 +01:00
|
|
|
def decode_user_token(auth_token: str) -> int:
|
|
|
|
"""
|
|
|
|
Return user id from token
|
|
|
|
"""
|
2020-12-25 19:35:15 +01:00
|
|
|
payload = jwt.decode(
|
|
|
|
auth_token,
|
2021-01-02 19:28:03 +01:00
|
|
|
current_app.config['SECRET_KEY'],
|
2020-12-25 19:35:15 +01:00
|
|
|
algorithms=['HS256'],
|
|
|
|
)
|
2020-05-10 17:08:18 +02:00
|
|
|
return payload['sub']
|
2022-09-15 13:14:55 +02:00
|
|
|
|
|
|
|
|
|
|
|
def clean_blacklisted_tokens(days: int) -> int:
|
|
|
|
"""
|
|
|
|
Delete blacklisted tokens expired for more than provided number of days
|
|
|
|
"""
|
|
|
|
sql = """
|
|
|
|
DELETE FROM blacklisted_tokens
|
2023-10-02 18:57:53 +02:00
|
|
|
WHERE blacklisted_tokens.expired_at < :limit;
|
2022-09-15 13:14:55 +02:00
|
|
|
"""
|
|
|
|
return clean(sql, days)
|