resetPassword static method

Future<bool> resetPassword({
  1. required String token,
  2. required String newPassword,
})

Reset password using token

Implementation

static Future<bool> resetPassword({
  required String token,
  required String newPassword,
}) async {
  if (newPassword.length < _config.passwordMinLength) {
    throw AuthException(
      'Password must be at least ${_config.passwordMinLength} characters long.',
    );
  }
  ensureFrameworkTablesExist();

  final tokenHash = Hashing().hash(token);
  final qb = QueryBuilder(table: 'password_reset_tokens');

  final tokenRecord = await qb
      .where('token', '=', tokenHash)
      .where('expires_at', '>', DateTime.now().toIso8601String())
      .first();

  if (tokenRecord == null) {
    return false; // Invalid or expired token
  }

  final email = tokenRecord['email'] as String;
  final hashedPassword = Hashing().hash(newPassword);

  // Update user password
  await QueryBuilder(table: config.table)
      .where(config.emailColumn, '=', email)
      .update({
    config.passwordColumn: hashedPassword,
  });

  // Delete used token
  await qb.where('token', '=', tokenHash).delete();

  return true;
}