"""Password hashing (argon2) and JWT access/refresh tokens.""" from __future__ import annotations import uuid from datetime import UTC, datetime, timedelta from typing import Any, Literal import jwt from argon2 import PasswordHasher from argon2.exceptions import InvalidHashError, VerifyMismatchError from core.config import get_settings _hasher = PasswordHasher() TokenType = Literal["access", "refresh", "stepup"] class TokenError(Exception): pass def hash_password(password: str) -> str: return _hasher.hash(password) def verify_password(password: str, password_hash: str) -> bool: try: return _hasher.verify(password_hash, password) except (VerifyMismatchError, InvalidHashError): return False def issue_token( user_id: uuid.UUID, tenant_id: uuid.UUID | None, kind: TokenType, ttl: timedelta | None = None, extra: dict[str, Any] | None = None, ) -> str: s = get_settings() if ttl is None: ttl = ( timedelta(minutes=s.access_token_minutes) if kind == "access" else timedelta(days=s.refresh_token_days) ) now = datetime.now(UTC) payload: dict[str, Any] = { "sub": str(user_id), "tid": str(tenant_id) if tenant_id else None, "typ": kind, "iat": int(now.timestamp()), "exp": int((now + ttl).timestamp()), "jti": str(uuid.uuid4()), } if extra: payload.update(extra) return jwt.encode(payload, s.jwt_secret.get_secret_value(), algorithm=s.jwt_algorithm) def decode_token(token: str, expected: TokenType) -> dict[str, Any]: s = get_settings() try: payload: dict[str, Any] = jwt.decode( token, s.jwt_secret.get_secret_value(), algorithms=[s.jwt_algorithm] ) except jwt.PyJWTError as exc: raise TokenError(str(exc)) from exc if payload.get("typ") != expected: raise TokenError(f"expected {expected} token") return payload