# ============================================================ # auth.py — Authentification JWT + hachage bcrypt # Data Sentinel # ============================================================ from datetime import datetime, timedelta, timezone from fastapi import Depends, HTTPException, status from fastapi.security import OAuth2PasswordBearer from jose import jwt, JWTError from passlib.context import CryptContext from config import Config oauth2_scheme = OAuth2PasswordBearer(tokenUrl="auth/login") pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto") def verify_password(plain: str, hashed: str) -> bool: return pwd_context.verify(plain, hashed) def hash_password(plain: str) -> str: return pwd_context.hash(plain) def create_access_token(data: dict) -> str: payload = data.copy() payload["exp"] = datetime.now(timezone.utc) + timedelta(minutes=Config.TOKEN_EXPIRE_MINUTES) return jwt.encode(payload, Config.SECRET_KEY, algorithm=Config.ALGORITHM) def get_current_user(token: str = Depends(oauth2_scheme)) -> dict: """Décode le JWT et retourne l'utilisateur courant, sinon 401.""" creds_exc = HTTPException( status_code=status.HTTP_401_UNAUTHORIZED, detail="Identifiants invalides", headers={"WWW-Authenticate": "Bearer"}, ) try: payload = jwt.decode(token, Config.SECRET_KEY, algorithms=[Config.ALGORITHM]) username = payload.get("sub") if not username: raise creds_exc return {"username": username, "role": payload.get("role"), "id_user": payload.get("uid")} except JWTError: raise creds_exc def require_admin(user: dict = Depends(get_current_user)) -> dict: """Réserve l'accès aux administrateurs (403 sinon).""" if user.get("role") != "Admin": raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="Accès réservé aux administrateurs") return user