AuthTokenMiddleware.php 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  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. $authInfo = null;
  22. $token = trim(ltrim($request->header('Authori-zation'), 'Bearer'));
  23. if(!$token) $token = trim(ltrim($request->header('Authorization'), 'Bearer'));//正式版,删除此行,某些服务器无法获取到token调整为 Authori-zation
  24. try {
  25. $authInfo = UserRepository::parseToken($token);
  26. } catch (AuthException $e) {
  27. if ($force)
  28. return app('json')->make($e->getCode(), $e->getMessage());
  29. }
  30. if (!is_null($authInfo)) {
  31. Request::macro('user', function () use (&$authInfo) {
  32. return $authInfo['user'];
  33. });
  34. Request::macro('tokenData', function () use (&$authInfo) {
  35. return $authInfo['tokenData'];
  36. });
  37. }
  38. Request::macro('isLogin', function () use (&$authInfo) {
  39. return !is_null($authInfo);
  40. });
  41. Request::macro('uid', function () use (&$authInfo) {
  42. return is_null($authInfo) ? 0 : $authInfo['user']->uid;
  43. });
  44. return $next($request);
  45. }
  46. }