Skip to content

infrastructure.persistence.repositories.session_repository

src.infrastructure.persistence.repositories.session_repository

SessionRepository - SQLAlchemy implementation of SessionRepository protocol.

Adapter for hexagonal architecture. Maps between domain SessionData DTOs and database Session models.

This repository handles all session persistence operations including: - CRUD operations - Active session counting (for limit enforcement) - Bulk revocation (password change, security events) - Session cleanup (expired session removal)

Reference
  • docs/architecture/session-management-architecture.md

Classes

SessionRepository

SQLAlchemy implementation of SessionRepository protocol.

This is an adapter that implements the SessionRepository port. It handles mapping between SessionData DTOs and Session database models.

This class does NOT inherit from SessionRepository protocol (Protocol uses structural typing - duck typing with type safety).

Attributes:

Name Type Description
session

SQLAlchemy async session for database operations.

Example

async with get_session() as db_session: ... repo = SessionRepository(db_session) ... session_data = await repo.find_by_id(session_id)

Source code in src/infrastructure/persistence/repositories/session_repository.py
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
class SessionRepository:
    """SQLAlchemy implementation of SessionRepository protocol.

    This is an adapter that implements the SessionRepository port.
    It handles mapping between SessionData DTOs and Session database models.

    This class does NOT inherit from SessionRepository protocol
    (Protocol uses structural typing - duck typing with type safety).

    Attributes:
        session: SQLAlchemy async session for database operations.

    Example:
        >>> async with get_session() as db_session:
        ...     repo = SessionRepository(db_session)
        ...     session_data = await repo.find_by_id(session_id)
    """

    def __init__(self, session: AsyncSession) -> None:
        """Initialize repository with database session.

        Args:
            session: SQLAlchemy async session.
        """
        self._session = session

    async def save(self, session_data: SessionData) -> None:
        """Save or update a session.

        Creates new session if it doesn't exist, updates if it does.
        Uses merge to handle both insert and update scenarios.

        Args:
            session_data: Session data to persist.
        """
        # Check if session exists
        existing = await self._session.get(SessionModel, session_data.id)

        if existing is None:
            # Create new session
            session_model = self._to_model(session_data)
            self._session.add(session_model)
        else:
            # Update existing session
            self._update_model(existing, session_data)

        await self._session.commit()

    async def find_by_id(self, session_id: UUID) -> SessionData | None:
        """Find session by ID.

        Args:
            session_id: Session identifier.

        Returns:
            SessionData if found, None otherwise.
        """
        session_model = await self._session.get(SessionModel, session_id)

        if session_model is None:
            return None

        return self._to_dto(session_model)

    async def find_by_user_id(
        self,
        user_id: UUID,
        *,
        active_only: bool = False,
    ) -> list[SessionData]:
        """Find all sessions for a user.

        Args:
            user_id: User identifier.
            active_only: If True, only return active (non-revoked, non-expired) sessions.

        Returns:
            List of session data, empty if none found.
            Ordered by created_at descending (newest first).
        """
        stmt = select(SessionModel).where(SessionModel.user_id == user_id)

        if active_only:
            now = datetime.now(UTC)
            stmt = stmt.where(
                and_(
                    SessionModel.is_revoked.is_(False),
                    SessionModel.expires_at > now,
                )
            )

        stmt = stmt.order_by(SessionModel.created_at.desc())
        result = await self._session.execute(stmt)
        session_models = result.scalars().all()

        return [self._to_dto(model) for model in session_models]

    async def find_by_refresh_token_id(
        self,
        refresh_token_id: UUID,
    ) -> SessionData | None:
        """Find session by refresh token ID.

        Used during token refresh to locate associated session.

        Args:
            refresh_token_id: Refresh token identifier.

        Returns:
            SessionData if found, None otherwise.
        """
        stmt = select(SessionModel).where(
            SessionModel.refresh_token_id == refresh_token_id
        )
        result = await self._session.execute(stmt)
        session_model = result.scalar_one_or_none()

        if session_model is None:
            return None

        return self._to_dto(session_model)

    async def count_active_sessions(self, user_id: UUID) -> int:
        """Count active sessions for a user.

        Used to enforce session limits. A session is active if:
        - is_revoked is False
        - expires_at is in the future

        Args:
            user_id: User identifier.

        Returns:
            Number of active sessions.
        """
        now = datetime.now(UTC)
        stmt = select(func.count()).where(
            and_(
                SessionModel.user_id == user_id,
                SessionModel.is_revoked.is_(False),
                SessionModel.expires_at > now,
            )
        )
        result = await self._session.execute(stmt)
        return result.scalar_one()

    async def delete(self, session_id: UUID) -> bool:
        """Delete a session (hard delete).

        Args:
            session_id: Session identifier.

        Returns:
            True if deleted, False if not found.
        """
        stmt = delete(SessionModel).where(SessionModel.id == session_id)
        result = await self._session.execute(stmt)
        await self._session.commit()
        return (cast(Any, result).rowcount or 0) > 0

    async def delete_all_for_user(self, user_id: UUID) -> int:
        """Delete all sessions for a user (hard delete).

        Used during account deletion or security reset.

        Args:
            user_id: User identifier.

        Returns:
            Number of sessions deleted.
        """
        stmt = delete(SessionModel).where(SessionModel.user_id == user_id)
        result = await self._session.execute(stmt)
        await self._session.commit()
        return cast(Any, result).rowcount or 0

    async def revoke_all_for_user(
        self,
        user_id: UUID,
        reason: str,
        *,
        except_session_id: UUID | None = None,
    ) -> int:
        """Revoke all sessions for a user (soft delete).

        Used during password change or security event.
        Optionally excludes the current session.

        Args:
            user_id: User identifier.
            reason: Revocation reason for audit.
            except_session_id: Session ID to exclude (e.g., current session).

        Returns:
            Number of sessions revoked.
        """
        now = datetime.now(UTC)

        # Build where clause
        conditions = [
            SessionModel.user_id == user_id,
            SessionModel.is_revoked.is_(False),
        ]

        if except_session_id is not None:
            conditions.append(SessionModel.id != except_session_id)

        stmt = (
            update(SessionModel)
            .where(and_(*conditions))
            .values(
                is_revoked=True,
                revoked_at=now,
                revoked_reason=reason,
            )
        )

        result = await self._session.execute(stmt)
        await self._session.commit()
        return cast(Any, result).rowcount or 0

    async def get_oldest_active_session(
        self,
        user_id: UUID,
    ) -> SessionData | None:
        """Get the oldest active session for a user.

        Used when enforcing session limits (FIFO eviction).

        Args:
            user_id: User identifier.

        Returns:
            Oldest active session data, None if no active sessions.
        """
        now = datetime.now(UTC)
        stmt = (
            select(SessionModel)
            .where(
                and_(
                    SessionModel.user_id == user_id,
                    SessionModel.is_revoked.is_(False),
                    SessionModel.expires_at > now,
                )
            )
            .order_by(SessionModel.created_at.asc())
            .limit(1)
        )

        result = await self._session.execute(stmt)
        session_model = result.scalar_one_or_none()

        if session_model is None:
            return None

        return self._to_dto(session_model)

    async def cleanup_expired_sessions(
        self,
        *,
        before: datetime | None = None,
    ) -> int:
        """Clean up expired sessions (batch operation).

        Called by scheduled job to remove old sessions.
        Deletes sessions that are either:
        - Expired (expires_at < before)
        - Revoked more than retention period ago

        Args:
            before: Delete sessions expired before this time.
                   Defaults to now.

        Returns:
            Number of sessions cleaned up.
        """
        if before is None:
            before = datetime.now(UTC)

        # Delete expired or revoked sessions
        stmt = delete(SessionModel).where(
            SessionModel.expires_at < before,
        )

        result = await self._session.execute(stmt)
        await self._session.commit()
        return cast(Any, result).rowcount or 0

    # =========================================================================
    # Additional utility methods (not in protocol but useful)
    # =========================================================================

    async def update_activity(
        self,
        session_id: UUID,
        ip_address: str | None = None,
    ) -> bool:
        """Update session activity timestamp and optionally IP.

        Called on each authenticated request to track activity.

        Args:
            session_id: Session identifier.
            ip_address: Current client IP (for detecting changes).

        Returns:
            True if updated, False if session not found.
        """
        now = datetime.now(UTC)
        values: dict[str, object] = {"last_activity_at": now}

        if ip_address is not None:
            values["last_ip_address"] = ip_address

        stmt = (
            update(SessionModel).where(SessionModel.id == session_id).values(**values)
        )

        result = await self._session.execute(stmt)
        await self._session.commit()
        return (cast(Any, result).rowcount or 0) > 0

    async def update_provider_access(
        self,
        session_id: UUID,
        provider_name: str,
    ) -> bool:
        """Record provider access in session.

        Updates last_provider_accessed, last_provider_sync_at,
        and adds to providers_accessed array.

        Args:
            session_id: Session identifier.
            provider_name: Name of provider accessed.

        Returns:
            True if updated, False if session not found.
        """
        now = datetime.now(UTC)

        # First, get current providers_accessed
        session_model = await self._session.get(SessionModel, session_id)
        if session_model is None:
            return False

        # Update providers list
        current_providers = session_model.providers_accessed or []
        if provider_name not in current_providers:
            current_providers = [*current_providers, provider_name]

        # Update fields
        session_model.last_provider_accessed = provider_name
        session_model.last_provider_sync_at = now
        session_model.providers_accessed = current_providers

        await self._session.commit()
        return True

    async def increment_suspicious_activity(
        self,
        session_id: UUID,
    ) -> int:
        """Increment suspicious activity counter.

        Args:
            session_id: Session identifier.

        Returns:
            New counter value, or -1 if session not found.
        """
        session_model = await self._session.get(SessionModel, session_id)
        if session_model is None:
            return -1

        session_model.suspicious_activity_count += 1
        await self._session.commit()
        return session_model.suspicious_activity_count

    async def set_refresh_token_id(
        self,
        session_id: UUID,
        refresh_token_id: UUID,
    ) -> bool:
        """Set the refresh token ID for a session.

        Called after refresh token is created to link it to session.

        Args:
            session_id: Session identifier.
            refresh_token_id: Refresh token identifier.

        Returns:
            True if updated, False if session not found.
        """
        stmt = (
            update(SessionModel)
            .where(SessionModel.id == session_id)
            .values(refresh_token_id=refresh_token_id)
        )

        result = await self._session.execute(stmt)
        await self._session.commit()
        return (cast(Any, result).rowcount or 0) > 0

    # =========================================================================
    # Mapping methods
    # =========================================================================

    def _to_dto(self, model: SessionModel) -> SessionData:
        """Convert database model to SessionData DTO.

        Args:
            model: SQLAlchemy Session model instance.

        Returns:
            SessionData DTO.
        """
        return SessionData(
            id=model.id,
            user_id=model.user_id,
            device_info=model.device_info,
            user_agent=model.user_agent,
            ip_address=str(model.ip_address) if model.ip_address else None,
            location=model.location,
            created_at=model.created_at,
            last_activity_at=model.last_activity_at,
            expires_at=model.expires_at,
            is_revoked=model.is_revoked,
            is_trusted=model.is_trusted,
            revoked_at=model.revoked_at,
            revoked_reason=model.revoked_reason,
            refresh_token_id=model.refresh_token_id,
            last_ip_address=str(model.last_ip_address)
            if model.last_ip_address
            else None,
            suspicious_activity_count=model.suspicious_activity_count,
            last_provider_accessed=model.last_provider_accessed,
            last_provider_sync_at=model.last_provider_sync_at,
            providers_accessed=list(model.providers_accessed)
            if model.providers_accessed
            else None,
        )

    def _to_model(self, dto: SessionData) -> SessionModel:
        """Convert SessionData DTO to database model.

        Args:
            dto: SessionData DTO.

        Returns:
            SQLAlchemy Session model instance.
        """
        return SessionModel(
            id=dto.id,
            user_id=dto.user_id,
            device_info=dto.device_info,
            user_agent=dto.user_agent,
            ip_address=dto.ip_address,
            location=dto.location,
            created_at=dto.created_at,  # Explicit: override DB default
            last_activity_at=dto.last_activity_at,
            expires_at=dto.expires_at,
            is_revoked=dto.is_revoked,
            is_trusted=dto.is_trusted,
            revoked_at=dto.revoked_at,
            revoked_reason=dto.revoked_reason,
            refresh_token_id=dto.refresh_token_id,
            last_ip_address=dto.last_ip_address,
            suspicious_activity_count=dto.suspicious_activity_count,
            last_provider_accessed=dto.last_provider_accessed,
            last_provider_sync_at=dto.last_provider_sync_at,
            providers_accessed=dto.providers_accessed,
        )

    def _update_model(self, model: SessionModel, dto: SessionData) -> None:
        """Update existing model with DTO values.

        Updates all mutable fields. Does not change id or user_id.

        Args:
            model: Existing SQLAlchemy model to update.
            dto: SessionData DTO with new values.
        """
        model.device_info = dto.device_info
        model.user_agent = dto.user_agent
        model.ip_address = dto.ip_address
        model.location = dto.location
        model.last_activity_at = dto.last_activity_at
        model.expires_at = dto.expires_at
        model.is_revoked = dto.is_revoked
        model.is_trusted = dto.is_trusted
        model.revoked_at = dto.revoked_at
        model.revoked_reason = dto.revoked_reason
        model.refresh_token_id = dto.refresh_token_id
        model.last_ip_address = dto.last_ip_address
        model.suspicious_activity_count = dto.suspicious_activity_count
        model.last_provider_accessed = dto.last_provider_accessed
        model.last_provider_sync_at = dto.last_provider_sync_at
        model.providers_accessed = dto.providers_accessed
Functions
__init__
__init__(session: AsyncSession) -> None

Parameters:

Name Type Description Default
session AsyncSession

SQLAlchemy async session.

required
Source code in src/infrastructure/persistence/repositories/session_repository.py
def __init__(self, session: AsyncSession) -> None:
    """Initialize repository with database session.

    Args:
        session: SQLAlchemy async session.
    """
    self._session = session
save async
save(session_data: SessionData) -> None

Save or update a session.

Creates new session if it doesn't exist, updates if it does. Uses merge to handle both insert and update scenarios.

Parameters:

Name Type Description Default
session_data SessionData

Session data to persist.

required
Source code in src/infrastructure/persistence/repositories/session_repository.py
async def save(self, session_data: SessionData) -> None:
    """Save or update a session.

    Creates new session if it doesn't exist, updates if it does.
    Uses merge to handle both insert and update scenarios.

    Args:
        session_data: Session data to persist.
    """
    # Check if session exists
    existing = await self._session.get(SessionModel, session_data.id)

    if existing is None:
        # Create new session
        session_model = self._to_model(session_data)
        self._session.add(session_model)
    else:
        # Update existing session
        self._update_model(existing, session_data)

    await self._session.commit()
find_by_id async
find_by_id(session_id: UUID) -> SessionData | None

Find session by ID.

Parameters:

Name Type Description Default
session_id UUID

Session identifier.

required

Returns:

Type Description
SessionData | None

SessionData if found, None otherwise.

Source code in src/infrastructure/persistence/repositories/session_repository.py
async def find_by_id(self, session_id: UUID) -> SessionData | None:
    """Find session by ID.

    Args:
        session_id: Session identifier.

    Returns:
        SessionData if found, None otherwise.
    """
    session_model = await self._session.get(SessionModel, session_id)

    if session_model is None:
        return None

    return self._to_dto(session_model)
find_by_user_id async
find_by_user_id(
    user_id: UUID, *, active_only: bool = False
) -> list[SessionData]

Find all sessions for a user.

Parameters:

Name Type Description Default
user_id UUID

User identifier.

required
active_only bool

If True, only return active (non-revoked, non-expired) sessions.

False

Returns:

Type Description
list[SessionData]

List of session data, empty if none found.

list[SessionData]

Ordered by created_at descending (newest first).

Source code in src/infrastructure/persistence/repositories/session_repository.py
async def find_by_user_id(
    self,
    user_id: UUID,
    *,
    active_only: bool = False,
) -> list[SessionData]:
    """Find all sessions for a user.

    Args:
        user_id: User identifier.
        active_only: If True, only return active (non-revoked, non-expired) sessions.

    Returns:
        List of session data, empty if none found.
        Ordered by created_at descending (newest first).
    """
    stmt = select(SessionModel).where(SessionModel.user_id == user_id)

    if active_only:
        now = datetime.now(UTC)
        stmt = stmt.where(
            and_(
                SessionModel.is_revoked.is_(False),
                SessionModel.expires_at > now,
            )
        )

    stmt = stmt.order_by(SessionModel.created_at.desc())
    result = await self._session.execute(stmt)
    session_models = result.scalars().all()

    return [self._to_dto(model) for model in session_models]
find_by_refresh_token_id async
find_by_refresh_token_id(
    refresh_token_id: UUID,
) -> SessionData | None

Find session by refresh token ID.

Used during token refresh to locate associated session.

Parameters:

Name Type Description Default
refresh_token_id UUID

Refresh token identifier.

required

Returns:

Type Description
SessionData | None

SessionData if found, None otherwise.

Source code in src/infrastructure/persistence/repositories/session_repository.py
async def find_by_refresh_token_id(
    self,
    refresh_token_id: UUID,
) -> SessionData | None:
    """Find session by refresh token ID.

    Used during token refresh to locate associated session.

    Args:
        refresh_token_id: Refresh token identifier.

    Returns:
        SessionData if found, None otherwise.
    """
    stmt = select(SessionModel).where(
        SessionModel.refresh_token_id == refresh_token_id
    )
    result = await self._session.execute(stmt)
    session_model = result.scalar_one_or_none()

    if session_model is None:
        return None

    return self._to_dto(session_model)
count_active_sessions async
count_active_sessions(user_id: UUID) -> int

Count active sessions for a user.

Used to enforce session limits. A session is active if: - is_revoked is False - expires_at is in the future

Parameters:

Name Type Description Default
user_id UUID

User identifier.

required

Returns:

Type Description
int

Number of active sessions.

Source code in src/infrastructure/persistence/repositories/session_repository.py
async def count_active_sessions(self, user_id: UUID) -> int:
    """Count active sessions for a user.

    Used to enforce session limits. A session is active if:
    - is_revoked is False
    - expires_at is in the future

    Args:
        user_id: User identifier.

    Returns:
        Number of active sessions.
    """
    now = datetime.now(UTC)
    stmt = select(func.count()).where(
        and_(
            SessionModel.user_id == user_id,
            SessionModel.is_revoked.is_(False),
            SessionModel.expires_at > now,
        )
    )
    result = await self._session.execute(stmt)
    return result.scalar_one()
delete async
delete(session_id: UUID) -> bool

Delete a session (hard delete).

Parameters:

Name Type Description Default
session_id UUID

Session identifier.

required

Returns:

Type Description
bool

True if deleted, False if not found.

Source code in src/infrastructure/persistence/repositories/session_repository.py
async def delete(self, session_id: UUID) -> bool:
    """Delete a session (hard delete).

    Args:
        session_id: Session identifier.

    Returns:
        True if deleted, False if not found.
    """
    stmt = delete(SessionModel).where(SessionModel.id == session_id)
    result = await self._session.execute(stmt)
    await self._session.commit()
    return (cast(Any, result).rowcount or 0) > 0
delete_all_for_user async
delete_all_for_user(user_id: UUID) -> int

Delete all sessions for a user (hard delete).

Used during account deletion or security reset.

Parameters:

Name Type Description Default
user_id UUID

User identifier.

required

Returns:

Type Description
int

Number of sessions deleted.

Source code in src/infrastructure/persistence/repositories/session_repository.py
async def delete_all_for_user(self, user_id: UUID) -> int:
    """Delete all sessions for a user (hard delete).

    Used during account deletion or security reset.

    Args:
        user_id: User identifier.

    Returns:
        Number of sessions deleted.
    """
    stmt = delete(SessionModel).where(SessionModel.user_id == user_id)
    result = await self._session.execute(stmt)
    await self._session.commit()
    return cast(Any, result).rowcount or 0
revoke_all_for_user async
revoke_all_for_user(
    user_id: UUID,
    reason: str,
    *,
    except_session_id: UUID | None = None
) -> int

Revoke all sessions for a user (soft delete).

Used during password change or security event. Optionally excludes the current session.

Parameters:

Name Type Description Default
user_id UUID

User identifier.

required
reason str

Revocation reason for audit.

required
except_session_id UUID | None

Session ID to exclude (e.g., current session).

None

Returns:

Type Description
int

Number of sessions revoked.

Source code in src/infrastructure/persistence/repositories/session_repository.py
async def revoke_all_for_user(
    self,
    user_id: UUID,
    reason: str,
    *,
    except_session_id: UUID | None = None,
) -> int:
    """Revoke all sessions for a user (soft delete).

    Used during password change or security event.
    Optionally excludes the current session.

    Args:
        user_id: User identifier.
        reason: Revocation reason for audit.
        except_session_id: Session ID to exclude (e.g., current session).

    Returns:
        Number of sessions revoked.
    """
    now = datetime.now(UTC)

    # Build where clause
    conditions = [
        SessionModel.user_id == user_id,
        SessionModel.is_revoked.is_(False),
    ]

    if except_session_id is not None:
        conditions.append(SessionModel.id != except_session_id)

    stmt = (
        update(SessionModel)
        .where(and_(*conditions))
        .values(
            is_revoked=True,
            revoked_at=now,
            revoked_reason=reason,
        )
    )

    result = await self._session.execute(stmt)
    await self._session.commit()
    return cast(Any, result).rowcount or 0
get_oldest_active_session async
get_oldest_active_session(
    user_id: UUID,
) -> SessionData | None

Get the oldest active session for a user.

Used when enforcing session limits (FIFO eviction).

Parameters:

Name Type Description Default
user_id UUID

User identifier.

required

Returns:

Type Description
SessionData | None

Oldest active session data, None if no active sessions.

Source code in src/infrastructure/persistence/repositories/session_repository.py
async def get_oldest_active_session(
    self,
    user_id: UUID,
) -> SessionData | None:
    """Get the oldest active session for a user.

    Used when enforcing session limits (FIFO eviction).

    Args:
        user_id: User identifier.

    Returns:
        Oldest active session data, None if no active sessions.
    """
    now = datetime.now(UTC)
    stmt = (
        select(SessionModel)
        .where(
            and_(
                SessionModel.user_id == user_id,
                SessionModel.is_revoked.is_(False),
                SessionModel.expires_at > now,
            )
        )
        .order_by(SessionModel.created_at.asc())
        .limit(1)
    )

    result = await self._session.execute(stmt)
    session_model = result.scalar_one_or_none()

    if session_model is None:
        return None

    return self._to_dto(session_model)
cleanup_expired_sessions async
cleanup_expired_sessions(
    *, before: datetime | None = None
) -> int

Clean up expired sessions (batch operation).

Called by scheduled job to remove old sessions. Deletes sessions that are either: - Expired (expires_at < before) - Revoked more than retention period ago

Parameters:

Name Type Description Default
before datetime | None

Delete sessions expired before this time. Defaults to now.

None

Returns:

Type Description
int

Number of sessions cleaned up.

Source code in src/infrastructure/persistence/repositories/session_repository.py
async def cleanup_expired_sessions(
    self,
    *,
    before: datetime | None = None,
) -> int:
    """Clean up expired sessions (batch operation).

    Called by scheduled job to remove old sessions.
    Deletes sessions that are either:
    - Expired (expires_at < before)
    - Revoked more than retention period ago

    Args:
        before: Delete sessions expired before this time.
               Defaults to now.

    Returns:
        Number of sessions cleaned up.
    """
    if before is None:
        before = datetime.now(UTC)

    # Delete expired or revoked sessions
    stmt = delete(SessionModel).where(
        SessionModel.expires_at < before,
    )

    result = await self._session.execute(stmt)
    await self._session.commit()
    return cast(Any, result).rowcount or 0
update_activity async
update_activity(
    session_id: UUID, ip_address: str | None = None
) -> bool

Update session activity timestamp and optionally IP.

Called on each authenticated request to track activity.

Parameters:

Name Type Description Default
session_id UUID

Session identifier.

required
ip_address str | None

Current client IP (for detecting changes).

None

Returns:

Type Description
bool

True if updated, False if session not found.

Source code in src/infrastructure/persistence/repositories/session_repository.py
async def update_activity(
    self,
    session_id: UUID,
    ip_address: str | None = None,
) -> bool:
    """Update session activity timestamp and optionally IP.

    Called on each authenticated request to track activity.

    Args:
        session_id: Session identifier.
        ip_address: Current client IP (for detecting changes).

    Returns:
        True if updated, False if session not found.
    """
    now = datetime.now(UTC)
    values: dict[str, object] = {"last_activity_at": now}

    if ip_address is not None:
        values["last_ip_address"] = ip_address

    stmt = (
        update(SessionModel).where(SessionModel.id == session_id).values(**values)
    )

    result = await self._session.execute(stmt)
    await self._session.commit()
    return (cast(Any, result).rowcount or 0) > 0
update_provider_access async
update_provider_access(
    session_id: UUID, provider_name: str
) -> bool

Record provider access in session.

Updates last_provider_accessed, last_provider_sync_at, and adds to providers_accessed array.

Parameters:

Name Type Description Default
session_id UUID

Session identifier.

required
provider_name str

Name of provider accessed.

required

Returns:

Type Description
bool

True if updated, False if session not found.

Source code in src/infrastructure/persistence/repositories/session_repository.py
async def update_provider_access(
    self,
    session_id: UUID,
    provider_name: str,
) -> bool:
    """Record provider access in session.

    Updates last_provider_accessed, last_provider_sync_at,
    and adds to providers_accessed array.

    Args:
        session_id: Session identifier.
        provider_name: Name of provider accessed.

    Returns:
        True if updated, False if session not found.
    """
    now = datetime.now(UTC)

    # First, get current providers_accessed
    session_model = await self._session.get(SessionModel, session_id)
    if session_model is None:
        return False

    # Update providers list
    current_providers = session_model.providers_accessed or []
    if provider_name not in current_providers:
        current_providers = [*current_providers, provider_name]

    # Update fields
    session_model.last_provider_accessed = provider_name
    session_model.last_provider_sync_at = now
    session_model.providers_accessed = current_providers

    await self._session.commit()
    return True
increment_suspicious_activity async
increment_suspicious_activity(session_id: UUID) -> int

Increment suspicious activity counter.

Parameters:

Name Type Description Default
session_id UUID

Session identifier.

required

Returns:

Type Description
int

New counter value, or -1 if session not found.

Source code in src/infrastructure/persistence/repositories/session_repository.py
async def increment_suspicious_activity(
    self,
    session_id: UUID,
) -> int:
    """Increment suspicious activity counter.

    Args:
        session_id: Session identifier.

    Returns:
        New counter value, or -1 if session not found.
    """
    session_model = await self._session.get(SessionModel, session_id)
    if session_model is None:
        return -1

    session_model.suspicious_activity_count += 1
    await self._session.commit()
    return session_model.suspicious_activity_count
set_refresh_token_id async
set_refresh_token_id(
    session_id: UUID, refresh_token_id: UUID
) -> bool

Set the refresh token ID for a session.

Called after refresh token is created to link it to session.

Parameters:

Name Type Description Default
session_id UUID

Session identifier.

required
refresh_token_id UUID

Refresh token identifier.

required

Returns:

Type Description
bool

True if updated, False if session not found.

Source code in src/infrastructure/persistence/repositories/session_repository.py
async def set_refresh_token_id(
    self,
    session_id: UUID,
    refresh_token_id: UUID,
) -> bool:
    """Set the refresh token ID for a session.

    Called after refresh token is created to link it to session.

    Args:
        session_id: Session identifier.
        refresh_token_id: Refresh token identifier.

    Returns:
        True if updated, False if session not found.
    """
    stmt = (
        update(SessionModel)
        .where(SessionModel.id == session_id)
        .values(refresh_token_id=refresh_token_id)
    )

    result = await self._session.execute(stmt)
    await self._session.commit()
    return (cast(Any, result).rowcount or 0) > 0