login static method

Future<bool> login({
  1. required HttpRequest request,
  2. required String email,
  3. required String password,
})

Attempts to authenticate a user and establish a session.

Behavior:

  • Creates a secure, HTTP-only session cookie.
  • Reuses an existing in-memory session when available for the email.
  • Otherwise verifies the user's password and creates a new persisted session record.
  • Registers the session in memory and attaches the cookie to the response.

Parameters:

  • request: The active HTTP request.
  • email: The user's email address.
  • password: The plain-text password to verify.

Returns true when login succeeds; otherwise returns false.

Example:

final success = await AuthSession.login(
  request: request,
  email: 'jane@example.com',
  password: 'super-secret-password',
);

if (success) {
  print('Login successful');
}

Implementation

static Future<bool> login({required HttpRequest request, required String email, required String password}) async {
  try {
    final cookie = Cookie('archery_session', App.generateKey())
      ..httpOnly = true
      ..secure = true
      ..sameSite = SameSite.lax;

    final authSessions = App().tryMake<List<AuthSession>>();
    if (authSessions == null) return false;

    final authSession = authSessions.firstWhereOrNull((session) => session.email == email);

    if (authSession != null) {
      request.response.cookies.add(cookie);
      authSession.cookie = cookie;
      authSession.lastActivity = DateTime.now();
      return true;
    } else {
      final user = await Model.firstWhere<User>(field: "email", value: email);

      if (user != null && Hasher.check(key: password, hash: user.password)) {
        final newAuthSession = await Model.create<AuthSession>(fromJson: {"email": user.email, "token": App.generateKey()});
        if (newAuthSession == null) return false;

        newAuthSession.lastActivity = DateTime.now();
        newAuthSession.cookie = cookie;
        authSessions.add(newAuthSession);

        request.response.cookies.add(cookie);

        return true;
      }
    }
    return false;
  } catch (e) {
    return false;
  }
}