changePassword static method

Future<bool> changePassword(
  1. Session session,
  2. int userId,
  3. String oldPassword,
  4. String newPassword,
)

Updates the password of a user.

Implementation

static Future<bool> changePassword(
  Session session,
  int userId,
  String oldPassword,
  String newPassword,
) async {
  var auth = await EmailAuth.db.findFirstRow(
    session,
    where: (t) => t.userId.equals(userId),
  );
  if (auth == null) {
    session.log(
      "userId: '$userId' is invalid!",
      level: LogLevel.debug,
    );
    return false;
  }

  if (!_isValidPasswordLength(password: newPassword, session: session)) {
    return false;
  }

  // Check old password

  try {
    final validationResponse = await validatePasswordHash(
      oldPassword,
      auth.email,
      auth.hash,
    );
    if (validationResponse is! PasswordValidationSuccess) {
      session.log(
        'Invalid password!',
        level: LogLevel.debug,
      );
      return false;
    }
  } catch (e) {
    session.log(
      ' - error when validating password hash: $e',
      level: LogLevel.error,
    );
    return false;
  }

  // Update password
  auth.hash = await generatePasswordHash(newPassword);
  await EmailAuth.db.updateRow(session, auth);

  return true;
}