首页转入默认赛事

master
weizong song 6 months ago
parent 4d2e73552e
commit eb3143ee84

@ -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。

@ -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]);
}
}

@ -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()

@ -0,0 +1,48 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class SmsVerification extends Model
{
public const SCENE_PARTICIPANT_LOGIN = 'participant_login';
public const PROVIDER_DISABLED = 'disabled';
public const PROVIDER_TENCENTCLOUD = 'tencentcloud';
public const STATUS_PENDING = 'pending';
public const STATUS_SENT = 'sent';
public const STATUS_FAILED = 'failed';
public const STATUS_USED = 'used';
public const STATUS_EXPIRED = 'expired';
protected $fillable = [
'scene',
'mobile',
'code',
'provider',
'status',
'template_id',
'sign_name',
'request_payload_json',
'response_json',
'provider_request_id',
'provider_code',
'provider_message',
'sent_at',
'failed_at',
'used_at',
'expires_at',
];
protected $casts = [
'request_payload_json' => 'array',
'response_json' => 'array',
'sent_at' => 'datetime',
'failed_at' => 'datetime',
'used_at' => 'datetime',
'expires_at' => 'datetime',
];
}

@ -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);
});
}
/**

@ -1,81 +0,0 @@
<?php
namespace App\Services;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;
/**
* 与 wx.sstbc.com app/Http/functions.php 中 ymSms() 相同通道与签名规则。
*/
class BtomSmsService
{
public function sendContent(string $mobile, string $content): bool
{
$appId = (string) config('sms.app_id');
$secret = (string) config('sms.secret');
$url = (string) config('sms.gateway');
if ($appId === '' || $secret === '') {
Log::warning('SMS skipped: SMS_APPID or SMS_SECRETKEY empty');
return false;
}
$timestamp = date('YmdHis');
$params = [
'appId' => $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;
}
}

@ -0,0 +1,19 @@
<?php
namespace App\Services\Sms;
use App\Models\SmsVerification;
class DisabledSmsSender implements SmsSender
{
public function sendVerification(SmsVerification $record): SmsSendResult
{
return SmsSendResult::success(
SmsVerification::PROVIDER_DISABLED,
null,
'DISABLED_OK',
'SMS_ENABLED=false; provider call skipped.',
['disabled' => true]
);
}
}

@ -0,0 +1,45 @@
<?php
namespace App\Services\Sms;
class SmsSendResult
{
/**
* @param array<string, mixed>|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<string, mixed>|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<string, mixed>|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);
}
}

@ -0,0 +1,10 @@
<?php
namespace App\Services\Sms;
use App\Models\SmsVerification;
interface SmsSender
{
public function sendVerification(SmsVerification $record): SmsSendResult;
}

@ -0,0 +1,187 @@
<?php
namespace App\Services\Sms;
use App\Models\SmsVerification;
use App\Support\SmsConfig;
use Illuminate\Support\Facades\Http;
class TencentCloudSmsSender implements SmsSender
{
private const ACTION = 'SendSms';
private const VERSION = '2021-01-11';
private const SERVICE = 'sms';
private const ALGORITHM = 'TC3-HMAC-SHA256';
public function sendVerification(SmsVerification $record): SmsSendResult
{
try {
SmsConfig::assertReadyForRealSending();
} catch (\Throwable $e) {
return SmsSendResult::failure(
SmsVerification::PROVIDER_TENCENTCLOUD,
null,
'CONFIG_INCOMPLETE',
$e->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<string, string>
*/
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<string, mixed> $response
* @return array<string, mixed>
*/
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'),
];
}
}

@ -0,0 +1,58 @@
<?php
namespace App\Support;
use RuntimeException;
class SmsConfig
{
/**
* Tencent Cloud SendSms uses Cloud API 3.0 authentication. SmsSdkAppId is
* a business parameter, not an API credential.
*
* @return array<string, string>
*/
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)
);
}
}
}

@ -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', '邮箱登陆验证码'),

@ -0,0 +1,56 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up(): void
{
Schema::table('sms_verifications', function (Blueprint $table) {
$table->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',
]);
});
}
};

@ -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 () {

@ -0,0 +1,380 @@
<?php
namespace Tests\Feature;
use App\Models\Competition;
use App\Models\SmsVerification;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Http\Client\Request;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Schema;
use Tests\TestCase;
class AuthSmsControllerTest extends TestCase
{
protected function setUp(): void
{
parent::setUp();
config([
'app.url' => '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();
});
}
}
Loading…
Cancel
Save