API Users wit Cookies
Sorry for the wrong branch
This commit is contained in:
1 parent
8b70ed1550
commit
a36749d788
15 files changed
+494
-2
No files matched your search
@@ -0,0 +1,40 @@
|
||||
# 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 UserAlreadyExistsError, UserNotFoundError
|
||||
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
|
||||
Reference in new issue
Block a user