AuthTokenMiddleware.php 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. <?php
  2. namespace app\http\middleware;
  3. use app\models\point_plan\UserPointPlan;
  4. use app\models\system\Site;
  5. use app\models\user\User;
  6. use app\models\user\UserLevel;
  7. use app\models\user\UserToken;
  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. // var_dump($request->site_id());
  25. $request->filter(['htmlspecialchars', 'strip_tags', 'addslashes', 'trim']);
  26. $authInfo = null;
  27. $token = trim(ltrim($request->header('Authori-zation'), 'Bearer'));
  28. // if (!$token) $token = trim(ltrim($request->header('Authorization'), 'Bearer'));//正式版,删除此行,某些服务器无法获取到token调整为 Authori-zation
  29. try {
  30. $authInfo = UserRepository::parseToken($token, $request->site_id());
  31. // if (!in_array($request->action(), ['binding_phone', 'user', 'userInfo', 'verify']) && ($authInfo['user']['account'] != $authInfo['user']['phone'] && $authInfo['user']['account'] != $authInfo['user']['email'])) {
  32. // return app('json')->make('400', '请先绑定手机号或邮箱');
  33. // }
  34. $authInfo['user']['level_info'] = UserLevel::getUserLevelInfo(UserLevel::getUserLevel($authInfo['user']['uid']));
  35. $authInfo['user']['point'] = UserPointPlan::where('uid', $authInfo['user']['uid'])->select();
  36. } catch (AuthException $e) {
  37. if ($force)
  38. return app('json')->make($e->getCode(), $e->getMessage());
  39. }
  40. if (!is_null($authInfo)) {
  41. Request::macro('user', function () use (&$authInfo) {
  42. return $authInfo['user'];
  43. });
  44. Request::macro('tokenData', function () use (&$authInfo) {
  45. return $authInfo['tokenData'];
  46. });
  47. }
  48. Request::macro('isLogin', function () use (&$authInfo) {
  49. return !is_null($authInfo);
  50. });
  51. Request::macro('uid', function () use (&$authInfo) {
  52. return is_null($authInfo) ? 0 : $authInfo['user']->uid;
  53. });
  54. return $next($request);
  55. }
  56. }