mirror of
https://git.victorphan.net/basketballcantho/ten-project.git
synced 2026-08-05 21:13:10 +07:00
37 lines
940 B
Python
37 lines
940 B
Python
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
|