backend
This commit is contained in:
commit
d7666f7b2c
44 changed files with 2246 additions and 0 deletions
45
backend/routers/auth.py
Normal file
45
backend/routers/auth.py
Normal file
|
@ -0,0 +1,45 @@
|
|||
from fastapi import APIRouter, Depends, HTTPException, status
|
||||
from sqlalchemy.orm import Session
|
||||
from fastapi.security import OAuth2PasswordRequestForm
|
||||
from datetime import timedelta
|
||||
|
||||
# Importations ABSOLUES
|
||||
from core.database import get_db
|
||||
from core.security import verify_password, create_access_token
|
||||
from crud import user as crud_user # Était déjà correcte pour "crud", mais assure la cohérence
|
||||
from schemas import user as schemas_user
|
||||
from core.config import settings
|
||||
from core.hashing import verify_password
|
||||
|
||||
router = APIRouter(
|
||||
prefix="/auth",
|
||||
tags=["Authentication"],
|
||||
responses={404: {"description": "Not found"}},
|
||||
)
|
||||
|
||||
ACCESS_TOKEN_EXPIRE_MINUTES = settings.ACCESS_TOKEN_EXPIRE_MINUTES
|
||||
|
||||
@router.post("/register", response_model=schemas_user.UserResponse, status_code=status.HTTP_201_CREATED)
|
||||
def register_user(user: schemas_user.UserCreate, db: Session = Depends(get_db)):
|
||||
db_user = crud_user.get_user_by_email(db, email=user.email)
|
||||
if db_user:
|
||||
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="Email déjà enregistré.")
|
||||
|
||||
new_user = crud_user.create_user(db=db, user=user)
|
||||
return new_user
|
||||
|
||||
@router.post("/login", response_model=dict)
|
||||
def login_for_access_token(form_data: OAuth2PasswordRequestForm = Depends(), db: Session = Depends(get_db)):
|
||||
user = crud_user.get_user_by_email(db, email=form_data.username)
|
||||
if not user or not verify_password(form_data.password, user.hashed_password):
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail="Identifiants incorrects",
|
||||
headers={"WWW-Authenticate": "Bearer"},
|
||||
)
|
||||
|
||||
access_token_expires = timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)
|
||||
access_token = create_access_token(
|
||||
data={"sub": user.email}, expires_delta=access_token_expires
|
||||
)
|
||||
return {"access_token": access_token, "token_type": "bearer"}
|
Loading…
Add table
Add a link
Reference in a new issue