hoàn thành phần Authentication

This commit is contained in:
2026-03-31 14:15:32 +07:00
commit ebfa869a26
12 changed files with 389 additions and 0 deletions
+36
View File
@@ -0,0 +1,36 @@
from fastapi import Cookie, Depends, HTTPException, status
from jose import JWTError
from sqlalchemy.orm import Session
from .database import get_db
from .models import User
from .security import decode_access_token
def get_current_user(
access_token: str | None = Cookie(default=None),
db: Session = Depends(get_db),
) -> User:
"""
Reads the JWT from the HttpOnly `access_token` cookie,
validates it, and returns the authenticated User ORM object.
Raises 401 on any failure.
"""
credentials_exception = HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Not authenticated.",
)
if access_token is None:
raise credentials_exception
try:
user_id = decode_access_token(access_token)
except JWTError:
raise credentials_exception
user = db.get(User, user_id)
if user is None:
raise credentials_exception
return user