CLI - add command to clean blacklisted tokens
This commit is contained in:
@ -1,3 +1,4 @@
|
||||
import logging
|
||||
from typing import Optional
|
||||
|
||||
import click
|
||||
@ -5,6 +6,12 @@ import click
|
||||
from fittrackee.cli.app import app
|
||||
from fittrackee.users.exceptions import UserNotFoundException
|
||||
from fittrackee.users.utils.admin import UserManagerService
|
||||
from fittrackee.users.utils.token import clean_blacklisted_tokens
|
||||
|
||||
handler = logging.StreamHandler()
|
||||
logger = logging.getLogger('fittrackee_clean_blacklisted_tokens')
|
||||
logger.setLevel(logging.INFO)
|
||||
logger.addHandler(handler)
|
||||
|
||||
|
||||
@click.group(name='users')
|
||||
@ -60,3 +67,16 @@ def manage_user(
|
||||
)
|
||||
except Exception as e:
|
||||
click.echo(f'An error occurred: {e}', err=True)
|
||||
|
||||
|
||||
@users_cli.command('clean_tokens')
|
||||
@click.option('--days', type=int, required=True, help='Number of days.')
|
||||
def clean(
|
||||
days: int,
|
||||
) -> None:
|
||||
"""
|
||||
Clean blacklisted tokens expired for more than provided number of days.
|
||||
"""
|
||||
with app.app_context():
|
||||
deleted_rows = clean_blacklisted_tokens(days)
|
||||
logger.info(f'Blacklisted tokens deleted: {deleted_rows}.')
|
||||
|
@ -244,11 +244,22 @@ class BlacklistedToken(BaseModel):
|
||||
|
||||
id = db.Column(db.Integer, primary_key=True, autoincrement=True)
|
||||
token = db.Column(db.String(500), unique=True, nullable=False)
|
||||
expired_at = db.Column(db.Integer, nullable=False)
|
||||
blacklisted_on = db.Column(db.DateTime, nullable=False)
|
||||
|
||||
def __init__(self, token: str) -> None:
|
||||
def __init__(
|
||||
self, token: str, blacklisted_on: Optional[datetime] = None
|
||||
) -> None:
|
||||
payload = jwt.decode(
|
||||
token,
|
||||
current_app.config['SECRET_KEY'],
|
||||
algorithms=['HS256'],
|
||||
)
|
||||
self.token = token
|
||||
self.blacklisted_on = datetime.utcnow()
|
||||
self.expired_at = payload['exp']
|
||||
self.blacklisted_on = (
|
||||
blacklisted_on if blacklisted_on else datetime.utcnow()
|
||||
)
|
||||
|
||||
@classmethod
|
||||
def check(cls, auth_token: str) -> bool:
|
||||
|
@ -4,6 +4,8 @@ from typing import Optional
|
||||
import jwt
|
||||
from flask import current_app
|
||||
|
||||
from fittrackee.utils import clean
|
||||
|
||||
|
||||
def get_user_token(
|
||||
user_id: int, password_reset: Optional[bool] = False
|
||||
@ -45,3 +47,14 @@ def decode_user_token(auth_token: str) -> int:
|
||||
algorithms=['HS256'],
|
||||
)
|
||||
return payload['sub']
|
||||
|
||||
|
||||
def clean_blacklisted_tokens(days: int) -> int:
|
||||
"""
|
||||
Delete blacklisted tokens expired for more than provided number of days
|
||||
"""
|
||||
sql = """
|
||||
DELETE FROM blacklisted_tokens
|
||||
WHERE blacklisted_tokens.expired_at < %(limit)s;
|
||||
"""
|
||||
return clean(sql, days)
|
||||
|
Reference in New Issue
Block a user