WechatAuthCheck.php 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  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 WechatAuthCheck implements MiddlewareInterface
  9. {
  10. /**
  11. * @inheritDoc
  12. */
  13. public function process(Request $request, callable $handler): Response
  14. {
  15. try {
  16. // 跳过不需要验证的控制器方法
  17. $controller = new \ReflectionClass($request->controller);
  18. $notNeedLogin = $controller->getDefaultProperties()['notNeedLogin'] ?? [];
  19. if (in_array($request->action, $notNeedLogin)) {
  20. return $handler($request);
  21. }
  22. $token = $request->header('Authorization');
  23. if (!$token) {
  24. throw new JwtTokenException('请先登录~', 500);
  25. }
  26. if (strpos($token, 'Bearer') === 0) {
  27. $token = trim(substr($token, 6));
  28. }
  29. JwtToken::verify(1, $token);
  30. $request->user_id = JwtToken::getCurrentId();
  31. $request->userInfo = JwtToken::getExtend();
  32. return $handler($request);
  33. } catch (JwtTokenException $e) {
  34. return json_fail($e->getMessage());
  35. }
  36. }
  37. }