listSessions method

Future<List<ServerSideSessionInfo>> listSessions(
  1. Session session, {
  2. UuidValue? authUserId,
  3. String? method,
  4. bool? expired,
  5. int? limit,
  6. Transaction? transaction,
})

List all sessions matching the given filters.

If authUserId is provided, only sessions for that user will be listed. If method is provided, only sessions created with that method will be listed. If expired is provided, only sessions matching the expiration status will be listed. A session is considered expired if either its expiresAt date has passed or it has been unused for longer than expireAfterUnusedFor.

Warning: In production systems with many sessions, calling this method without filter parameters (especially authUserId) and without a limit can be slow and memory-intensive. It is recommended to always use filters and set a reasonable limit when querying sessions in production.

If limit is provided, the results will be sorted by session ID to ensure deterministic ordering.

Implementation

Future<List<ServerSideSessionInfo>> listSessions(
  final Session session, {
  final UuidValue? authUserId,
  final String? method,
  final bool? expired,
  final int? limit,
  final Transaction? transaction,
}) async {
  final serverSideSessions = await ServerSideSession.db.find(
    session,
    where: (final t) {
      Expression<dynamic> expression = Constant.bool(true);

      if (authUserId != null) {
        expression &= t.authUserId.equals(authUserId);
      }

      if (method != null) {
        expression &= t.method.equals(method);
      }

      return expression;
    },
    limit: limit,
    orderBy: limit != null ? (final t) => t.id : null,
    transaction: transaction,
  );

  final sessionInfos = <ServerSideSessionInfo>[
    for (final serverSideSession in serverSideSessions)
      if (_shouldIncludeSession(serverSideSession, expired))
        ServerSideSessionInfo(
          id: serverSideSession.id!,
          authUserId: serverSideSession.authUserId,
          scopeNames: serverSideSession.scopeNames,
          created: serverSideSession.createdAt,
          lastUsed: serverSideSession.lastUsedAt,
          expiresAt: serverSideSession.expiresAt,
          expireAfterUnusedFor: serverSideSession.expireAfterUnusedFor,
          method: serverSideSession.method,
        ),
  ];

  return sessionInfos;
}