AuthTokenMiddleware.php 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  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. if ($authInfo['user']['status'] == 0) {
  33. return app('json')->fail('账号已被冻结!');
  34. }
  35. } catch (AuthException $e) {
  36. if ($force)
  37. return app('json')->make($e->getCode(), $e->getMessage());
  38. }
  39. if (!is_null($authInfo)) {
  40. Request::macro('user', function () use (&$authInfo) {
  41. return $authInfo['user'];
  42. });
  43. Request::macro('tokenData', function () use (&$authInfo) {
  44. return $authInfo['tokenData'];
  45. });
  46. }
  47. Request::macro('isLogin', function () use (&$authInfo) {
  48. return !is_null($authInfo);
  49. });
  50. Request::macro('uid', function () use (&$authInfo) {
  51. return is_null($authInfo) ? 0 : $authInfo['user']->uid;
  52. });
  53. return $next($request);
  54. }
  55. }