"""Password hashing, access tokens (JWT) and opaque single-use tokens (refresh, password reset).""" import hashlib import secrets from datetime import UTC, datetime, timedelta from uuid import UUID import jwt from argon2 import PasswordHasher from argon2.exceptions import InvalidHashError, VerificationError from app.core.config import get_settings from app.core.errors import Unauthenticated _hasher = PasswordHasher() _ALGORITHM = "HS256" def hash_password(password: str) -> str: return _hasher.hash(password) def verify_password(password: str, password_hash: str | None) -> bool: if not password_hash: return False try: return _hasher.verify(password_hash, password) except (VerificationError, InvalidHashError): return False def create_access_token(account_id: UUID) -> tuple[str, int]: """Returns (token, expires_in_seconds).""" settings = get_settings() now = datetime.now(UTC) claims = {"sub": str(account_id), "typ": "access", "iat": now, "exp": now + timedelta(seconds=settings.access_token_ttl_s)} return jwt.encode(claims, settings.jwt_secret, algorithm=_ALGORITHM), settings.access_token_ttl_s def decode_access_token(token: str) -> UUID: try: claims = jwt.decode(token, get_settings().jwt_secret, algorithms=[_ALGORITHM]) if claims.get("typ") != "access": raise Unauthenticated() return UUID(claims["sub"]) except (jwt.PyJWTError, KeyError, ValueError) as exc: raise Unauthenticated() from exc def new_opaque_token() -> str: return secrets.token_urlsafe(48) def hash_token(token: str) -> str: """Opaque tokens are stored only as SHA-256 hashes.""" return hashlib.sha256(token.encode()).hexdigest()