EXPLAIN на 8837 сообщениях и session expiry

This commit is contained in:
2026-10-01 03:14:07 +03:00
parent ba9ce69b48
commit 2b90834d03
7 changed files with 150 additions and 17 deletions
+16 -14
View File
@@ -11,6 +11,10 @@ from sqlalchemy.ext.asyncio import AsyncSession
from .db.models import SessionRow, User
from .db.session import get_db
import redis.asyncio as redis
redis_client = redis.from_url(os.getenv("REDIS_URL", "redis://redis:6379/0"))
SESSION_TTL = int(os.getenv("SESSION_TTL_SECONDS", "3600"))
@@ -46,6 +50,14 @@ def _unauthorized_bearer() -> HTTPException:
)
async def create_session(user_id: str) -> str:
token = generate_token()
await redis_client.setex(
f"session:{hash_token(token)}", SESSION_TTL, str(user_id)
)
return token
async def get_current_user(
authorization: str | None = Header(None, alias="Authorization"),
db: AsyncSession = Depends(get_db),
@@ -54,15 +66,10 @@ async def get_current_user(
raise _unauthorized_bearer()
token = authorization[7:]
token_hash = hash_token(token)
now = datetime.now(timezone.utc)
stmt = select(SessionRow).where(
SessionRow.token_hash == token_hash,
SessionRow.expires_at > now,
)
session = (await db.execute(stmt)).scalar_one_or_none()
if session is None:
user_id_raw = await redis_client.get(f"session:{token_hash}")
if user_id_raw is None:
raise _unauthorized_bearer()
user = await db.get(User, session.user_id)
user = await db.get(User, UUID(user_id_raw.decode()))
if user is None:
raise _unauthorized_bearer()
return user
@@ -72,9 +79,4 @@ async def revoke_current_session(authorization: str, db: AsyncSession) -> None:
if not authorization or not authorization.startswith("Bearer "):
raise _unauthorized_bearer()
token = authorization[7:]
result = await db.execute(
delete(SessionRow).where(SessionRow.token_hash == hash_token(token))
)
await db.commit()
if result.rowcount == 0:
raise _unauthorized_bearer()
await redis_client.delete(f"session:{hash_token(token)}")