user static method

Future<User?> user(
  1. HttpRequest request
)

Resolves the currently authenticated user from the incoming request.

Workflow:

  1. Reads the archery_session cookie from the request.
  2. Looks up the matching in-memory session.
  3. Verifies the session is still valid.
  4. Updates the session activity timestamp.
  5. Loads and returns the corresponding User record.

If any step fails, the request is logged out and null is returned.

Returns the authenticated User, or null when authentication fails.

Example:

final currentUser = await AuthSession.user(request);

if (currentUser != null) {
  print('Authenticated as ${currentUser.email}');
}

Implementation

static Future<User?> user(HttpRequest request) async {
  final cookie = request.cookies.firstWhereOrNull((cookie) => cookie.name == "archery_session");
  if (cookie == null) {
    await logout(request);
    return null;
  }

  final authSessions = App().tryMake<List<AuthSession>>();

  if (authSessions == null || authSessions.isEmpty) {
    await logout(request);
    return null;
  }

  final session = authSessions.firstWhereOrNull((session) => session.cookie?.value == cookie.value);

  if (session == null) {
    await logout(request);
    return null;
  }

  if (!_validateSession(session)) {
    await logout(request);
    return null;
  }

  session.lastActivity = DateTime.now();

  final sessionRecord = await Model.firstWhere<AuthSession>(field: "email", value: session.email);

  if (sessionRecord != null) {
    return await Model.firstWhere<User>(field: "email", value: sessionRecord.email);
  }
  return null;
}