Coverage for app/services/sessions.py: 81%

149 statements  

« prev     ^ index     » next       coverage.py v7.14.1, created at 2026-10-31 11:18 +0000

1"""Durable session tracking service. 

2 

3Wraps all Postgres reads/writes for the `sessions` table. Each function manages 

4its own short-lived DB session via ``SessionLocal`` so callers (the async route 

5handlers in ``main.py``) stay thin. 

6 

7The opaque Redis token ``sid`` is the join key between this store and Redis. It 

8is treated as a server-only secret: it is used internally to build Redis keys 

9and to flag the caller's current session, but is never serialised to clients. 

10""" 

11 

12import logging 

13import uuid 

14from dataclasses import dataclass 

15from datetime import datetime, timedelta 

16from typing import Optional 

17 

18from sqlalchemy import delete, func, select, update 

19 

20from app.db.engine import SessionLocal 

21from app.db.models import SessionEndReason, SessionRecord, SessionStatus 

22from app.util.geoip import GeoLocation 

23from app.util.request_meta import DeviceInfo 

24from app.util.time import aware_utcnow 

25 

26logger = logging.getLogger(__name__) 

27 

28 

29@dataclass 

30class SessionView: 

31 """Detached, serialisable snapshot of a session row. 

32 

33 ``sid`` is included for internal use (Redis key + current-session flag) and 

34 must be stripped before returning to a client — see ``to_public_dict``. 

35 """ 

36 

37 id: uuid.UUID 

38 sid: str 

39 user_id: str 

40 created_at: datetime 

41 last_seen_at: datetime 

42 ended_at: Optional[datetime] 

43 end_reason: Optional[SessionEndReason] 

44 ip: Optional[str] 

45 user_agent: Optional[str] 

46 device_type: Optional[str] 

47 browser: Optional[str] 

48 os: Optional[str] 

49 location_city: Optional[str] 

50 location_country: Optional[str] 

51 location_lat: Optional[float] 

52 location_lng: Optional[float] 

53 

54 def status(self) -> SessionStatus: 

55 if self.ended_at is None: 

56 return SessionStatus.ACTIVE 

57 if self.end_reason == SessionEndReason.EXPIRED: 

58 return SessionStatus.EXPIRED 

59 return SessionStatus.ENDED 

60 

61 def to_public_dict(self, *, current: bool) -> dict: 

62 """Client-facing shape. Deliberately omits ``sid`` and ``user_id``.""" 

63 return { 

64 "id": str(self.id), 

65 "current": current, 

66 "status": self.status().value, 

67 "end_reason": self.end_reason.value if self.end_reason else None, 

68 "created_at": self.created_at.isoformat() if self.created_at else None, 

69 "last_seen_at": ( 

70 self.last_seen_at.isoformat() if self.last_seen_at else None 

71 ), 

72 "ended_at": self.ended_at.isoformat() if self.ended_at else None, 

73 "ip": self.ip, 

74 "device": { 

75 "type": self.device_type, 

76 "browser": self.browser, 

77 "os": self.os, 

78 "user_agent": self.user_agent, 

79 }, 

80 "location": { 

81 "city": self.location_city, 

82 "country": self.location_country, 

83 "lat": self.location_lat, 

84 "lng": self.location_lng, 

85 }, 

86 } 

87 

88 

89def _to_view(row: SessionRecord) -> SessionView: 

90 return SessionView( 

91 id=row.id, 

92 sid=row.sid, 

93 user_id=row.user_id, 

94 created_at=row.created_at, 

95 last_seen_at=row.last_seen_at, 

96 ended_at=row.ended_at, 

97 end_reason=row.end_reason, 

98 ip=row.ip, 

99 user_agent=row.user_agent, 

100 device_type=row.device_type, 

101 browser=row.browser, 

102 os=row.os, 

103 location_city=row.location_city, 

104 location_country=row.location_country, 

105 location_lat=row.location_lat, 

106 location_lng=row.location_lng, 

107 ) 

108 

109 

110def create_session( 

111 *, 

112 sid: str, 

113 user_id: str, 

114 ip: Optional[str], 

115 device: DeviceInfo, 

116 geo: GeoLocation, 

117 created_at: Optional[datetime] = None, 

118) -> None: 

119 """Insert a session row at login (called from /callback). 

120 

121 Best-effort: a DB failure here must not break authentication, so errors are 

122 logged and swallowed — the user is still logged in via Redis. 

123 """ 

124 now = created_at or aware_utcnow() 

125 try: 

126 with SessionLocal() as db: 

127 db.add( 

128 SessionRecord( 

129 sid=sid, 

130 user_id=user_id, 

131 created_at=now, 

132 last_seen_at=now, 

133 ip=ip, 

134 user_agent=device.user_agent, 

135 device_type=device.device_type, 

136 browser=device.browser, 

137 os=device.os, 

138 location_city=geo.city, 

139 location_country=geo.country, 

140 location_lat=geo.latitude, 

141 location_lng=geo.longitude, 

142 ) 

143 ) 

144 db.commit() 

145 except Exception as e: 

146 logger.error("Failed to record session for user %s: %s", user_id, e) 

147 

148 

149def touch_session(*, sid: str, interval_seconds: int) -> None: 

150 """Bump ``last_seen_at`` for an active session, throttled. 

151 

152 The update is gated in SQL to fire at most once per ``interval_seconds`` — 

153 ``/verify`` runs on nearly every request, so this avoids a write per call. 

154 Best-effort; never raises into the request path. 

155 """ 

156 now = aware_utcnow() 

157 try: 

158 with SessionLocal() as db: 

159 db.execute( 

160 update(SessionRecord) 

161 .where( 

162 SessionRecord.sid == sid, 

163 SessionRecord.ended_at.is_(None), 

164 SessionRecord.last_seen_at < now - _interval(interval_seconds), 

165 ) 

166 .values(last_seen_at=now) 

167 ) 

168 db.commit() 

169 except Exception as e: 

170 logger.error("Failed to touch session %s: %s", _redact(sid), e) 

171 

172 

173def end_session_by_sid(*, sid: str, reason: SessionEndReason) -> None: 

174 """Mark a session ended by its Redis token (called from /logout, /verify).""" 

175 _end_where(SessionRecord.sid == sid, reason=reason) 

176 

177 

178def end_session_by_id( 

179 *, session_id: uuid.UUID, user_id: str, reason: SessionEndReason 

180) -> Optional[str]: 

181 """Revoke a specific session owned by ``user_id``. 

182 

183 Returns the session's ``sid`` so the caller can delete the matching Redis 

184 keys, or ``None`` if no active session with that id belongs to the user. 

185 """ 

186 try: 

187 with SessionLocal() as db: 

188 row = db.execute( 

189 select(SessionRecord).where( 

190 SessionRecord.id == session_id, 

191 SessionRecord.user_id == user_id, 

192 ) 

193 ).scalar_one_or_none() 

194 

195 if row is None: 

196 return None 

197 

198 sid = row.sid 

199 if row.ended_at is None: 

200 row.ended_at = aware_utcnow() 

201 row.end_reason = reason 

202 db.commit() 

203 return sid 

204 except Exception as e: 

205 logger.error("Failed to revoke session %s: %s", session_id, e) 

206 return None 

207 

208 

209def end_other_sessions( 

210 *, user_id: str, keep_sid: str, reason: SessionEndReason 

211) -> list[str]: 

212 """End every active session for ``user_id`` except ``keep_sid``. 

213 

214 Returns the list of ``sid`` values that were ended so the caller can purge 

215 their Redis keys. 

216 """ 

217 try: 

218 with SessionLocal() as db: 

219 rows = ( 

220 db.execute( 

221 select(SessionRecord).where( 

222 SessionRecord.user_id == user_id, 

223 SessionRecord.ended_at.is_(None), 

224 SessionRecord.sid != keep_sid, 

225 ) 

226 ) 

227 .scalars() 

228 .all() 

229 ) 

230 now = aware_utcnow() 

231 sids = [] 

232 for row in rows: 

233 row.ended_at = now 

234 row.end_reason = reason 

235 sids.append(row.sid) 

236 db.commit() 

237 return sids 

238 except Exception as e: 

239 logger.error("Failed to revoke other sessions for %s: %s", user_id, e) 

240 return [] 

241 

242 

243def get_user_sessions(*, user_id: str) -> list[SessionView]: 

244 """Return all sessions for a user, most-recently-active first (detached).""" 

245 try: 

246 with SessionLocal() as db: 

247 rows = ( 

248 db.execute( 

249 select(SessionRecord) 

250 .where(SessionRecord.user_id == user_id) 

251 .order_by(SessionRecord.last_seen_at.desc()) 

252 ) 

253 .scalars() 

254 .all() 

255 ) 

256 return [_to_view(r) for r in rows] 

257 except Exception as e: 

258 logger.error("Failed to list sessions for %s: %s", user_id, e) 

259 return [] 

260 

261 

262def get_active_sessions(*, user_id: str) -> list[SessionView]: 

263 """Return the user's not-yet-ended sessions, most-recently-active first. 

264 

265 The set is naturally small (one row per live login), so it is returned 

266 unpaginated. Historic sessions are served by ``get_session_history``. 

267 """ 

268 try: 

269 with SessionLocal() as db: 

270 rows = ( 

271 db.execute( 

272 select(SessionRecord) 

273 .where( 

274 SessionRecord.user_id == user_id, 

275 SessionRecord.ended_at.is_(None), 

276 ) 

277 .order_by(SessionRecord.last_seen_at.desc()) 

278 ) 

279 .scalars() 

280 .all() 

281 ) 

282 return [_to_view(r) for r in rows] 

283 except Exception as e: 

284 logger.error("Failed to list active sessions for %s: %s", user_id, e) 

285 return [] 

286 

287 

288def get_session_history( 

289 *, user_id: str, limit: int, offset: int 

290) -> tuple[list[SessionView], int]: 

291 """Return a page of the user's ended sessions plus the total ended count. 

292 

293 Only sessions that have ended (logged out, revoked, or expired) are 

294 included; live sessions are served by ``get_active_sessions``. Rows are 

295 ordered most-recently-ended first, with ``id`` as a stable tie-breaker so 

296 limit/offset paging never overlaps or skips rows. 

297 """ 

298 try: 

299 with SessionLocal() as db: 

300 condition = ( 

301 SessionRecord.user_id == user_id, 

302 SessionRecord.ended_at.is_not(None), 

303 ) 

304 total = db.execute( 

305 select(func.count()).select_from(SessionRecord).where(*condition) 

306 ).scalar_one() 

307 rows = ( 

308 db.execute( 

309 select(SessionRecord) 

310 .where(*condition) 

311 .order_by(SessionRecord.ended_at.desc(), SessionRecord.id.desc()) 

312 .limit(limit) 

313 .offset(offset) 

314 ) 

315 .scalars() 

316 .all() 

317 ) 

318 return [_to_view(r) for r in rows], total 

319 except Exception as e: 

320 logger.error("Failed to list session history for %s: %s", user_id, e) 

321 return [], 0 

322 

323 

324def mark_expired(*, session_ids: list[uuid.UUID]) -> None: 

325 """Flag active rows whose Redis session has vanished (idle TTL lapse).""" 

326 if not session_ids: 

327 return 

328 now = aware_utcnow() 

329 try: 

330 with SessionLocal() as db: 

331 db.execute( 

332 update(SessionRecord) 

333 .where( 

334 SessionRecord.id.in_(session_ids), 

335 SessionRecord.ended_at.is_(None), 

336 ) 

337 .values(ended_at=now, end_reason=SessionEndReason.EXPIRED) 

338 ) 

339 db.commit() 

340 except Exception as e: 

341 logger.error("Failed to mark sessions expired: %s", e) 

342 

343 

344def purge_old_sessions(*, retention_days: int) -> int: 

345 """Delete ended sessions whose ``ended_at`` is older than the retention window. 

346 

347 Only ended rows (logged out / revoked / expired) are eligible — active 

348 sessions (``ended_at IS NULL``) are never deleted regardless of age. Returns 

349 the number of rows removed. A non-positive ``retention_days`` disables 

350 purging and returns 0. Best-effort: errors are logged and swallowed. 

351 """ 

352 if retention_days <= 0: 

353 return 0 

354 cutoff = aware_utcnow() - timedelta(days=retention_days) 

355 try: 

356 with SessionLocal() as db: 

357 result = db.execute( 

358 delete(SessionRecord).where( 

359 SessionRecord.ended_at.is_not(None), 

360 SessionRecord.ended_at < cutoff, 

361 ) 

362 ) 

363 db.commit() 

364 return result.rowcount or 0 

365 except Exception as e: 

366 logger.error("Failed to purge old sessions: %s", e) 

367 return 0 

368 

369 

370# --------------------------------------------------------------------------- # 

371# Internals 

372# --------------------------------------------------------------------------- # 

373 

374 

375def _end_where(condition, *, reason: SessionEndReason) -> None: 

376 now = aware_utcnow() 

377 try: 

378 with SessionLocal() as db: 

379 db.execute( 

380 update(SessionRecord) 

381 .where(condition, SessionRecord.ended_at.is_(None)) 

382 .values(ended_at=now, end_reason=reason) 

383 ) 

384 db.commit() 

385 except Exception as e: 

386 logger.error("Failed to end session: %s", e) 

387 

388 

389def _interval(seconds: int): 

390 from datetime import timedelta 

391 

392 return timedelta(seconds=seconds) 

393 

394 

395def _redact(sid: str) -> str: 

396 return f"{sid[:6]}…" if sid else "?"