feat: periodically sweep expired auth sessions

auth_sessions rows were never deleted after expiry, only rejected
on read. Adds a background sweep (every 30 min) in the app lifespan,
plus a tested pure delete_expired_sessions() function.
This commit is contained in:
Indiana
2026-07-21 03:43:34 +00:00
parent 0756e677b9
commit 7f0775c8c3
3 changed files with 91 additions and 2 deletions

View File

@@ -0,0 +1,23 @@
"""Periodic sweep of expired auth_sessions rows.
get_current_user (app/deps.py) already rejects expired sessions on read, but
never deletes them — left alone, auth_sessions grows forever. The lifespan
in app/main.py runs delete_expired_sessions on a timer to keep the table
bounded.
"""
from datetime import datetime, timezone
from sqlalchemy import delete
from sqlalchemy.ext.asyncio import AsyncSession
from app.models.auth_session import AuthSession
async def delete_expired_sessions(db: AsyncSession) -> int:
"""Deletes expired auth_sessions rows. Returns the number deleted."""
result = await db.execute(
delete(AuthSession).where(AuthSession.expires_at < datetime.now(timezone.utc))
)
await db.commit()
return result.rowcount