backend
This commit is contained in:
commit
d7666f7b2c
44 changed files with 2246 additions and 0 deletions
55
backend/core/security.py
Normal file
55
backend/core/security.py
Normal file
|
@ -0,0 +1,55 @@
|
|||
# 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()}")
|
Loading…
Add table
Add a link
Reference in a new issue