Add per-device active sessions with revocation (#69)

Replaces the stateless signed-cookie session (bare user_id) with a
real server-side sessions table -- the cookie now just carries an
opaque session id, resolved against the DB on every request. Each
session records IP address (respects X-Forwarded-For), a parsed
device label, and last-seen time (throttled updates, not written on
every request).

New GET/DELETE /api/auth/sessions endpoints and an "Active sessions"
section in Profile settings let a user see every device they're
logged in from and revoke one they don't recognize -- including their
own current session, which just signs them out.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
2026-08-28 20:22:50 -06:00
co-authored by Claude Sonnet 5
parent 278f8bb995
commit b26643527d
15 changed files with 554 additions and 14 deletions
+14 -3
View File
@@ -8,6 +8,7 @@ from sqlalchemy.orm import selectinload
from app.database import get_db
from app.models import RoomMembership, RoomRole, User
from app.services.bot_service import resolve_token
from app.services.session_service import resolve_session
_ROLE_RANK = {RoomRole.member: 0, RoomRole.admin: 1, RoomRole.owner: 2}
@@ -29,16 +30,26 @@ async def get_current_user(
request.state.api_token = token
return user
user_id = request.session.get("user_id")
if not user_id:
session_id = request.session.get("session_id")
if not session_id:
raise HTTPException(status_code=401, detail="Not authenticated")
# #69: a session row, not a bare user_id -- resolve_session is also
# where a revoked session (this endpoint's own DELETE, or another
# device's "sign out") actually takes effect, since there's no other
# per-request check of that state.
session = await resolve_session(db, uuid.UUID(session_id))
if session is None:
request.session.clear()
raise HTTPException(status_code=401, detail="Not authenticated")
request.state.session_id = session.id
# Eager-loaded so UserRead.active_custom_theme (app/schemas/user.py) can
# be read without a MissingGreenlet -- selectinload skips the second
# query entirely when active_custom_theme_id is null (the common case),
# so this costs nothing for users who've never set a custom theme.
user = await db.get(
User, uuid.UUID(user_id), options=[selectinload(User.active_custom_theme)]
User, session.user_id, options=[selectinload(User.active_custom_theme)]
)
if user is None or not user.is_active:
request.session.clear()