AuthTokenMiddleware.php 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. <?php
  2. namespace app\http\middleware;
  3. use app\models\user\User;
  4. use app\models\user\UserToken;
  5. use app\Request;
  6. use crmeb\exceptions\AuthException;
  7. use crmeb\interfaces\MiddlewareInterface;
  8. use crmeb\repositories\UserRepository;
  9. use think\db\exception\DataNotFoundException;
  10. use think\db\exception\ModelNotFoundException;
  11. use think\exception\DbException;
  12. /**
  13. * token验证中间件
  14. * Class AuthTokenMiddleware
  15. * @package app\http\middleware
  16. */
  17. class AuthTokenMiddleware implements MiddlewareInterface
  18. {
  19. public function handle(Request $request, \Closure $next, bool $force = true)
  20. {
  21. $request->filter(['htmlspecialchars', 'strip_tags', 'addslashes', 'trim']);
  22. $authInfo = null;
  23. $token = trim(ltrim($request->header('Authori-zation'), 'Bearer'));
  24. if(!$token) $token = trim(ltrim($request->header('Authorization'), 'Bearer'));//正式版,删除此行,某些服务器无法获取到token调整为 Authori-zation
  25. try {
  26. $authInfo = UserRepository::parseToken($token);
  27. } catch (AuthException $e) {
  28. if ($force)
  29. return app('json')->make($e->getCode(), $e->getMessage());
  30. }
  31. if (!is_null($authInfo)) {
  32. Request::macro('user', function () use (&$authInfo) {
  33. return $authInfo['user'];
  34. });
  35. Request::macro('tokenData', function () use (&$authInfo) {
  36. return $authInfo['tokenData'];
  37. });
  38. }
  39. Request::macro('isLogin', function () use (&$authInfo) {
  40. return !is_null($authInfo);
  41. });
  42. Request::macro('uid', function () use (&$authInfo) {
  43. return is_null($authInfo) ? 0 : $authInfo['user']->uid;
  44. });
  45. return $next($request);
  46. }
  47. }