loginWithEmailAndPassword static method

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

Verifies credentials and issues a new authentication cookie.

Requires a registered session cache and rejects already authenticated requests. Multiple sessions may share an email, each with its own token.

Implementation

static Future<bool> loginWithEmailAndPassword(HttpRequest request, {required String email, required String password}) async {
  try {
    if (_cachedSessions == null) {
      return false;
    }

    if (await check(request)) {
      return false;
    }

    // < v1.6 allowed for only one authSession per email.
    // now allowing multiple... will base on cookie value

    // use check to limit login sessions

    // final sessions = await Model.where<AuthSession>(field: "email", value: email);
    //
    // if( sessions.length >= 5 ) {
    //   return false;
    // }

    final user = await Model.firstWhere<User>(field: "email", value: email);

    if (user != null && Hasher.check(key: password, hash: user.password)) {
      final cookie = Cookie('archery_session', App.generateKey())
        ..httpOnly = true
        ..secure = true
        ..sameSite = SameSite.lax;

      final newAuthSession = await Model.create<AuthSession>(fromJson: {"email": user.email, "token": cookie.value});

      if (newAuthSession == null) return false;

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

      request.response.cookies.add(cookie);
      request.cookies.add(cookie);

      return await newAuthSession.save();
    }

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