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;
  }

  // Check old password
  if (!await validatePasswordHash(
    oldPassword,
    auth.email,
    auth.hash,
    onError: (e) {
      session.log(
        ' - error when validating password hash: $e',
        level: LogLevel.error,
      );
    },
  )) {
    session.log(
      'Invalid password!',
      level: LogLevel.debug,
    );
    return false;
  }

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

  return true;
}