AuthTokenMiddleware.php 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  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\Achievement;
  6. use app\models\user\User;
  7. use app\models\user\UserLevel;
  8. use app\models\user\UserToken;
  9. use app\Request;
  10. use crmeb\exceptions\AuthException;
  11. use crmeb\interfaces\MiddlewareInterface;
  12. use crmeb\repositories\UserRepository;
  13. use think\db\exception\DataNotFoundException;
  14. use think\db\exception\ModelNotFoundException;
  15. use think\exception\DbException;
  16. /**
  17. * token验证中间件
  18. * Class AuthTokenMiddleware
  19. * @package app\http\middleware
  20. */
  21. class AuthTokenMiddleware implements MiddlewareInterface
  22. {
  23. public function handle(Request $request, \Closure $next, bool $force = true)
  24. {
  25. // var_dump($request->site_id());
  26. $request->filter(['htmlspecialchars', 'strip_tags', 'addslashes', 'trim']);
  27. $authInfo = null;
  28. $token = trim(ltrim($request->header('Authori-zation'), 'Bearer'));
  29. // if (!$token) $token = trim(ltrim($request->header('Authorization'), 'Bearer'));//正式版,删除此行,某些服务器无法获取到token调整为 Authori-zation
  30. try {
  31. $authInfo = UserRepository::parseToken($token, $request->site_id());
  32. // if (!in_array($request->action(), ['binding_phone', 'user', 'userInfo', 'verify']) && ($authInfo['user']['account'] != $authInfo['user']['phone'] && $authInfo['user']['account'] != $authInfo['user']['email'])) {
  33. // return app('json')->make('400', '请先绑定手机号或邮箱');
  34. // }
  35. $authInfo['user']['level_info'] = UserLevel::getUserLevelInfo(UserLevel::getUserLevel($authInfo['user']['uid']));
  36. $authInfo['user']['point'] = UserPointPlan::where('uid', $authInfo['user']['uid'])->select();
  37. $authInfo['user']['all_achievement'] = Achievement::where('uid', $authInfo['user']['uid'])->sum('achievement');
  38. $authInfo['user']['self_achievement'] = Achievement::where('uid', $authInfo['user']['uid'])->where('from_uid', $authInfo['user']['uid'])->sum('achievement');
  39. } catch (AuthException $e) {
  40. if ($force)
  41. return app('json')->make($e->getCode(), $e->getMessage());
  42. }
  43. if (!is_null($authInfo)) {
  44. Request::macro('user', function () use (&$authInfo) {
  45. return $authInfo['user'];
  46. });
  47. Request::macro('tokenData', function () use (&$authInfo) {
  48. return $authInfo['tokenData'];
  49. });
  50. }
  51. Request::macro('isLogin', function () use (&$authInfo) {
  52. return !is_null($authInfo);
  53. });
  54. Request::macro('uid', function () use (&$authInfo) {
  55. return is_null($authInfo) ? 0 : $authInfo['user']->uid;
  56. });
  57. return $next($request);
  58. }
  59. }