You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
virt/web/app/Services/AccountEmailChangeService.php

326 lines
12 KiB
PHP

<?php
namespace App\Services;
use App\Models\EmailVerify;
use App\Models\User;
use App\Utils\Hash;
use Illuminate\Database\QueryException;
/** Securely replace an account email after verifying the new address. */
final class AccountEmailChangeService
{
private const CODE_PREFIX = 'email_change:';
private const SEND_COOLDOWN_SECONDS = 60;
private const ACTIVE_CODE_LIMIT = 3;
private const FACTOR_FAIL_LIMIT = 8;
private const FACTOR_FAIL_TTL = 600;
/** @return array{ok:bool,msg:string,retry_after:int} */
public static function sendNewEmailCode(
User $user,
$newEmail,
$clientIp = '',
?RedisClient $redis = null
): array
{
$userId = (int) $user->id;
$currentEmail = self::normalizeEmail($user->email);
$newEmail = self::normalizeEmail($newEmail);
if ($userId < 1 || $newEmail === null) {
return ['ok' => false, 'msg' => '请输入有效的新邮箱地址', 'retry_after' => 0];
}
if ($currentEmail !== null && hash_equals($currentEmail, $newEmail)) {
return ['ok' => false, 'msg' => '新邮箱不能与当前邮箱相同', 'retry_after' => 0];
}
if (User::where('email', '=', $newEmail)->where('id', '<>', $userId)->exists()) {
return ['ok' => false, 'msg' => '该邮箱已被其他账户使用', 'retry_after' => 0];
}
if (Mail::isRecipientBlacklisted($newEmail)) {
return ['ok' => false, 'msg' => '该邮箱暂时无法接收验证邮件', 'retry_after' => 0];
}
$redis = $redis ?? new RedisClient();
$cooldownKey = self::sendCooldownKey($user);
if (!self::acquireCooldown($redis, $cooldownKey)) {
return [
'ok' => false,
'msg' => '请求过于频繁,请稍后再试',
'retry_after' => self::ttl($redis, $cooldownKey),
];
}
$now = time();
$codePrefix = self::codePrefixForUser($userId);
$active = EmailVerify::where('email', $newEmail)
->where('code', 'like', $codePrefix . '%')
->where('expire_in', '>', $now)
->count();
if ((int) $active >= self::ACTIVE_CODE_LIMIT) {
return [
'ok' => false,
'msg' => '验证码请求次数过多,请稍后再试',
'retry_after' => self::SEND_COOLDOWN_SECONDS,
];
}
$plainCode = (string) random_int(100000, 999999);
$verification = new EmailVerify();
$verification->email = $newEmail;
$verification->ip = self::normalizeIp($clientIp);
$verification->code = $codePrefix . $plainCode;
$verification->expire_in = $now + (int) CaptchaConfig::get('email_verify_ttl');
if (!$verification->save()) {
return ['ok' => false, 'msg' => '验证码发送失败,请稍后重试', 'retry_after' => 0];
}
try {
$sent = Mail::send(
$newEmail,
Config::get('appName') . ' - 修改邮箱验证',
'auth/verify.tpl',
[
'code' => $plainCode,
'expire' => date('Y-m-d H:i:s', $verification->expire_in),
'language' => 'false',
'scene' => 'email_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,
];
}
/**
* @return array{ok:bool,msg:string,status:int,email?:string}
*/
public static function change(
User $user,
$newEmail,
$currentPassword,
$emailCode,
?RedisClient $redis = null
): array
{
$newEmail = self::normalizeEmail($newEmail);
$currentPassword = is_string($currentPassword) ? $currentPassword : '';
$emailCode = is_scalar($emailCode) ? trim((string) $emailCode) : '';
$userId = (int) $user->id;
if ($userId < 1 || $newEmail === null) {
return ['ok' => false, 'msg' => '请输入有效的新邮箱地址', 'status' => 422];
}
if (!preg_match('/^\d{6}$/D', $emailCode)) {
return ['ok' => false, 'msg' => '请输入发送到新邮箱的 6 位验证码', 'status' => 422];
}
if (Mail::isRecipientBlacklisted($newEmail)) {
return ['ok' => false, 'msg' => '该邮箱暂时不可使用', 'status' => 422];
}
$redis = $redis ?? new RedisClient();
$failureKey = self::factorFailureKey($userId);
if (self::factorFailures($redis, $failureKey) >= self::FACTOR_FAIL_LIMIT) {
return ['ok' => false, 'msg' => '验证码尝试次数过多,请稍后再试', 'status' => 429];
}
$connection = (new User())->getConnection();
try {
$result = $connection->transaction(
static function () use (
$userId,
$newEmail,
$currentPassword,
$emailCode
): array {
$locked = User::where('id', '=', $userId)->lockForUpdate()->first();
if ($locked === null) {
return ['ok' => false, 'msg' => '账户不存在', 'status' => 404];
}
if (!Hash::checkPassword($locked->pass, $currentPassword)) {
return [
'ok' => false,
'msg' => '当前密码错误',
'status' => 422,
'factor_failure' => true,
];
}
$currentEmail = self::normalizeEmail($locked->email);
if ($currentEmail === null) {
return ['ok' => false, 'msg' => '当前账户邮箱无效', 'status' => 422];
}
if (hash_equals($currentEmail, $newEmail)) {
return ['ok' => false, 'msg' => '新邮箱不能与当前邮箱相同', 'status' => 422];
}
if (User::where('email', '=', $newEmail)
->where('id', '<>', $userId)->exists()) {
return ['ok' => false, 'msg' => '该邮箱已被其他账户使用', 'status' => 409];
}
$verification = EmailVerify::where('email', '=', $newEmail)
->where('code', '=', self::codePrefixForUser($userId) . $emailCode)
->where('expire_in', '>', time())
->lockForUpdate()
->first();
if ($verification === null) {
return [
'ok' => false,
'msg' => '新邮箱验证码不正确或已过期',
'status' => 422,
'factor_failure' => true,
];
}
// Consume every outstanding code issued by this account
// for the verified target without touching another
// account's pending verification for the same address.
EmailVerify::where('email', '=', $newEmail)
->where('code', 'like', self::codePrefixForUser($userId) . '%')
->delete();
$locked->email = $newEmail;
if (!$locked->save()) {
throw new \RuntimeException('账户邮箱保存失败');
}
LoginSessionRevocationService::revokeUser($locked);
return [
'ok' => true,
'msg' => '邮箱修改成功,请使用新邮箱重新登录',
'status' => 200,
'email' => $newEmail,
];
},
3
);
} catch (QueryException $exception) {
if (self::isDuplicateEmailException($exception)) {
return ['ok' => false, 'msg' => '该邮箱已被其他账户使用', 'status' => 409];
}
throw $exception;
}
if (($result['factor_failure'] ?? false) === true) {
self::recordFactorFailure($redis, $failureKey);
} elseif (($result['ok'] ?? false) === true) {
self::clearFactorFailures($redis, $failureKey);
}
unset($result['factor_failure']);
return $result;
}
private static function normalizeEmail($value): ?string
{
if (!is_scalar($value)) {
return null;
}
$email = strtolower(trim((string) $value));
if ($email === '' || strlen($email) > 254
|| filter_var($email, FILTER_VALIDATE_EMAIL) === false) {
return null;
}
return $email;
}
private static function normalizeIp($value): string
{
if (!is_scalar($value)) {
return '0.0.0.0';
}
$ip = trim((string) $value);
return $ip === '' ? '0.0.0.0' : substr($ip, 0, 128);
}
private static function sendCooldownKey(User $user): string
{
return 'account_email_change_verify_send:' . (int) $user->id;
}
private static function codePrefixForUser(int $userId): string
{
return self::CODE_PREFIX . $userId . ':';
}
private static function factorFailureKey(int $userId): string
{
return 'account_email_change_verify_fail:' . $userId;
}
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) {
// The database active-code limit remains the durable fallback.
return true;
}
}
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) {
// Verification still fails closed if Redis is unavailable.
}
}
private static function clearFactorFailures(RedisClient $redis, string $key): void
{
try {
$redis->del($key);
} catch (\Throwable $exception) {
// A stale counter only affects abuse throttling.
}
}
private static function isDuplicateEmailException(QueryException $exception): bool
{
$message = strtolower($exception->getMessage());
return (string) $exception->getCode() === '23000'
|| str_contains($message, 'duplicate entry')
|| str_contains($message, 'unique constraint');
}
}