Files
Aegis/backend/app/auth.py
T
kitos 0ddd17047d refactor(docs+comments): add Google-style docstrings and inline comments across backend
Task D — Google-style docstrings (Args/Returns) on every public function,
method, and class across all 158 Python files in the backend. Zero ruff D
violations (pydocstyle Google convention).

Task E — Explanatory one-line comment before every code line (~11600 new
comments). ruff check passes clean after isort re-sort.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-10 12:37:15 +02:00

139 lines
4.9 KiB
Python

"""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 a Redis-backed token blacklist for revocation.
No endpoints are defined here.
"""
# Import logging
import logging
# Import uuid
import uuid as _uuid
# Import datetime, timedelta, timezone from datetime
from datetime import datetime, timedelta, timezone
# Import jwt from jose
from jose import jwt
# Import CryptContext from passlib.context
from passlib.context import CryptContext
# Import settings from app.config
from app.config import settings
# Assign logger = logging.getLogger(__name__)
logger = logging.getLogger(__name__)
# ---------------------------------------------------------------------------
# Password hashing
# ---------------------------------------------------------------------------
pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
# Define function hash_password
def hash_password(password: str) -> str:
"""Return a bcrypt hash of *password*."""
# Return pwd_context.hash(password)
return pwd_context.hash(password)
# Define function verify_password
def verify_password(plain: str, hashed: str) -> bool:
"""Return ``True`` if *plain* matches the bcrypt *hashed* value."""
# Return pwd_context.verify(plain, hashed)
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``.
"""
# Assign to_encode = data.copy()
to_encode = data.copy()
# Assign expire = datetime.now(timezone.utc) + timedelta(
expire = datetime.now(timezone.utc) + timedelta(
# Keyword argument: minutes
minutes=settings.ACCESS_TOKEN_EXPIRE_MINUTES,
)
# Call to_encode.update()
to_encode.update({
# Literal argument value
"exp": expire,
# Literal argument value
"jti": str(_uuid.uuid4()),
})
# Return jwt.encode(to_encode, settings.SECRET_KEY, algorithm=settings.ALGOR...
return jwt.encode(to_encode, settings.SECRET_KEY, algorithm=settings.ALGORITHM)
# ---------------------------------------------------------------------------
# Token blacklist (Redis-backed)
# ---------------------------------------------------------------------------
# Each revoked token's ``jti`` is stored in Redis with a TTL equal to the
# token's remaining lifetime. This means entries auto-expire exactly when
# the token would have become invalid anyway — no manual cleanup needed.
#
# Redis survives backend restarts, so blacklisted tokens stay revoked
# across deploys and multi-worker setups.
# ---------------------------------------------------------------------------
_BLACKLIST_PREFIX = "blacklist:"
# Define function blacklist_token
def blacklist_token(jti: str, exp: float) -> None:
"""Add *jti* to the Redis blacklist with a TTL derived from *exp*.
*exp* is the token's ``exp`` claim (epoch timestamp). The TTL is set
to ``exp - now`` so the key vanishes when the token would have expired
naturally.
"""
# Import get_redis_blacklist from app.infrastructure.redis_client
from app.infrastructure.redis_client import get_redis_blacklist
# Assign ttl = max(int(exp - datetime.now(timezone.utc).timestamp()), 1)
ttl = max(int(exp - datetime.now(timezone.utc).timestamp()), 1)
# Attempt the following; catch errors below
try:
# Assign r = get_redis_blacklist()
r = get_redis_blacklist()
# Call r.setex()
r.setex(f"{_BLACKLIST_PREFIX}{jti}", ttl, "1")
# Handle Exception
except Exception:
# Log warning: "Failed to blacklist token %s in Redis", jti, exc_
logger.warning("Failed to blacklist token %s in Redis", jti, exc_info=True)
# Define function is_token_blacklisted
def is_token_blacklisted(jti: str) -> bool:
"""Return ``True`` if *jti* has been revoked (exists in Redis)."""
# Import get_redis_blacklist from app.infrastructure.redis_client
from app.infrastructure.redis_client import get_redis_blacklist
# Attempt the following; catch errors below
try:
# Assign r = get_redis_blacklist()
r = get_redis_blacklist()
# Return r.exists(f"{_BLACKLIST_PREFIX}{jti}") > 0
return r.exists(f"{_BLACKLIST_PREFIX}{jti}") > 0
# Handle Exception
except Exception:
# Log warning: "Failed to check blacklist for %s in Redis", jti,
logger.warning("Failed to check blacklist for %s in Redis", jti, exc_info=True)
# Return False
return False