mirror of
https://git.victorphan.net/basketballcantho/ten-project.git
synced 2026-08-05 13:23:10 +07:00
hoàn thành phần Authentication
This commit is contained in:
@@ -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
|
||||
Reference in New Issue
Block a user