41 lines
1.1 KiB
Python
41 lines
1.1 KiB
Python
# @/routers/auth.py
|
|
from fastapi import APIRouter, Depends, status, Response
|
|
from fastapi.security import OAuth2PasswordRequestForm
|
|
from sqlalchemy.orm import Session
|
|
|
|
from database import get_db
|
|
from schemas.auth import LoginRequest
|
|
from schemas.user import UserResponse
|
|
from exceptions import UnauthorizedError
|
|
from crud.user import get_user_by_email
|
|
from auth.security import verify_password, create_access_token
|
|
|
|
|
|
router = APIRouter(prefix="/auth", tags=["Authentication"])
|
|
|
|
|
|
|
|
|
|
@router.post("/login", response_model=UserResponse, status_code=status.HTTP_200_OK)
|
|
def login(
|
|
data: LoginRequest,
|
|
response: Response,
|
|
db: Session = Depends(get_db)
|
|
):
|
|
user = get_user_by_email(db, email=data.username)
|
|
|
|
if not user or not verify_password(data.password, user.password):
|
|
raise UnauthorizedError("Wrong username or password")
|
|
|
|
access_token = create_access_token(data={"sub": str(user.id)})
|
|
|
|
response.set_cookie(
|
|
key="access_token",
|
|
value=access_token,
|
|
httponly=True, # Schutz gegen XSS
|
|
secure=False, # Im local dev (HTTP) auf False, auf Prod (HTTPS) auf True
|
|
samesite="lax",
|
|
)
|
|
|
|
return user
|