AuthTokenMiddleware.php 2.1 KB

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