123456789101112131415161718192021222324252627282930313233343536373839 |
- <?php
- namespace app\middleware;
- use Tinywan\Jwt\Exception\JwtTokenException;
- use Tinywan\Jwt\JwtToken;
- use Webman\Http\Request;
- use Webman\Http\Response;
- use Webman\MiddlewareInterface;
- class AdminAuthCheck implements MiddlewareInterface
- {
- public function process(Request $request, callable $handler): Response
- {
- try {
- // 跳过不需要验证的控制器方法
- $controller = new \ReflectionClass($request->controller);
- $notNeedLogin = $controller->getDefaultProperties()['notNeedLogin'] ?? [];
- if (in_array($request->action, $notNeedLogin)) {
- return $handler($request);
- }
- $token = $request->header('Authorization');
- if (!$token) {
- throw new JwtTokenException('请先登录~', 500);
- }
- if (strpos($token, 'Bearer') === 0) {
- $token = trim(substr($token, 6));
- }
- JwtToken::verify(1, $token);
- $request->adminId = JwtToken::getCurrentId();
- $request->adminJwtInfo = JwtToken::getExtend();
- return $handler($request);
- } catch (JwtTokenException $e) {
- return json_fail($e->getMessage());
- }
- }
- }
|