39 lines
1.1 KiB
Python
39 lines
1.1 KiB
Python
from datetime import UTC, datetime
|
|
|
|
from fastapi import Depends, HTTPException
|
|
from fastapi.security import OAuth2AuthorizationCodeBearer
|
|
from pydantic import ValidationError
|
|
from sqlalchemy.ext.asyncio import AsyncSession
|
|
|
|
from core.secrets import decode_jwt
|
|
from db.models import User
|
|
from db.session import get_db
|
|
from repositories.users import UserRepository
|
|
from schemas.jwt import JWTPayload
|
|
|
|
oauth_scheme = OAuth2AuthorizationCodeBearer(
|
|
authorizationUrl="/auth/login", tokenUrl="/auth/refresh"
|
|
)
|
|
|
|
|
|
async def get_current_user(
|
|
session: AsyncSession = Depends(get_db), token: str = Depends(oauth_scheme)
|
|
) -> User | None:
|
|
content = decode_jwt(token)
|
|
|
|
try:
|
|
payload = JWTPayload.model_validate(content)
|
|
except ValidationError:
|
|
raise HTTPException(status_code=401, detail="Invalid credentials") from None
|
|
|
|
if payload.exp < datetime.now(UTC).timestamp():
|
|
raise HTTPException(status_code=401, detail="Access token expired")
|
|
|
|
repo = UserRepository(session)
|
|
user = await repo.get_user_by_id(int(payload.sub))
|
|
|
|
if not user:
|
|
raise HTTPException(status_code=401, detail="User not found")
|
|
|
|
return user
|