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:
23
backend/app/session_cleanup.py
Normal file
23
backend/app/session_cleanup.py
Normal 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
|
||||
Reference in New Issue
Block a user