Files
lotteryLaravel/app/Http/Middleware/EnsurePlayerApi.php

45 lines
1.5 KiB
PHP
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
<?php
namespace App\Http\Middleware;
use Closure;
use App\Lottery\ErrorCode;
use App\Support\ApiResponse;
use Illuminate\Http\Request;
use App\Support\LotteryMessage;
use App\Services\PlayerTokenResolver;
use Symfony\Component\HttpFoundation\Response;
use App\Exceptions\PlayerAuthenticationException;
/**
* 【玩家端 API 鉴权中间件】
*
* - 成功:解析 Bearer → Player写入 request attribute `lottery_player`。
* - 失败:直接 JSON 返回,不进入控制器;其中 msg 经由 LotteryMessage::sso() 按请求语言翻译
* (依赖前置的 NegotiateLotteryLocalecode 为 {@see ErrorCode} 中玩家鉴权段。
*
* PlayerAuthenticationException 的 getMessage() 仅作开发与日志用语,可与 API msg 语种不一致。
*/
final class EnsurePlayerApi
{
public function handle(Request $request, Closure $next): Response
{
try {
$player = app(PlayerTokenResolver::class)->resolve($request);
} catch (PlayerAuthenticationException $e) {
// msg多语言用户提示code / httpStatus仍来自异常内业务定义
return ApiResponse::error(
LotteryMessage::sso($request, $e->lotteryCode),
$e->lotteryCode,
null,
$e->httpStatus,
);
}
// 使用 attributes避免与 Laravel 内置 input 混淆
$request->attributes->set('lottery_player', $player);
return $next($request);
}
}