58 lines
1.4 KiB
Python
58 lines
1.4 KiB
Python
"""
|
|
Dépendances FastAPI pour injection et authentification.
|
|
"""
|
|
|
|
from fastapi import Depends, HTTPException, status
|
|
from fastapi.security import OAuth2PasswordBearer
|
|
from sqlalchemy.orm import Session
|
|
from . import models
|
|
from .auth import verify_token
|
|
from .database import SessionLocal
|
|
|
|
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")
|
|
|
|
|
|
def get_db():
|
|
"""Dépendance pour obtenir une session de base de données"""
|
|
db = SessionLocal()
|
|
try:
|
|
yield db
|
|
finally:
|
|
db.close()
|
|
|
|
|
|
async def get_current_voter(
|
|
token: str = Depends(oauth2_scheme),
|
|
db: Session = Depends(get_db)
|
|
) -> models.Voter:
|
|
"""
|
|
Dépendance pour récupérer l'électeur actuel.
|
|
Valide le token JWT et retourne l'électeur.
|
|
"""
|
|
payload = verify_token(token)
|
|
|
|
if payload is None:
|
|
raise HTTPException(
|
|
status_code=status.HTTP_401_UNAUTHORIZED,
|
|
detail="Invalid or expired token"
|
|
)
|
|
|
|
voter_id = payload.get("voter_id")
|
|
if voter_id is None:
|
|
raise HTTPException(
|
|
status_code=status.HTTP_401_UNAUTHORIZED,
|
|
detail="Invalid token"
|
|
)
|
|
|
|
voter = db.query(models.Voter).filter(
|
|
models.Voter.id == voter_id
|
|
).first()
|
|
|
|
if voter is None:
|
|
raise HTTPException(
|
|
status_code=status.HTTP_401_UNAUTHORIZED,
|
|
detail="Voter not found"
|
|
)
|
|
|
|
return voter
|