55 lines
No EOL
2 KiB
Python
55 lines
No EOL
2 KiB
Python
# backend/core/security.py
|
|
from datetime import datetime, timedelta
|
|
from typing import Optional
|
|
|
|
from jose import JWTError, jwt
|
|
|
|
# Importations pour get_current_user
|
|
from fastapi import Depends, HTTPException, status
|
|
from fastapi.security import OAuth2PasswordBearer
|
|
from sqlalchemy.orm import Session
|
|
from schemas.token import TokenData
|
|
from crud import user as crud_user
|
|
from core.database import get_db
|
|
|
|
# Importation ABSOLUE
|
|
from core.config import settings
|
|
|
|
# Nouvelle importation pour les fonctions de hachage
|
|
from core.hashing import verify_password, get_password_hash # <-- NOUVEAU
|
|
|
|
# Schéma OAuth2
|
|
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="auth/login")
|
|
|
|
def create_access_token(data: dict, expires_delta: Optional[timedelta] = None):
|
|
to_encode = data.copy()
|
|
if expires_delta:
|
|
expire = datetime.utcnow() + expires_delta
|
|
else:
|
|
expire = datetime.utcnow() + timedelta(minutes=settings.ACCESS_TOKEN_EXPIRE_MINUTES)
|
|
to_encode.update({"exp": expire})
|
|
encoded_jwt = jwt.encode(to_encode, settings.SECRET_KEY, algorithm=settings.ALGORITHM)
|
|
return encoded_jwt
|
|
|
|
# Fonction get_current_user
|
|
async def get_current_user(token: str = Depends(oauth2_scheme), db: Session = Depends(get_db)):
|
|
credentials_exception = HTTPException(
|
|
status_code=status.HTTP_401_UNAUTHORIZED,
|
|
detail="Could not validate credentials",
|
|
headers={"WWW-Authenticate": "Bearer"},
|
|
)
|
|
try:
|
|
payload = jwt.decode(token, settings.SECRET_KEY, algorithms=[settings.ALGORITHM])
|
|
username: str = payload.get("sub")
|
|
if username is None:
|
|
raise credentials_exception
|
|
token_data = TokenData(email=username)
|
|
except JWTError:
|
|
raise credentials_exception
|
|
user = crud_user.get_user_by_email(db, email=token_data.email)
|
|
if user is None:
|
|
raise credentials_exception
|
|
return user
|
|
|
|
# LIGNE DE DÉBOGAGE CORRECTEMENT INDENTÉE (au niveau du module)
|
|
print(f"DEBUG_SECURITY: Noms définis dans core.security.py : {dir()}") |