From eb3143ee8472637c81bce910e7f7df70c442d745 Mon Sep 17 00:00:00 2001 From: weizong song Date: Fri, 5 Jun 2026 23:39:13 +0800 Subject: [PATCH] =?UTF-8?q?=E9=A6=96=E9=A1=B5=E8=BD=AC=E5=85=A5=E9=BB=98?= =?UTF-8?q?=E8=AE=A4=E8=B5=9B=E4=BA=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .env.example | 3 +- .../Controllers/Api/AuthSmsController.php | 156 +++++-- .../Api/PublicCompetitionController.php | 19 + app/Models/SmsVerification.php | 48 +++ app/Providers/AppServiceProvider.php | 9 +- app/Services/BtomSmsService.php | 81 ---- app/Services/Sms/DisabledSmsSender.php | 19 + app/Services/Sms/SmsSendResult.php | 45 +++ app/Services/Sms/SmsSender.php | 10 + app/Services/Sms/TencentCloudSmsSender.php | 187 +++++++++ app/Support/SmsConfig.php | 58 +++ config/sms.php | 8 +- ..._100000_extend_sms_verifications_table.php | 56 +++ routes/api.php | 1 + tests/Feature/AuthSmsControllerTest.php | 380 ++++++++++++++++++ 15 files changed, 966 insertions(+), 114 deletions(-) create mode 100644 app/Models/SmsVerification.php delete mode 100644 app/Services/BtomSmsService.php create mode 100644 app/Services/Sms/DisabledSmsSender.php create mode 100644 app/Services/Sms/SmsSendResult.php create mode 100644 app/Services/Sms/SmsSender.php create mode 100644 app/Services/Sms/TencentCloudSmsSender.php create mode 100644 app/Support/SmsConfig.php create mode 100644 database/migrations/2026_06_05_100000_extend_sms_verifications_table.php create mode 100644 tests/Feature/AuthSmsControllerTest.php diff --git a/.env.example b/.env.example index 61287d3..46bfb88 100644 --- a/.env.example +++ b/.env.example @@ -37,8 +37,9 @@ SMS_CODE_TTL_SECONDS=300 TENCENT_SMS_ENDPOINT=sms.tencentcloudapi.com TENCENT_SMS_REGION=ap-guangzhou +TENCENTCLOUD_SECRET_ID= +TENCENTCLOUD_SECRET_KEY= TENCENT_SMS_SDK_APP_ID= -TENCENT_SMS_APP_KEY= TENCENT_SMS_SIGN_NAME=元禾控股 # 当前模板变量数量与正式模板保持一致,后续正式切换只需要替换 TENCENT_SMS_TEMPLATE_ID。 diff --git a/app/Http/Controllers/Api/AuthSmsController.php b/app/Http/Controllers/Api/AuthSmsController.php index cdc32e2..b7d42c2 100644 --- a/app/Http/Controllers/Api/AuthSmsController.php +++ b/app/Http/Controllers/Api/AuthSmsController.php @@ -5,8 +5,9 @@ namespace App\Http\Controllers\Api; use App\Http\Controllers\Controller; use App\Models\Application; use App\Models\Competition; +use App\Models\SmsVerification; use App\Models\User; -use App\Services\BtomSmsService; +use App\Services\Sms\SmsSender; use Illuminate\Http\JsonResponse; use Illuminate\Http\Request; use Illuminate\Support\Facades\Cache; @@ -31,7 +32,7 @@ class AuthSmsController extends Controller return substr($mobile, 0, 3).'****'.substr($mobile, -4); } - public function send(Request $request, BtomSmsService $sms): JsonResponse + public function send(Request $request, SmsSender $sender): JsonResponse { $data = $request->validate([ 'mobile' => ['required', 'regex:/^1[3-9]\d{9}$/'], @@ -60,49 +61,112 @@ class AuthSmsController extends Controller } $code = (string) random_int(100000, 999999); - $smsSign = (string) config('sms.sign'); - $content = "{$smsSign}您的验证码是:{$code},验证码五分钟内有效,如非本人操作,请忽略。"; - $smsEnabled = (bool) config('sms.enabled'); + $ttlSeconds = (int) config('sms.code_ttl_seconds', 300); + $ttlMinutes = (string) (int) ceil($ttlSeconds / 60); Log::info('sms.send branch', [ 'mobile_mask' => $this->maskMobile($mobile), 'sms_enabled' => (bool) config('sms.enabled'), ]); - if (! $smsEnabled) { - Cache::put($key, ['code' => $code, 'time' => time()], 300); + $verification = SmsVerification::query()->create([ + 'scene' => SmsVerification::SCENE_PARTICIPANT_LOGIN, + 'mobile' => $mobile, + 'code' => $code, + 'provider' => $smsEnabled + ? SmsVerification::PROVIDER_TENCENTCLOUD + : SmsVerification::PROVIDER_DISABLED, + 'status' => SmsVerification::STATUS_PENDING, + 'template_id' => (string) config('sms.tencentcloud.template_id'), + 'sign_name' => (string) config('sms.tencentcloud.sign_name'), + 'request_payload_json' => [ + 'phone_number' => $this->maskMobile($mobile), + 'template_id' => (string) config('sms.tencentcloud.template_id'), + 'sign_name' => (string) config('sms.tencentcloud.sign_name'), + 'template_param_count' => (int) config('sms.tencentcloud.template_param_count', 2), + 'ttl_minutes' => $ttlMinutes, + ], + 'expires_at' => now()->addSeconds($ttlSeconds), + ]); - Log::info('sms.send disabled cache_set', [ + try { + $result = $sender->sendVerification($verification); + } catch (\Throwable $e) { + $verification->forceFill([ + 'status' => SmsVerification::STATUS_FAILED, + 'failed_at' => now(), + 'provider_code' => 'SENDER_EXCEPTION', + 'provider_message' => $e->getMessage(), + 'response_json' => ['error' => 'sender_exception'], + ])->save(); + + Log::error('sms.send sender_exception', [ 'mobile_mask' => $this->maskMobile($mobile), - 'ttl_sec' => 300, + 'verification_id' => $verification->id, + 'error' => $e->getMessage(), ]); return response()->json([ - 'message' => '发送成功', - ]); + 'message' => '发送失败', + ], 503); } - Log::info('sms.send gateway_call', ['mobile_mask' => $this->maskMobile($mobile)]); - - $result = $sms->sendContent($mobile, $content); - if (! $result) { - Log::warning('sms.send gateway_failed', ['mobile_mask' => $this->maskMobile($mobile)]); + if (! $result->success) { + $verification->forceFill([ + 'status' => SmsVerification::STATUS_FAILED, + 'failed_at' => now(), + 'provider_request_id' => $result->requestId, + 'provider_code' => $result->providerCode, + 'provider_message' => $result->providerMessage, + 'response_json' => $result->response, + ])->save(); + + Log::error('sms.send failed', [ + 'mobile_mask' => $this->maskMobile($mobile), + 'verification_id' => $verification->id, + 'provider' => $result->provider, + 'provider_request_id' => $result->requestId, + 'provider_code' => $result->providerCode, + 'provider_message' => $result->providerMessage, + ]); return response()->json([ - 'message' => '发送失败', - ], 422); + 'message' => $result->providerCode === 'CONFIG_INCOMPLETE' + ? '短信服务配置未完成' + : '发送失败', + ], 503); } - Cache::put($key, ['code' => $code, 'time' => time()], 300); + $verification->forceFill([ + 'status' => SmsVerification::STATUS_SENT, + 'sent_at' => now(), + 'provider_request_id' => $result->requestId, + 'provider_code' => $result->providerCode, + 'provider_message' => $result->providerMessage, + 'response_json' => $result->response, + ])->save(); + + $this->expirePreviousVerifications($mobile, $verification->id); + Cache::put($key, ['code' => $code, 'time' => time()], $ttlSeconds); - Log::info('sms.send gateway_ok cache_set', [ + Log::info('sms.send sent', [ 'mobile_mask' => $this->maskMobile($mobile), + 'verification_id' => $verification->id, + 'provider' => $result->provider, + 'provider_request_id' => $result->requestId, + 'provider_code' => $result->providerCode, ]); - return response()->json([ + $payload = [ 'message' => '发送成功', - ]); + ]; + + if (! $smsEnabled && app()->environment('local', 'testing')) { + $payload['debug_code'] = $code; + } + + return response()->json($payload); } public function login(Request $request): JsonResponse @@ -113,17 +177,35 @@ class AuthSmsController extends Controller 'competition_slug' => ['required', 'string', 'max:64'], ]); - $key = $this->cacheKey($data['mobile']); - $cached = Cache::get($key); + $verification = SmsVerification::query() + ->where('scene', SmsVerification::SCENE_PARTICIPANT_LOGIN) + ->where('mobile', $data['mobile']) + ->where('status', SmsVerification::STATUS_SENT) + ->where('expires_at', '>', now()) + ->latest('id') + ->first(); - if (! is_array($cached) || ($cached['code'] ?? null) !== $data['code']) { + if ($verification === null || $verification->code !== $data['code']) { throw ValidationException::withMessages([ 'code' => ['验证码无效或已过期'], ]); } - $user = DB::transaction(function () use ($data, $key) { - Cache::forget($key); + $user = DB::transaction(function () use ($data, $verification) { + $verification = SmsVerification::query() + ->whereKey($verification->id) + ->where('scene', SmsVerification::SCENE_PARTICIPANT_LOGIN) + ->where('mobile', $data['mobile']) + ->where('status', SmsVerification::STATUS_SENT) + ->where('expires_at', '>', now()) + ->lockForUpdate() + ->first(); + + if ($verification === null || $verification->code !== $data['code']) { + throw ValidationException::withMessages([ + 'code' => ['验证码无效或已过期'], + ]); + } $competition = Competition::query() ->where('slug', $data['competition_slug']) @@ -149,6 +231,13 @@ class AuthSmsController extends Controller ['status' => 'draft'] ); + $verification->forceFill([ + 'status' => SmsVerification::STATUS_USED, + 'used_at' => now(), + ])->save(); + + Cache::forget($this->cacheKey($data['mobile'])); + return $user; }); @@ -166,4 +255,17 @@ class AuthSmsController extends Controller ], ]); } + + private function expirePreviousVerifications(string $mobile, int $currentId): void + { + SmsVerification::query() + ->where('scene', SmsVerification::SCENE_PARTICIPANT_LOGIN) + ->where('mobile', $mobile) + ->where('id', '<>', $currentId) + ->whereIn('status', [ + SmsVerification::STATUS_PENDING, + SmsVerification::STATUS_SENT, + ]) + ->update(['status' => SmsVerification::STATUS_EXPIRED]); + } } diff --git a/app/Http/Controllers/Api/PublicCompetitionController.php b/app/Http/Controllers/Api/PublicCompetitionController.php index 25ec157..abff164 100644 --- a/app/Http/Controllers/Api/PublicCompetitionController.php +++ b/app/Http/Controllers/Api/PublicCompetitionController.php @@ -8,6 +8,25 @@ use Illuminate\Http\JsonResponse; class PublicCompetitionController extends Controller { + public function active(): JsonResponse + { + $competition = Competition::query() + ->where('published', true) + ->where('status', 'signup_open') + ->orderByDesc('signup_open_at') + ->orderByDesc('id') + ->firstOrFail(); + + return response()->json([ + 'id' => $competition->id, + 'slug' => $competition->slug, + 'name' => $competition->name, + 'status' => $competition->status, + 'signup_open_at' => $competition->signup_open_at?->toIso8601String(), + 'signup_close_at' => $competition->signup_close_at?->toIso8601String(), + ]); + } + public function showBySlug(string $slug): JsonResponse { $competition = Competition::query() diff --git a/app/Models/SmsVerification.php b/app/Models/SmsVerification.php new file mode 100644 index 0000000..6be8b7f --- /dev/null +++ b/app/Models/SmsVerification.php @@ -0,0 +1,48 @@ + 'array', + 'response_json' => 'array', + 'sent_at' => 'datetime', + 'failed_at' => 'datetime', + 'used_at' => 'datetime', + 'expires_at' => 'datetime', + ]; +} diff --git a/app/Providers/AppServiceProvider.php b/app/Providers/AppServiceProvider.php index 6a56508..1823ad7 100644 --- a/app/Providers/AppServiceProvider.php +++ b/app/Providers/AppServiceProvider.php @@ -2,6 +2,9 @@ namespace App\Providers; +use App\Services\Sms\DisabledSmsSender; +use App\Services\Sms\SmsSender; +use App\Services\Sms\TencentCloudSmsSender; use Illuminate\Support\Facades\URL; use Illuminate\Support\ServiceProvider; @@ -12,7 +15,11 @@ class AppServiceProvider extends ServiceProvider */ public function register(): void { - // + $this->app->bind(SmsSender::class, function ($app) { + return (bool) config('sms.enabled') + ? $app->make(TencentCloudSmsSender::class) + : $app->make(DisabledSmsSender::class); + }); } /** diff --git a/app/Services/BtomSmsService.php b/app/Services/BtomSmsService.php deleted file mode 100644 index 5510a21..0000000 --- a/app/Services/BtomSmsService.php +++ /dev/null @@ -1,81 +0,0 @@ - $appId, - 'timestamp' => $timestamp, - 'mobiles' => $mobile, - 'content' => $content, - ]; - $params['sign'] = md5($appId.$secret.$timestamp); - - Log::info('sms.gateway request', [ - 'url' => $url, - 'mobile_mask' => strlen($mobile) >= 11 - ? substr($mobile, 0, 3).'****'.substr($mobile, -4) - : '***', - 'app_id_len' => strlen($appId), - 'timestamp' => $timestamp, - ]); - - try { - $response = Http::timeout((int) config('sms.timeout', 5)) - ->withHeaders(['Content-Type' => 'application/json']) - ->get($url, $params); - } catch (\Throwable $e) { - Log::error('SMS request failed', ['exception' => $e->getMessage()]); - - return false; - } - - $status = $response->status(); - $bodySnippet = substr($response->body(), 0, 500); - Log::info('sms.gateway response', [ - 'http_status' => $status, - 'body_preview' => $bodySnippet, - ]); - - $return = $response->json(); - if (! is_array($return)) { - Log::error('SMS invalid JSON', ['body' => $response->body()]); - - return false; - } - - if (($return['code'] ?? '') !== 'SUCCESS') { - Log::warning('SMS gateway error', array_merge($return, ['http_status' => $status])); - - return false; - } - - Log::info('sms.gateway success', [ - 'mobile_mask' => strlen($mobile) >= 11 - ? substr($mobile, 0, 3).'****'.substr($mobile, -4) - : '***', - ]); - - return true; - } -} diff --git a/app/Services/Sms/DisabledSmsSender.php b/app/Services/Sms/DisabledSmsSender.php new file mode 100644 index 0000000..3365ecd --- /dev/null +++ b/app/Services/Sms/DisabledSmsSender.php @@ -0,0 +1,19 @@ + true] + ); + } +} diff --git a/app/Services/Sms/SmsSendResult.php b/app/Services/Sms/SmsSendResult.php new file mode 100644 index 0000000..1d19b14 --- /dev/null +++ b/app/Services/Sms/SmsSendResult.php @@ -0,0 +1,45 @@ +|null $response + */ + public function __construct( + public readonly bool $success, + public readonly string $provider, + public readonly ?string $requestId = null, + public readonly ?string $providerCode = null, + public readonly ?string $providerMessage = null, + public readonly ?array $response = null, + ) { + } + + /** + * @param array|null $response + */ + public static function success( + string $provider, + ?string $requestId = null, + ?string $providerCode = null, + ?string $providerMessage = null, + ?array $response = null, + ): self { + return new self(true, $provider, $requestId, $providerCode, $providerMessage, $response); + } + + /** + * @param array|null $response + */ + public static function failure( + string $provider, + ?string $requestId = null, + ?string $providerCode = null, + ?string $providerMessage = null, + ?array $response = null, + ): self { + return new self(false, $provider, $requestId, $providerCode, $providerMessage, $response); + } +} diff --git a/app/Services/Sms/SmsSender.php b/app/Services/Sms/SmsSender.php new file mode 100644 index 0000000..74a476c --- /dev/null +++ b/app/Services/Sms/SmsSender.php @@ -0,0 +1,10 @@ +getMessage(), + ['error' => 'config_incomplete'] + ); + } + + $endpoint = (string) config('sms.tencentcloud.endpoint'); + $region = (string) config('sms.tencentcloud.region'); + $secretId = (string) config('sms.tencentcloud.secret_id'); + $secretKey = (string) config('sms.tencentcloud.secret_key'); + $timeout = (int) config('sms.timeout', 5); + + $payload = [ + 'PhoneNumberSet' => ['+86'.$record->mobile], + 'SmsSdkAppId' => (string) config('sms.tencentcloud.sdk_app_id'), + 'SignName' => (string) config('sms.tencentcloud.sign_name'), + 'TemplateId' => (string) config('sms.tencentcloud.template_id'), + 'TemplateParamSet' => [ + (string) $record->code, + (string) data_get($record->request_payload_json, 'ttl_minutes', '5'), + ], + ]; + + $body = json_encode($payload, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES); + if ($body === false) { + return SmsSendResult::failure( + SmsVerification::PROVIDER_TENCENTCLOUD, + null, + 'PAYLOAD_ENCODE_FAILED', + 'Tencent Cloud SMS payload encode failed.', + ['error' => 'payload_encode_failed'] + ); + } + + $timestamp = time(); + $headers = $this->buildHeaders($endpoint, $region, $secretId, $secretKey, $timestamp, $body); + + try { + $response = Http::timeout($timeout) + ->withHeaders($headers) + ->withBody($body, 'application/json; charset=utf-8') + ->post('https://'.$endpoint); + } catch (\Throwable $e) { + return SmsSendResult::failure( + SmsVerification::PROVIDER_TENCENTCLOUD, + null, + 'NETWORK_ERROR', + $e->getMessage(), + ['error' => 'network_error'] + ); + } + + $json = $response->json(); + if (! is_array($json)) { + return SmsSendResult::failure( + SmsVerification::PROVIDER_TENCENTCLOUD, + null, + 'INVALID_RESPONSE', + 'Tencent Cloud SMS returned a non-json response.', + ['http_status' => $response->status()] + ); + } + + $tencentResponse = data_get($json, 'Response', []); + $requestId = data_get($tencentResponse, 'RequestId'); + + if (data_get($tencentResponse, 'Error.Code')) { + return SmsSendResult::failure( + SmsVerification::PROVIDER_TENCENTCLOUD, + is_string($requestId) ? $requestId : null, + (string) data_get($tencentResponse, 'Error.Code'), + (string) data_get($tencentResponse, 'Error.Message'), + $this->responseSummary($json) + ); + } + + $status = data_get($tencentResponse, 'SendStatusSet.0', []); + $providerCode = (string) data_get($status, 'Code', ''); + $providerMessage = (string) data_get($status, 'Message', ''); + + if ($response->successful() && $providerCode === 'Ok') { + return SmsSendResult::success( + SmsVerification::PROVIDER_TENCENTCLOUD, + is_string($requestId) ? $requestId : null, + $providerCode, + $providerMessage, + $this->responseSummary($json) + ); + } + + return SmsSendResult::failure( + SmsVerification::PROVIDER_TENCENTCLOUD, + is_string($requestId) ? $requestId : null, + $providerCode !== '' ? $providerCode : 'HTTP_'.$response->status(), + $providerMessage !== '' ? $providerMessage : 'Tencent Cloud SMS send failed.', + $this->responseSummary($json) + ); + } + + /** + * @return array + */ + private function buildHeaders( + string $host, + string $region, + string $secretId, + string $secretKey, + int $timestamp, + string $payload, + ): array { + $date = gmdate('Y-m-d', $timestamp); + $canonicalHeaders = "content-type:application/json; charset=utf-8\nhost:{$host}\n"; + $signedHeaders = 'content-type;host'; + $canonicalRequest = implode("\n", [ + 'POST', + '/', + '', + $canonicalHeaders, + $signedHeaders, + hash('sha256', $payload), + ]); + + $credentialScope = $date.'/'.self::SERVICE.'/tc3_request'; + $stringToSign = implode("\n", [ + self::ALGORITHM, + (string) $timestamp, + $credentialScope, + hash('sha256', $canonicalRequest), + ]); + + $secretDate = hash_hmac('sha256', $date, 'TC3'.$secretKey, true); + $secretService = hash_hmac('sha256', self::SERVICE, $secretDate, true); + $secretSigning = hash_hmac('sha256', 'tc3_request', $secretService, true); + $signature = hash_hmac('sha256', $stringToSign, $secretSigning); + + $authorization = self::ALGORITHM + .' Credential='.$secretId.'/'.$credentialScope + .', SignedHeaders='.$signedHeaders + .', Signature='.$signature; + + return [ + 'Authorization' => $authorization, + 'Content-Type' => 'application/json; charset=utf-8', + 'Host' => $host, + 'X-TC-Action' => self::ACTION, + 'X-TC-Region' => $region, + 'X-TC-Timestamp' => (string) $timestamp, + 'X-TC-Version' => self::VERSION, + ]; + } + + /** + * @param array $response + * @return array + */ + private function responseSummary(array $response): array + { + return [ + 'request_id' => data_get($response, 'Response.RequestId'), + 'error' => data_get($response, 'Response.Error'), + 'send_status_set' => data_get($response, 'Response.SendStatusSet'), + ]; + } +} diff --git a/app/Support/SmsConfig.php b/app/Support/SmsConfig.php new file mode 100644 index 0000000..a2c171a --- /dev/null +++ b/app/Support/SmsConfig.php @@ -0,0 +1,58 @@ + + */ + public static function realSendingRequiredEnv(): array + { + return [ + 'sms.tencentcloud.endpoint' => 'TENCENT_SMS_ENDPOINT', + 'sms.tencentcloud.region' => 'TENCENT_SMS_REGION', + 'sms.tencentcloud.secret_id' => 'TENCENTCLOUD_SECRET_ID', + 'sms.tencentcloud.secret_key' => 'TENCENTCLOUD_SECRET_KEY', + 'sms.tencentcloud.sdk_app_id' => 'TENCENT_SMS_SDK_APP_ID', + 'sms.tencentcloud.sign_name' => 'TENCENT_SMS_SIGN_NAME', + 'sms.tencentcloud.template_id' => 'TENCENT_SMS_TEMPLATE_ID', + ]; + } + + public static function assertReadyForRealSending(): void + { + if (! (bool) config('sms.enabled')) { + return; + } + + if ((string) config('sms.driver') !== 'tencentcloud') { + throw new RuntimeException('SMS_ENABLED=true requires SMS_DRIVER=tencentcloud.'); + } + + $missing = []; + foreach (self::realSendingRequiredEnv() as $configKey => $envName) { + $value = config($configKey); + if ($value === null || trim((string) $value) === '') { + $missing[] = $envName; + } + } + + if ((int) config('sms.tencentcloud.template_param_count') !== 2) { + $missing[] = 'TENCENT_SMS_TEMPLATE_PARAM_COUNT must be 2'; + } + + if ($missing !== []) { + throw new RuntimeException( + 'SMS_ENABLED=true but Tencent Cloud SMS configuration is incomplete. ' + .'SendSms uses Cloud API 3.0 and requires CAM credentials. Missing or invalid: ' + .implode(', ', $missing) + ); + } + } +} diff --git a/config/sms.php b/config/sms.php index 4f1ddf4..c990dfd 100644 --- a/config/sms.php +++ b/config/sms.php @@ -14,11 +14,10 @@ return [ 'timeout' => (int) env('SMS_HTTP_TIMEOUT', 5), /** - * 是否真实调用短信供应商。 - * 默认:local 环境为 false;非 local 环境为 true。 + * 是否真实调用短信供应商。默认关闭,避免缺省配置误触达外部供应商。 */ 'enabled' => filter_var( - env('SMS_ENABLED', env('APP_ENV') !== 'local'), + env('SMS_ENABLED', false), FILTER_VALIDATE_BOOLEAN ), @@ -31,8 +30,9 @@ return [ 'tencentcloud' => [ 'endpoint' => env('TENCENT_SMS_ENDPOINT', 'sms.tencentcloudapi.com'), 'region' => env('TENCENT_SMS_REGION', 'ap-guangzhou'), + 'secret_id' => env('TENCENTCLOUD_SECRET_ID'), + 'secret_key' => env('TENCENTCLOUD_SECRET_KEY'), 'sdk_app_id' => env('TENCENT_SMS_SDK_APP_ID'), - 'app_key' => env('TENCENT_SMS_APP_KEY'), 'sign_name' => env('TENCENT_SMS_SIGN_NAME', '元禾控股'), 'template_id' => env('TENCENT_SMS_TEMPLATE_ID'), 'template_name' => env('TENCENT_SMS_TEMPLATE_NAME', '邮箱登陆验证码'), diff --git a/database/migrations/2026_06_05_100000_extend_sms_verifications_table.php b/database/migrations/2026_06_05_100000_extend_sms_verifications_table.php new file mode 100644 index 0000000..c0c20dd --- /dev/null +++ b/database/migrations/2026_06_05_100000_extend_sms_verifications_table.php @@ -0,0 +1,56 @@ +string('scene', 64)->default('participant_login')->after('id'); + $table->string('provider', 32)->default('disabled')->after('code'); + $table->string('status', 16)->default('pending')->after('provider'); + $table->string('template_id', 64)->nullable()->after('status'); + $table->string('sign_name', 64)->nullable()->after('template_id'); + $table->json('request_payload_json')->nullable()->after('sign_name'); + $table->json('response_json')->nullable()->after('request_payload_json'); + $table->string('provider_request_id', 128)->nullable()->after('response_json'); + $table->string('provider_code', 128)->nullable()->after('provider_request_id'); + $table->string('provider_message', 500)->nullable()->after('provider_code'); + $table->timestamp('sent_at')->nullable()->after('expires_at'); + $table->timestamp('failed_at')->nullable()->after('sent_at'); + $table->timestamp('used_at')->nullable()->after('failed_at'); + + $table->index(['scene', 'mobile', 'created_at'], 'sms_verifications_scene_mobile_created_idx'); + $table->index(['scene', 'mobile', 'status', 'expires_at'], 'sms_verifications_scene_mobile_status_expires_idx'); + $table->index(['provider', 'provider_code', 'created_at'], 'sms_verifications_provider_code_created_idx'); + }); + } + + public function down(): void + { + Schema::table('sms_verifications', function (Blueprint $table) { + $table->dropIndex('sms_verifications_scene_mobile_created_idx'); + $table->dropIndex('sms_verifications_scene_mobile_status_expires_idx'); + $table->dropIndex('sms_verifications_provider_code_created_idx'); + + $table->dropColumn([ + 'scene', + 'provider', + 'status', + 'template_id', + 'sign_name', + 'request_payload_json', + 'response_json', + 'provider_request_id', + 'provider_code', + 'provider_message', + 'sent_at', + 'failed_at', + 'used_at', + ]); + }); + } +}; diff --git a/routes/api.php b/routes/api.php index a6476ff..1595c45 100644 --- a/routes/api.php +++ b/routes/api.php @@ -19,6 +19,7 @@ use App\Http\Controllers\Api\UserProfileController; use Illuminate\Support\Facades\Route; Route::prefix('v1')->group(function () { + Route::get('public/competitions/active', [PublicCompetitionController::class, 'active']); Route::get('public/competitions/by-slug/{slug}', [PublicCompetitionController::class, 'showBySlug']); Route::prefix('review')->group(function () { diff --git a/tests/Feature/AuthSmsControllerTest.php b/tests/Feature/AuthSmsControllerTest.php new file mode 100644 index 0000000..6334441 --- /dev/null +++ b/tests/Feature/AuthSmsControllerTest.php @@ -0,0 +1,380 @@ + 'http://localhost', + 'cache.default' => 'array', + 'database.default' => 'sqlite', + 'database.connections.sqlite' => [ + 'driver' => 'sqlite', + 'database' => ':memory:', + 'prefix' => '', + 'foreign_key_constraints' => false, + ], + 'sms.driver' => 'tencentcloud', + 'sms.enabled' => false, + 'sms.resend_interval_seconds' => 60, + 'sms.code_ttl_seconds' => 300, + 'sms.tencentcloud.endpoint' => 'sms.tencentcloudapi.com', + 'sms.tencentcloud.region' => 'ap-guangzhou', + 'sms.tencentcloud.secret_id' => null, + 'sms.tencentcloud.secret_key' => null, + 'sms.tencentcloud.sdk_app_id' => null, + 'sms.tencentcloud.sign_name' => '元禾控股', + 'sms.tencentcloud.template_id' => '2175650', + 'sms.tencentcloud.template_param_count' => 2, + ]); + + DB::purge(); + DB::reconnect(); + Cache::flush(); + + $this->createSchema(); + } + + public function test_disabled_sender_creates_record_and_login_consumes_it(): void + { + $this->competition('main-event'); + + $send = $this->postJson('/api/auth/sms/send', [ + 'mobile' => '13800138000', + ])->assertOk(); + + $code = (string) $send->json('debug_code'); + $this->assertMatchesRegularExpression('/^\d{6}$/', $code); + + $record = SmsVerification::query()->firstOrFail(); + $this->assertSame(SmsVerification::STATUS_SENT, $record->status); + $this->assertSame(SmsVerification::PROVIDER_DISABLED, $record->provider); + $this->assertSame('DISABLED_OK', $record->provider_code); + $this->assertSame('138****8000', $record->request_payload_json['phone_number']); + $this->assertArrayNotHasKey('code', $record->request_payload_json); + + $this->postJson('/api/auth/sms/login', [ + 'mobile' => '13800138000', + 'code' => $code, + 'competition_slug' => 'main-event', + ])->assertOk() + ->assertJsonPath('token_type', 'Bearer'); + + $this->assertDatabaseHas('sms_verifications', [ + 'id' => $record->id, + 'status' => SmsVerification::STATUS_USED, + ]); + $this->assertDatabaseHas('applications', [ + 'competition_id' => Competition::query()->where('slug', 'main-event')->value('id'), + 'status' => 'draft', + ]); + + $this->postJson('/api/auth/sms/login', [ + 'mobile' => '13800138000', + 'code' => $code, + 'competition_slug' => 'main-event', + ])->assertUnprocessable(); + } + + public function test_enabled_sender_fails_fast_when_cloud_credentials_are_missing(): void + { + config(['sms.enabled' => true]); + Http::fake(); + + $this->postJson('/api/auth/sms/send', [ + 'mobile' => '13800138001', + ])->assertStatus(503) + ->assertJsonPath('message', '短信服务配置未完成'); + + $this->assertDatabaseHas('sms_verifications', [ + 'mobile' => '13800138001', + 'provider' => SmsVerification::PROVIDER_TENCENTCLOUD, + 'status' => SmsVerification::STATUS_FAILED, + 'provider_code' => 'CONFIG_INCOMPLETE', + ]); + Http::assertNothingSent(); + } + + public function test_disabled_sender_does_not_expose_debug_code_in_production(): void + { + $this->app->detectEnvironment(fn () => 'production'); + + $this->postJson('/api/auth/sms/send', [ + 'mobile' => '13800138006', + ])->assertOk() + ->assertJsonMissingPath('debug_code'); + + $this->assertDatabaseHas('sms_verifications', [ + 'mobile' => '13800138006', + 'provider' => SmsVerification::PROVIDER_DISABLED, + 'status' => SmsVerification::STATUS_SENT, + ]); + } + + public function test_enabled_sender_posts_tencent_cloud_template_parameters_and_marks_sent(): void + { + $this->enableTencentCloudConfig(); + Http::fake([ + 'https://sms.tencentcloudapi.com' => Http::response([ + 'Response' => [ + 'SendStatusSet' => [[ + 'SerialNo' => 'serial-1', + 'PhoneNumber' => '+8613800138002', + 'Fee' => 1, + 'SessionContext' => '', + 'Code' => 'Ok', + 'Message' => 'send success', + 'IsoCode' => 'CN', + ]], + 'RequestId' => 'request-1', + ], + ], 200), + ]); + + $this->postJson('/api/auth/sms/send', [ + 'mobile' => '13800138002', + ])->assertOk() + ->assertJsonMissingPath('debug_code'); + + Http::assertSent(function (Request $request): bool { + $payload = json_decode($request->body(), true); + + return $request->hasHeader('X-TC-Action', 'SendSms') + && $request->hasHeader('X-TC-Version', '2021-01-11') + && str_contains((string) $request->header('Authorization')[0], 'TC3-HMAC-SHA256 Credential=test-secret-id/') + && $payload['PhoneNumberSet'] === ['+8613800138002'] + && $payload['SmsSdkAppId'] === '1400000000' + && $payload['SignName'] === '元禾控股' + && $payload['TemplateId'] === '2175650' + && count($payload['TemplateParamSet']) === 2 + && preg_match('/^\d{6}$/', (string) $payload['TemplateParamSet'][0]) === 1 + && $payload['TemplateParamSet'][1] === '5'; + }); + + $this->assertDatabaseHas('sms_verifications', [ + 'mobile' => '13800138002', + 'provider' => SmsVerification::PROVIDER_TENCENTCLOUD, + 'status' => SmsVerification::STATUS_SENT, + 'provider_request_id' => 'request-1', + 'provider_code' => 'Ok', + ]); + } + + public function test_failed_new_send_keeps_previous_sent_code_usable(): void + { + $competition = $this->competition('main-event'); + $old = SmsVerification::query()->create([ + 'scene' => SmsVerification::SCENE_PARTICIPANT_LOGIN, + 'mobile' => '13800138003', + 'code' => '111111', + 'provider' => SmsVerification::PROVIDER_DISABLED, + 'status' => SmsVerification::STATUS_SENT, + 'expires_at' => now()->addMinutes(5), + ]); + + $this->enableTencentCloudConfig(); + Http::fake([ + 'https://sms.tencentcloudapi.com' => Http::response([ + 'Response' => [ + 'SendStatusSet' => [[ + 'Code' => 'FailedOperation.TemplateIncorrect', + 'Message' => 'template incorrect', + ]], + 'RequestId' => 'request-failed', + ], + ], 200), + ]); + + $this->postJson('/api/auth/sms/send', [ + 'mobile' => '13800138003', + ])->assertStatus(503) + ->assertJsonPath('message', '发送失败'); + + $this->assertDatabaseHas('sms_verifications', [ + 'id' => $old->id, + 'status' => SmsVerification::STATUS_SENT, + ]); + $this->assertDatabaseHas('sms_verifications', [ + 'mobile' => '13800138003', + 'status' => SmsVerification::STATUS_FAILED, + 'provider_request_id' => 'request-failed', + 'provider_code' => 'FailedOperation.TemplateIncorrect', + ]); + + $this->postJson('/api/auth/sms/login', [ + 'mobile' => '13800138003', + 'code' => '111111', + 'competition_slug' => $competition->slug, + ])->assertOk(); + } + + public function test_successful_new_send_expires_previous_sent_code(): void + { + $this->competition('main-event'); + $old = SmsVerification::query()->create([ + 'scene' => SmsVerification::SCENE_PARTICIPANT_LOGIN, + 'mobile' => '13800138007', + 'code' => '333333', + 'provider' => SmsVerification::PROVIDER_DISABLED, + 'status' => SmsVerification::STATUS_SENT, + 'expires_at' => now()->addMinutes(5), + ]); + + $this->enableTencentCloudConfig(); + Http::fake([ + 'https://sms.tencentcloudapi.com' => Http::response([ + 'Response' => [ + 'SendStatusSet' => [[ + 'Code' => 'Ok', + 'Message' => 'send success', + ]], + 'RequestId' => 'request-new', + ], + ], 200), + ]); + + $this->postJson('/api/auth/sms/send', [ + 'mobile' => '13800138007', + ])->assertOk(); + + $this->assertDatabaseHas('sms_verifications', [ + 'id' => $old->id, + 'status' => SmsVerification::STATUS_EXPIRED, + ]); + + $this->postJson('/api/auth/sms/login', [ + 'mobile' => '13800138007', + 'code' => '333333', + 'competition_slug' => 'main-event', + ])->assertUnprocessable() + ->assertJsonValidationErrors('code'); + } + + public function test_rate_limit_is_kept_after_successful_send(): void + { + $this->postJson('/api/auth/sms/send', [ + 'mobile' => '13800138004', + ])->assertOk(); + + $this->postJson('/api/auth/sms/send', [ + 'mobile' => '13800138004', + ])->assertUnprocessable() + ->assertJsonValidationErrors('mobile'); + } + + public function test_expired_sent_code_cannot_login(): void + { + $this->competition('main-event'); + SmsVerification::query()->create([ + 'scene' => SmsVerification::SCENE_PARTICIPANT_LOGIN, + 'mobile' => '13800138005', + 'code' => '222222', + 'provider' => SmsVerification::PROVIDER_DISABLED, + 'status' => SmsVerification::STATUS_SENT, + 'expires_at' => now()->subSecond(), + ]); + + $this->postJson('/api/auth/sms/login', [ + 'mobile' => '13800138005', + 'code' => '222222', + 'competition_slug' => 'main-event', + ])->assertUnprocessable() + ->assertJsonValidationErrors('code'); + } + + private function enableTencentCloudConfig(): void + { + config([ + 'sms.enabled' => true, + 'sms.tencentcloud.secret_id' => 'test-secret-id', + 'sms.tencentcloud.secret_key' => 'test-secret-key', + 'sms.tencentcloud.sdk_app_id' => '1400000000', + ]); + } + + private function competition(string $slug): Competition + { + return Competition::query()->create([ + 'slug' => $slug, + 'name' => '测试赛事', + 'status' => 'published', + 'published' => true, + ]); + } + + private function createSchema(): void + { + Schema::create('users', function (Blueprint $table) { + $table->id(); + $table->string('mobile')->unique(); + $table->string('name')->nullable(); + $table->string('email')->nullable(); + $table->string('password')->nullable(); + $table->timestamps(); + }); + + Schema::create('competitions', function (Blueprint $table) { + $table->id(); + $table->string('slug')->unique(); + $table->string('name'); + $table->string('status')->default('draft'); + $table->boolean('published')->default(false); + $table->timestamps(); + }); + + Schema::create('applications', function (Blueprint $table) { + $table->id(); + $table->foreignId('user_id'); + $table->foreignId('competition_id'); + $table->string('status')->default('draft'); + $table->timestamps(); + $table->unique(['user_id', 'competition_id']); + }); + + Schema::create('sms_verifications', function (Blueprint $table) { + $table->id(); + $table->string('scene', 64)->default('participant_login'); + $table->string('mobile', 20)->index(); + $table->string('code', 10); + $table->string('provider', 32)->default('disabled'); + $table->string('status', 16)->default('pending'); + $table->string('template_id', 64)->nullable(); + $table->string('sign_name', 64)->nullable(); + $table->json('request_payload_json')->nullable(); + $table->json('response_json')->nullable(); + $table->string('provider_request_id', 128)->nullable(); + $table->string('provider_code', 128)->nullable(); + $table->string('provider_message', 500)->nullable(); + $table->timestamp('expires_at'); + $table->timestamp('sent_at')->nullable(); + $table->timestamp('failed_at')->nullable(); + $table->timestamp('used_at')->nullable(); + $table->timestamps(); + }); + + Schema::create('personal_access_tokens', function (Blueprint $table) { + $table->id(); + $table->morphs('tokenable'); + $table->string('name'); + $table->string('token', 64)->unique(); + $table->text('abilities')->nullable(); + $table->timestamp('last_used_at')->nullable(); + $table->timestamp('expires_at')->nullable(); + $table->timestamps(); + }); + } +}