AuthTokenMiddleware.php 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  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 ($authInfo['user']){
  31. if ($authInfo['user']['status'] == 0) {
  32. return app('json')->fail('用户已被冻结24小时,请联系管理员解除');
  33. }
  34. }
  35. if (!is_null($authInfo)) {
  36. Request::macro('user', function () use (&$authInfo) {
  37. return $authInfo['user'];
  38. });
  39. Request::macro('tokenData', function () use (&$authInfo) {
  40. return $authInfo['tokenData'];
  41. });
  42. }
  43. Request::macro('isLogin', function () use (&$authInfo) {
  44. return !is_null($authInfo);
  45. });
  46. Request::macro('uid', function () use (&$authInfo) {
  47. return is_null($authInfo) ? 0 : $authInfo['user']->uid;
  48. });
  49. return $next($request);
  50. }
  51. }