AdminAuthCheck.php 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839
  1. <?php
  2. namespace app\middleware;
  3. use Tinywan\Jwt\Exception\JwtTokenException;
  4. use Tinywan\Jwt\JwtToken;
  5. use Webman\Http\Request;
  6. use Webman\Http\Response;
  7. use Webman\MiddlewareInterface;
  8. class AdminAuthCheck implements MiddlewareInterface
  9. {
  10. public function process(Request $request, callable $handler): Response
  11. {
  12. try {
  13. // 跳过不需要验证的控制器方法
  14. $controller = new \ReflectionClass($request->controller);
  15. $notNeedLogin = $controller->getDefaultProperties()['notNeedLogin'] ?? [];
  16. if (in_array($request->action, $notNeedLogin)) {
  17. return $handler($request);
  18. }
  19. $token = $request->header('Authorization');
  20. if (!$token) {
  21. throw new JwtTokenException('请先登录~', 500);
  22. }
  23. if (strpos($token, 'Bearer') === 0) {
  24. $token = trim(substr($token, 6));
  25. }
  26. JwtToken::verify(1, $token);
  27. $request->adminId = JwtToken::getCurrentId();
  28. $request->adminJwtInfo = JwtToken::getExtend();
  29. return $handler($request);
  30. } catch (JwtTokenException $e) {
  31. return json_fail($e->getMessage());
  32. }
  33. }
  34. }