from datetime import datetime, timedelta, timezone from typing import Any, Dict, Optional from fastapi import HTTPException, status from fastapi.security import OAuth2PasswordBearer from jose import JWTError, jwt from app.core.config import settings ALGORITHM = "HS256" oauth2_scheme = OAuth2PasswordBearer(tokenUrl="/api/v1/auth/login", scheme_name="Bearer") def create_access_token(*, subject: str, role: str, expires_delta: Optional[timedelta] = None) -> str: expire = datetime.now(timezone.utc) + (expires_delta or timedelta(minutes=settings.JWT_EXPIRE_MINUTES)) to_encode: Dict[str, Any] = {"sub": subject, "role": role, "exp": expire} return jwt.encode(to_encode, settings.JWT_SECRET_KEY, algorithm=ALGORITHM) def decode_access_token(token: str) -> Dict[str, Any]: try: payload = jwt.decode(token, settings.JWT_SECRET_KEY, algorithms=[ALGORITHM]) except JWTError as exc: raise HTTPException( status_code=status.HTTP_401_UNAUTHORIZED, detail="Could not validate credentials", headers={"WWW-Authenticate": "Bearer"}, ) from exc return payload