AuthTokenMiddleware.php 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  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. class AuthTokenMiddleware implements MiddlewareInterface
  13. {
  14. public function handle(Request $request, \Closure $next, bool $force = true)
  15. {
  16. $authInfo = null;
  17. $token = trim(ltrim($request->header('Authori-zation'), 'Bearer'));
  18. if(!$token) $token = trim(ltrim($request->header('Authorization'), 'Bearer'));//正式版,删除此行,某些服务器无法获取到token调整为 Authori-zation
  19. try {
  20. $authInfo = UserRepository::parseToken($token);
  21. } catch (AuthException $e) {
  22. if ($force)
  23. return app('json')->make($e->getCode(), $e->getMessage());
  24. }
  25. if (!is_null($authInfo)) {
  26. Request::macro('user', function () use (&$authInfo) {
  27. return $authInfo['user'];
  28. });
  29. Request::macro('tokenData', function () use (&$authInfo) {
  30. return $authInfo['tokenData'];
  31. });
  32. }
  33. Request::macro('isLogin', function () use (&$authInfo) {
  34. return !is_null($authInfo);
  35. });
  36. Request::macro('uid', function () use (&$authInfo) {
  37. return is_null($authInfo) ? 0 : $authInfo['user']->uid;
  38. });
  39. return $next($request);
  40. }
  41. }