54 lines
1.7 KiB
Python
54 lines
1.7 KiB
Python
import uuid
|
|
|
|
import redis.asyncio as aioredis
|
|
from fastapi import Depends, Header, HTTPException, status
|
|
from sqlalchemy.ext.asyncio import AsyncSession
|
|
|
|
from src.core.redis import get_redis
|
|
from src.db.session import get_db
|
|
from src.models.models import User
|
|
from src.services import sessions as sessions_service
|
|
from src.services import users as users_service
|
|
|
|
|
|
async def get_current_user(
|
|
authorization: str | None = Header(default=None),
|
|
db: AsyncSession = Depends(get_db),
|
|
redis: aioredis.Redis = Depends(get_redis),
|
|
) -> User:
|
|
if not authorization or not authorization.lower().startswith("bearer "):
|
|
raise HTTPException(
|
|
status_code=status.HTTP_401_UNAUTHORIZED,
|
|
detail="unauthorized",
|
|
)
|
|
|
|
token = authorization.split(" ", 1)[1].strip()
|
|
if not token:
|
|
raise HTTPException(
|
|
status_code=status.HTTP_401_UNAUTHORIZED,
|
|
detail="unauthorized",
|
|
)
|
|
|
|
try:
|
|
user_id = await sessions_service.get_session_user_id(redis, token)
|
|
except (aioredis.RedisError, ConnectionError, OSError):
|
|
# Redis недоступен → не пропускаем запрос, отдаём 503.
|
|
raise HTTPException(
|
|
status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
|
|
detail="session store unavailable",
|
|
)
|
|
|
|
if user_id is None:
|
|
raise HTTPException(
|
|
status_code=status.HTTP_401_UNAUTHORIZED,
|
|
detail="unauthorized",
|
|
)
|
|
|
|
user = await users_service.get_user_by_id(db, user_id)
|
|
if user is None:
|
|
raise HTTPException(
|
|
status_code=status.HTTP_401_UNAUTHORIZED,
|
|
detail="unauthorized",
|
|
)
|
|
|
|
return user |