| 123456789101112131415161718192021222324252627282930313233343536373839404142 |
- <?php
- declare(strict_types=1);
- namespace app\miniapi\middleware;
- use Webman\Http\Request;
- use Webman\Http\Response;
- use Webman\MiddlewareInterface;
- use app\miniapi\auth\TokenVerifier;
- use app\miniapi\exception\ApiException;
- final class Authenticate implements MiddlewareInterface
- {
- public function process(Request $request, callable $handler): Response
- {
- $request->miniPrincipal = null;
- $header = (string) $request->header('authorization', '');
- if (!preg_match('/^Bearer ([A-Za-z0-9._~+\/-]{1,4096}=*)$/D', $header, $match) || strlen($header) > 4103) {
- throw new ApiException(40101, '请先登录', 401);
- }
- $class = config('mini_api.token_verifier');
- if (!$class) {
- throw new ApiException(50301, '小程序登录服务尚未接入', 503);
- }
- if (!is_string($class) || !is_subclass_of($class, TokenVerifier::class)) {
- throw new \LogicException('Invalid mini API token verifier');
- }
- $request->miniPrincipal = (new $class())->verify($match[1]);
- if (config('mini_protection.enabled', false)) {
- (new \app\miniapi\protection\TrafficGuard())->check(
- 'account',
- $request->miniPrincipal->userId,
- \app\miniapi\protection\RequestProfile::endpoint($request),
- $request->miniListCost ?? \app\miniapi\protection\RequestProfile::listCost($request),
- \app\miniapi\http\ApiResponse::requestId($request)
- );
- }
- return $handler($request);
- }
- }
|