""" Security utilities: password hashing and JWT token management. This module provides pure functions for: - Hashing and verifying passwords using bcrypt via passlib. - Creating JWT access tokens using python-jose. - Managing an in-memory token blacklist for revocation. No endpoints are defined here. """ import threading import uuid as _uuid from datetime import datetime, timedelta, timezone from jose import jwt from passlib.context import CryptContext from app.config import settings # --------------------------------------------------------------------------- # Password hashing # --------------------------------------------------------------------------- pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto") def hash_password(password: str) -> str: """Return a bcrypt hash of *password*.""" return pwd_context.hash(password) def verify_password(plain: str, hashed: str) -> bool: """Return ``True`` if *plain* matches the bcrypt *hashed* value.""" return pwd_context.verify(plain, hashed) # --------------------------------------------------------------------------- # JWT tokens # --------------------------------------------------------------------------- def create_access_token(data: dict) -> str: """Create a signed JWT containing *data* plus ``exp`` and ``jti`` claims. - ``jti`` (JWT ID): unique identifier that enables token revocation. - ``exp``: expiration timestamp based on ``ACCESS_TOKEN_EXPIRE_MINUTES``. """ to_encode = data.copy() expire = datetime.now(timezone.utc) + timedelta( minutes=settings.ACCESS_TOKEN_EXPIRE_MINUTES, ) to_encode.update({ "exp": expire, "jti": str(_uuid.uuid4()), }) return jwt.encode(to_encode, settings.SECRET_KEY, algorithm=settings.ALGORITHM) # --------------------------------------------------------------------------- # Token blacklist (in-memory) # --------------------------------------------------------------------------- # Stores (jti, expiry_timestamp) tuples. Entries are automatically purged # once they are past their original expiry (the token would be invalid # anyway at that point). Thread-safe via a simple lock. # # For multi-worker / multi-process deployments, consider replacing this # with a shared store like Redis. # --------------------------------------------------------------------------- _blacklist: dict[str, float] = {} # jti → expiry epoch _blacklist_lock = threading.Lock() def blacklist_token(jti: str, exp: float) -> None: """Add *jti* to the blacklist until it naturally expires at *exp*.""" with _blacklist_lock: _blacklist[jti] = exp _cleanup_blacklist() def is_token_blacklisted(jti: str) -> bool: """Return ``True`` if *jti* has been revoked.""" with _blacklist_lock: return jti in _blacklist def _cleanup_blacklist() -> None: """Remove entries whose tokens have already expired (caller holds lock).""" now = datetime.now(timezone.utc).timestamp() expired = [k for k, exp in _blacklist.items() if exp < now] for k in expired: del _blacklist[k]