123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472 |
- <?php
- namespace app\common\controller;
- use app\common\library\Authdoctor as Auth;
- use think\Config;
- use think\exception\HttpResponseException;
- use think\exception\ValidateException;
- use think\Hook;
- use think\Lang;
- use think\Loader;
- use think\Request;
- use think\Response;
- use think\Route;
- use think\Validate;
- use Redis;
- class Apic
- {
-
- protected $request;
-
- protected $failException = false;
-
- protected $batchValidate = false;
-
- protected $beforeActionList = [];
-
- protected $noNeedLogin = [];
-
- protected $noNeedRight = [];
-
- protected $auth = null;
-
- protected $responseType = 'json';
-
- public $logType = 2;
-
- public function __construct(Request $request = null)
- {
- $this->request = is_null($request) ? Request::instance() : $request;
- if(config('site.apisite_switch') == 0){
- $controllername = $this->request->controller();
- $controllername = strtolower($controllername);
- if(!in_array($controllername,['notify','easemob','payios'])){
- $notice = config('site.apisite_notice') ?: '全站维护中';
- $this->error($notice);
- }
- }
-
- $this->_initialize();
-
- $this->request_log();
-
- if ($this->beforeActionList) {
- foreach ($this->beforeActionList as $method => $options) {
- is_numeric($method) ?
- $this->beforeAction($options) :
- $this->beforeAction($method, $options);
- }
- }
- }
-
- protected function _initialize()
- {
-
- check_cors_request();
-
- check_ip_allowed();
-
- $this->request->filter('trim,strip_tags,htmlspecialchars');
- $this->auth = Auth::instance();
- $modulename = $this->request->module();
- $controllername = Loader::parseName($this->request->controller());
- $actionname = strtolower($this->request->action());
-
- $token = $this->request->server('HTTP_TOKEN', $this->request->request('token', \think\Cookie::get('token')));
- $path = str_replace('.', '/', $controllername) . '/' . $actionname;
-
- $this->auth->setRequestUri($path);
-
- if (!$this->auth->match($this->noNeedLogin)) {
-
- $this->auth->init($token);
-
- if (!$this->auth->isLogin()) {
- $this->error(__('Please login first'), null, 401);
- }
-
-
- } else {
-
- if ($token) {
- $this->auth->init($token);
-
- if (!$this->auth->isLogin()) {
- $this->error(__('Please login first'), null, 401);
- }
- }
- }
- $upload = \app\common\model\Config::upload();
-
- Hook::listen("upload_config_init", $upload);
- Config::set('upload', array_merge(Config::get('upload'), $upload));
-
- $this->loadlang($controllername);
- }
-
- protected function loadlang($name)
- {
- $name = Loader::parseName($name);
- $name = preg_match("/^([a-zA-Z0-9_\.\/]+)\$/i", $name) ? $name : 'index';
- $lang = $this->request->langset();
- $lang = preg_match("/^([a-zA-Z\-_]{2,10})\$/i", $lang) ? $lang : 'zh-cn';
- Lang::load(APP_PATH . $this->request->module() . '/lang/' . $lang . '/' . str_replace('.', '/', $name) . '.php');
- }
-
- protected function success($msg = '', $data = null, $code = 1, $type = null, array $header = [])
- {
- if($msg == 1){
- $msg = 'success';
- }
- if(empty($msg)){
- $msg = '操作成功';
- }
- $this->result($msg, $data, $code, $type, $header);
- }
-
- protected function error($msg = '', $data = null, $code = 0, $type = null, array $header = [])
- {
- if(empty($msg)){
- $msg = __('Invalid parameters');
- }
- $this->result($msg, $data, $code, $type, $header);
- }
-
- protected function result($msg, $data = null, $code = 0, $type = null, array $header = [])
- {
- $result = [
- 'code' => $code,
- 'msg' => __($msg),
- 'time' => Request::instance()->server('REQUEST_TIME'),
- 'data' => $data,
- ];
-
- $this->request_log_update($result);
-
- $type = $type ? : $this->responseType;
- if (isset($header['statuscode'])) {
- $code = $header['statuscode'];
- unset($header['statuscode']);
- } else {
-
- $code = $code >= 1000 || $code < 200 ? 200 : $code;
- }
- $response = Response::create($result, $type, $code)->header($header);
- throw new HttpResponseException($response);
- }
-
- protected function beforeAction($method, $options = [])
- {
- if (isset($options['only'])) {
- if (is_string($options['only'])) {
- $options['only'] = explode(',', $options['only']);
- }
- if (!in_array($this->request->action(), $options['only'])) {
- return;
- }
- } elseif (isset($options['except'])) {
- if (is_string($options['except'])) {
- $options['except'] = explode(',', $options['except']);
- }
- if (in_array($this->request->action(), $options['except'])) {
- return;
- }
- }
- call_user_func([$this, $method]);
- }
-
- protected function validateFailException($fail = true)
- {
- $this->failException = $fail;
- return $this;
- }
-
- protected function validate($data, $validate, $message = [], $batch = false, $callback = null)
- {
- if (is_array($validate)) {
- $v = Loader::validate();
- $v->rule($validate);
- } else {
-
- if (strpos($validate, '.')) {
- list($validate, $scene) = explode('.', $validate);
- }
- $v = Loader::validate($validate);
- !empty($scene) && $v->scene($scene);
- }
-
- if ($batch || $this->batchValidate) {
- $v->batch(true);
- }
-
- if (is_array($message)) {
- $v->message($message);
- }
-
- if ($callback && is_callable($callback)) {
- call_user_func_array($callback, [$v, &$data]);
- }
- if (!$v->check($data)) {
- if ($this->failException) {
- throw new ValidateException($v->getError());
- }
- return $v->getError();
- }
- return true;
- }
-
- protected function token()
- {
- $token = $this->request->param('__token__');
-
- if (!Validate::make()->check(['__token__' => $token], ['__token__' => 'require|token'])) {
- $this->error(__('Token verification error'), ['__token__' => $this->request->token()]);
- }
-
- $this->request->token();
- }
-
- protected function request_log(){
-
- $modulename = $this->request->module();
- $controllername = $this->request->controller();
- $actionname = $this->request->action();
- if(strtolower($actionname) == 'callback'){
- return true;
- }
- defined('API_REQUEST_LOG_TYPE') or define('API_REQUEST_LOG_TYPE', $this->logType);
- $params = input();
- if ($this->logType === 1){
-
- register_shutdown_function([new LogUtil, 'close']);
- LogUtil::getInstance('Api/');
- LogUtil::info('uid', 'Api-Middleware-Log', 'request_log', $this->auth->id);
- LogUtil::info('api', 'Api-Middleware-Log', 'request_log', $modulename . '/' . $controllername . '/' . $actionname);
- LogUtil::info('params', 'Api-Middleware-Log', 'request_log', json_encode($params));
- LogUtil::info('ip', 'Api-Middleware-Log', 'request_log', request()->ip());
- }else{
- $data = [
- 'uid' => $this->auth->id,
- 'api' => $modulename.'/'.$controllername.'/'.$actionname,
- 'params' => json_encode($params),
- 'addtime' => time(),
- 'adddatetime' => date('Y-m-d H:i:s'),
- 'ip' => request()->ip(),
- ];
- $request_id = db('api_request_log')->insertGetId($data);
- defined('API_REQUEST_ID') or define('API_REQUEST_ID', $request_id);
- }
- }
- protected function request_log_update($log_result){
- $actionname = $this->request->action();
- if(strtolower($actionname) == 'givegifttoyou'){
-
- }
- if ($this->logType === 1){
- if (strlen(json_encode($log_result['data'])) > 1000) {
-
- }
- LogUtil::info('result', 'Api-Middleware-Log', 'request_log', $log_result);
- }else{
- if(defined('API_REQUEST_ID')) {
- if(strlen(json_encode($log_result['data'])) > 1000) {
-
- }
- db('api_request_log')->where('id',API_REQUEST_ID)->update(['result'=>json_encode($log_result)]);
- }
- }
- }
-
- public function apiLimit($apiLimit = 1, $apiLimitTime = 1000, $key = '')
- {
- $userId = $this->auth->id;
- $controller = request()->controller();
- $action = request()->action();
- if (!$key) {
- $key = strtolower($controller) . '_' . strtolower($action) . '_' . $userId;
- }
- $redis = new Redis();
- $redisconfig = config("redis");
- $redis->connect($redisconfig["host"], $redisconfig["port"]);
- if ($redisconfig['redis_pwd']) {
- $redis->auth($redisconfig['redis_pwd']);
- }
- if($redisconfig['redis_selectdb'] > 0){
- $redis->select($redisconfig['redis_selectdb']);
- }
-
-
- $count = $redis->incr($key);
- if ($count > $apiLimit) {
- return false;
- }
-
- if ($count == 1) {
- $redis->pExpire($key, $apiLimitTime);
- }
- return true;
- }
- }
|