12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667 |
- <?php
- namespace app\http\middleware;
- use app\models\point_plan\UserPointPlan;
- use app\models\system\Site;
- use app\models\user\Achievement;
- use app\models\user\User;
- use app\models\user\UserLevel;
- use app\models\user\UserToken;
- use app\Request;
- use crmeb\exceptions\AuthException;
- use crmeb\interfaces\MiddlewareInterface;
- use crmeb\repositories\UserRepository;
- use think\db\exception\DataNotFoundException;
- use think\db\exception\ModelNotFoundException;
- use think\exception\DbException;
- /**
- * token验证中间件
- * Class AuthTokenMiddleware
- * @package app\http\middleware
- */
- class AuthTokenMiddleware implements MiddlewareInterface
- {
- public function handle(Request $request, \Closure $next, bool $force = true)
- {
- // var_dump($request->site_id());
- $request->filter(['htmlspecialchars', 'strip_tags', 'addslashes', 'trim']);
- $authInfo = null;
- $token = trim(ltrim($request->header('Authori-zation'), 'Bearer'));
- // if (!$token) $token = trim(ltrim($request->header('Authorization'), 'Bearer'));//正式版,删除此行,某些服务器无法获取到token调整为 Authori-zation
- try {
- $authInfo = UserRepository::parseToken($token, $request->site_id());
- // if (!in_array($request->action(), ['binding_phone', 'user', 'userInfo', 'verify']) && ($authInfo['user']['account'] != $authInfo['user']['phone'] && $authInfo['user']['account'] != $authInfo['user']['email'])) {
- // return app('json')->make('400', '请先绑定手机号或邮箱');
- // }
- $authInfo['user']['level_info'] = UserLevel::getUserLevelInfo(UserLevel::getUserLevel($authInfo['user']['uid']));
- $authInfo['user']['point'] = UserPointPlan::where('uid', $authInfo['user']['uid'])->select();
- $authInfo['user']['all_achievement'] = Achievement::where('uid', $authInfo['user']['uid'])->sum('achievement');
- $authInfo['user']['self_achievement'] = Achievement::where('uid', $authInfo['user']['uid'])->where('from_uid', $authInfo['user']['uid'])->sum('achievement');
- $authInfo['user']['new_achievement'] = Achievement::where('uid', $authInfo['user']['uid'])->where('do', 0)->sum('achievement');
- } catch (AuthException $e) {
- if ($force)
- return app('json')->make($e->getCode(), $e->getMessage());
- }
- if (!is_null($authInfo)) {
- Request::macro('user', function () use (&$authInfo) {
- return $authInfo['user'];
- });
- Request::macro('tokenData', function () use (&$authInfo) {
- return $authInfo['tokenData'];
- });
- }
- Request::macro('isLogin', function () use (&$authInfo) {
- return !is_null($authInfo);
- });
- Request::macro('uid', function () use (&$authInfo) {
- return is_null($authInfo) ? 0 : $authInfo['user']->uid;
- });
- return $next($request);
- }
- }
|