31 lines
1.0 KiB
Python
31 lines
1.0 KiB
Python
from datetime import datetime, timezone
|
|
|
|
from fastapi import Cookie, Depends, HTTPException, status
|
|
from sqlalchemy import select
|
|
from sqlalchemy.ext.asyncio import AsyncSession
|
|
|
|
from app.db import get_db
|
|
from app.models.auth_session import AuthSession, hash_token
|
|
from app.models.user import User
|
|
|
|
SESSION_COOKIE_NAME = "qm_session"
|
|
|
|
|
|
async def get_current_user(
|
|
qm_session: str | None = Cookie(default=None),
|
|
db: AsyncSession = Depends(get_db),
|
|
) -> User:
|
|
if qm_session is None:
|
|
raise HTTPException(status.HTTP_401_UNAUTHORIZED, "not authenticated")
|
|
|
|
token_hash = hash_token(qm_session)
|
|
result = await db.execute(select(AuthSession).where(AuthSession.token_hash == token_hash))
|
|
session = result.scalar_one_or_none()
|
|
if session is None or session.expires_at < datetime.now(timezone.utc):
|
|
raise HTTPException(status.HTTP_401_UNAUTHORIZED, "session expired")
|
|
|
|
user = await db.get(User, session.user_id)
|
|
if user is None:
|
|
raise HTTPException(status.HTTP_401_UNAUTHORIZED, "user not found")
|
|
return user
|