ga_enable === 1 && Totp::normalizeSecret($user->ga_token) !== ''; } /** @return array{ok:bool,msg:string,retry_after:int} */ public static function sendPasswordEmailCode(User $user, $clientIp = ''): array { $email = strtolower(trim((string) $user->email)); if ($email === '' || filter_var($email, FILTER_VALIDATE_EMAIL) === false) { return ['ok' => false, 'msg' => '账户邮箱无效', 'retry_after' => 0]; } if (Mail::isRecipientBlacklisted($email)) { return ['ok' => false, 'msg' => '当前邮箱暂时无法接收验证邮件', 'retry_after' => 0]; } $ip = is_scalar($clientIp) ? trim((string) $clientIp) : ''; $redis = new RedisClient(); // Scope the send gate to the authenticated account. Binding it to a // client IP lets a requester evade the cooldown by rotating proxies. $key = self::sendCooldownKey($user); if (!self::acquireCooldown($redis, $key)) { $retryAfter = self::ttl($redis, $key); return ['ok' => false, 'msg' => '请求过于频繁,请稍后再试', 'retry_after' => $retryAfter]; } $now = time(); $ttl = (int) CaptchaConfig::get('email_verify_ttl'); $active = EmailVerify::where('email', $email) ->where('code', 'like', 'password_change:%') ->where('expire_in', '>', $now) ->count(); if ((int) $active >= self::ACTIVE_CODE_LIMIT) { return ['ok' => false, 'msg' => '验证码请求次数过多,请稍后再试', 'retry_after' => self::SEND_COOLDOWN_SECONDS]; } $verification = new EmailVerify(); $verification->email = $email; $verification->ip = $ip === '' ? '0.0.0.0' : $ip; $plainCode = (string) random_int(100000, 999999); $verification->code = 'password_change:' . $plainCode; $verification->expire_in = $now + $ttl; if (!$verification->save()) { return ['ok' => false, 'msg' => '验证码发送失败,请稍后重试', 'retry_after' => 0]; } try { $sent = Mail::send( $email, Config::get('appName') . ' - 修改密码验证', 'auth/verify.tpl', [ 'code' => $plainCode, 'expire' => date('Y-m-d H:i:s', $verification->expire_in), 'language' => 'false', 'scene' => 'password_change', ], [], '修改密码验证' ); } catch (\Throwable $exception) { $sent = false; } if (!$sent) { $verification->delete(); return ['ok' => false, 'msg' => '验证码发送失败,请稍后重试', 'retry_after' => 0]; } return ['ok' => true, 'msg' => '验证码已发送,请检查邮箱', 'retry_after' => self::SEND_COOLDOWN_SECONDS]; } /** Consume one accepted password-change factor. */ public static function consumePasswordFactor(User $user, $emailCode = '', $totpCode = '', $clientIp = ''): ?string { $redis = new RedisClient(); $failKey = self::factorFailKey($user); if (self::factorFailures($redis, $failKey) >= self::FACTOR_FAIL_LIMIT) { return null; } $emailCode = is_scalar($emailCode) ? trim((string) $emailCode) : ''; $totpCode = is_scalar($totpCode) ? trim((string) $totpCode) : ''; if (self::hasTotp($user)) { if (Totp::verify($user->ga_token, $totpCode)) { self::clearFactorFailures($redis, $failKey); return 'totp'; } } if ($emailCode === '' || !preg_match('/^\d{6}$/D', $emailCode) || Mail::isRecipientBlacklisted($user->email)) { self::recordFactorFailure($redis, $failKey); return null; } $connection = (new EmailVerify())->getConnection(); $consumed = false; $connection->transaction(function () use ($user, $emailCode, &$consumed) { $verification = EmailVerify::where('email', strtolower(trim((string) $user->email))) ->where('code', 'password_change:' . $emailCode) ->where('expire_in', '>', time()) ->lockForUpdate() ->first(); if ($verification !== null) { $verification->delete(); $consumed = true; } }, 3); if ($consumed) { self::clearFactorFailures($redis, $failKey); return 'email'; } self::recordFactorFailure($redis, $failKey); return null; } private static function sendCooldownKey(User $user): string { return 'account_password_verify_send:' . (int) $user->id; } private static function ttl(RedisClient $redis, string $key): int { try { $ttl = $redis->getClient()->ttl($key); return $ttl > 0 ? (int) $ttl : 0; } catch (\Throwable $exception) { return 0; } } private static function acquireCooldown(RedisClient $redis, string $key): bool { try { $result = $redis->getClient()->set( $key, '1', 'EX', self::SEND_COOLDOWN_SECONDS, 'NX' ); return $result === true || strtoupper((string) $result) === 'OK'; } catch (\Throwable $exception) { // Redis is an abuse-control accelerator. The database active-code // limit still bounds outstanding codes when it is unavailable. return true; } } private static function factorFailKey(User $user): string { return 'account_password_verify_fail:' . (int) $user->id; } private static function factorFailures(RedisClient $redis, string $key): int { try { $value = $redis->getClient()->get($key); return is_numeric($value) ? (int) $value : 0; } catch (\Throwable $exception) { return 0; } } private static function recordFactorFailure(RedisClient $redis, string $key): void { try { $client = $redis->getClient(); $value = (int) $client->incr($key); if ($value === 1) { $client->expire($key, self::FACTOR_FAIL_TTL); } } catch (\Throwable $exception) { // Continue with database verification when Redis is unavailable. } } private static function clearFactorFailures(RedisClient $redis, string $key): void { try { $redis->del($key); } catch (\Throwable $exception) { // A stale failure counter only affects abuse throttling. } } }