1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283 |
- <?php
- namespace app\http\middleware;
- use app\models\user\User;
- use app\models\user\UserLevel;
- use app\models\user\UserSpread;
- 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)
- {
- $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);
- if (!is_null($authInfo)) {
- $authInfo['user']['lock_spread_user'] = User::where('uid', $authInfo['user']->spread_uid)->field('nickname,phone,avatar')->find();
- $authInfo['user']['level_info'] = UserLevel::getUserLevelInfo(UserLevel::getUserLevel($authInfo['user']->uid));
- if (!$authInfo['user']['lock_spread_user']) {
- $spread_user = UserSpread::where('uid', $authInfo['user']->uid)->order('spread_time', 'desc')->find();
- if ($spread_user) {
- $sp = $spread_user['spread_uid'];
- $userlist = User::column('uid,spread_uid', 'uid');
- while ($sp) {
- if ($sp == $authInfo['user']->uid) {
- $spread_user['spread_uid'] = 0;
- break;
- }
- $sp = $userlist[$sp]['spread_uid'];
- }
- if (!$spread_user['spread_uid']) {
- $authInfo['user']['unlock_spread_user'] = null;
- } else {
- $authInfo['user']['unlock_spread_user'] = User::where('uid', $spread_user['spread_uid'])->field('nickname,phone,avatar')->find();
- }
- } else {
- $authInfo['user']['unlock_spread_user'] = null;
- }
- } else {
- $authInfo['user']['unlock_spread_user'] = null;
- }
- }
- } 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);
- }
- }
|