from datetime import datetime, timedelta, timezone from typing import Any from jose import jwt from passlib.context import CryptContext from app.core.config import get_settings pwd_context = CryptContext(schemes=["argon2"], deprecated="auto") def hash_password(password: str) -> str: return pwd_context.hash(password) def verify_password(password: str, password_hash: str) -> bool: return pwd_context.verify(password, password_hash) def create_token(subject: str, token_type: str, expires_delta: timedelta, claims: dict[str, Any] | None = None) -> str: settings = get_settings() now = datetime.now(timezone.utc) payload: dict[str, Any] = { "sub": subject, "typ": token_type, "iat": now, "exp": now + expires_delta, } if claims: payload.update(claims) return jwt.encode(payload, settings.jwt_secret, algorithm="HS256") def create_access_token(subject: str, permissions: list[str]) -> str: settings = get_settings() return create_token( subject, "access", timedelta(minutes=settings.jwt_access_token_minutes), {"permissions": permissions}, ) def create_refresh_token(subject: str) -> str: settings = get_settings() return create_token(subject, "refresh", timedelta(days=settings.jwt_refresh_token_days)) def decode_token(token: str) -> dict[str, Any]: return jwt.decode(token, get_settings().jwt_secret, algorithms=["HS256"])