// +---------------------------------------------------------------------- namespace App\Http\Controllers\Oapi; use App\Helpers\Jwt; use App\Http\Controllers\BaseController; use App\Models\ApiModel; use App\Services\Api\MemberService; use App\Services\ConfigService; use App\Services\RedisService; /** * 控制器基类 * @since 2020/11/10 * Class BaseController * @package App\Http\Controllers */ class webApp extends BaseController { // 模型 protected $model; // 服务 protected $service; // 校验 protected $validate; // 登录ID protected $userId = 0; // 所属接口平台ID protected $apiId = 0; // 登录信息 protected $userInfo = []; /** * 构造函数 * @author wesmiler * @since 2020/11/10 * Backend constructor. */ public function __construct() { parent::__construct(); // 初始化分页参数 $this->initConfig(); // 登录检测中间件 $this->middleware('api.login'); // 初始化登录信息 $this->middleware(function ($request, $next) { // 请求头信息 $params = $request->all(); $token = isset($params['token'])? $params['token'] : ''; $tokenData = RedisService::get("apis:tokens:{$token}"); $userId = isset($tokenData['id'])? $tokenData['id'] : 0; $this->apiId = isset($tokenData['api_id'])? $tokenData['api_id'] : 0; // 请求频率限制 $clientIp = get_client_ip(); $ipStr = str_replace('.', '_', $clientIp); $cacheKey = "apis:request:temp:{$ipStr}"; $requestCount = RedisService::get($cacheKey); $requestCount = $requestCount? $requestCount : 0; if($requestCount >= 10){ return message(1028, false, null, 403); } // 登录验证 $userInfo = RedisService::get("apis:auths:info:{$userId}"); if(empty($userInfo) && $userId){ $this->initLogin($userId); }else{ $this->userId = $userId; $this->userInfo = $userInfo; $this->apiId = isset($userInfo['api_id'])? $userInfo['api_id'] : $this->apiId; } RedisService::set($cacheKey, $requestCount+1, rand(1,2)); return $next($request); }); } /** * 初始化配置 * @author laravel开发员 * @since 2020/11/10 */ public function initConfig() { // 请求参数 $this->param = \request()->input(); // 分页基础默认值 defined('PERPAGE') or define('PERPAGE', isset($this->param['limit']) ? $this->param['limit'] : 20); defined('PAGE') or define('PAGE', isset($this->param['page']) ? $this->param['page'] : 1); } /** * 登录验证 * @param $userId 用户ID * @return * @author wesmiler * @since 2020/8/31 */ public function initLogin($userId) { // 登录用户ID $this->userId = $userId; // 登录用户信息 if ($userId) { $userInfo = MemberService::make()->getInfo($this->userId); $this->userInfo = $userInfo; $this->apiId = isset($userInfo['api_id'])? $userInfo['api_id'] : 0; RedisService::set("apis:auths:info:{$userId}", $this->userInfo, 4*24*3600); } } }