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 and db sessions.
  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 Auth.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) {
    return null;
  }

  final containerSession = _checkContainer(cookie.value);
  if (containerSession != null) {
    if (!_validateSession(containerSession)) {
      await logout(request);
      return null;
    }

    containerSession.lastActivity = DateTime.now();
    await containerSession.save();

    return await Model.firstWhere<User>(field: "email", value: containerSession.email);
  }

  final sessionRecord = await _checkDB(cookie.value);
  if (sessionRecord != null) {
    if (!_validateSession(sessionRecord)) {
      await logout(request);
      return null;
    }

    sessionRecord.lastActivity = DateTime.now();
    _cachedSessions?.add(sessionRecord);

    await sessionRecord.save();

    return await Model.firstWhere<User>(field: "email", value: sessionRecord.email);
  }

  return null;
}