Apic.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472
  1. <?php
  2. namespace app\common\controller;
  3. use app\common\library\Authdoctor as Auth;
  4. use think\Config;
  5. use think\exception\HttpResponseException;
  6. use think\exception\ValidateException;
  7. use think\Hook;
  8. use think\Lang;
  9. use think\Loader;
  10. use think\Request;
  11. use think\Response;
  12. use think\Route;
  13. use think\Validate;
  14. use Redis;
  15. /**
  16. * API控制器基类
  17. */
  18. class Apic
  19. {
  20. /**
  21. * @var Request Request 实例
  22. */
  23. protected $request;
  24. /**
  25. * @var bool 验证失败是否抛出异常
  26. */
  27. protected $failException = false;
  28. /**
  29. * @var bool 是否批量验证
  30. */
  31. protected $batchValidate = false;
  32. /**
  33. * @var array 前置操作方法列表
  34. */
  35. protected $beforeActionList = [];
  36. /**
  37. * 无需登录的方法,同时也就不需要鉴权了
  38. * @var array
  39. */
  40. protected $noNeedLogin = [];
  41. /**
  42. * 无需鉴权的方法,但需要登录
  43. * @var array
  44. */
  45. protected $noNeedRight = [];
  46. /**
  47. * 权限Auth
  48. * @var Auth
  49. */
  50. protected $auth = null;
  51. /**
  52. * 默认响应输出类型,支持json/xml
  53. * @var string
  54. */
  55. protected $responseType = 'json';
  56. /**
  57. * @var int 日志类型 1 文件;2sql
  58. */
  59. public $logType = 2;
  60. /**
  61. * 构造方法
  62. * @access public
  63. * @param Request $request Request 对象
  64. */
  65. public function __construct(Request $request = null)
  66. {
  67. $this->request = is_null($request) ? Request::instance() : $request;
  68. if(config('site.apisite_switch') == 0){
  69. $controllername = $this->request->controller();
  70. $controllername = strtolower($controllername);
  71. if(!in_array($controllername,['notify','easemob','payios'])){
  72. $notice = config('site.apisite_notice') ?: '全站维护中';
  73. $this->error($notice);
  74. }
  75. }
  76. // 控制器初始化
  77. $this->_initialize();
  78. //日志
  79. $this->request_log();
  80. // 前置操作方法
  81. if ($this->beforeActionList) {
  82. foreach ($this->beforeActionList as $method => $options) {
  83. is_numeric($method) ?
  84. $this->beforeAction($options) :
  85. $this->beforeAction($method, $options);
  86. }
  87. }
  88. }
  89. /**
  90. * 初始化操作
  91. * @access protected
  92. */
  93. protected function _initialize()
  94. {
  95. //跨域请求检测
  96. check_cors_request();
  97. // 检测IP是否允许
  98. check_ip_allowed();
  99. //移除HTML标签
  100. $this->request->filter('trim,strip_tags,htmlspecialchars');
  101. $this->auth = Auth::instance();
  102. $modulename = $this->request->module();
  103. $controllername = Loader::parseName($this->request->controller());
  104. $actionname = strtolower($this->request->action());
  105. // token
  106. $token = $this->request->server('HTTP_TOKEN', $this->request->request('token', \think\Cookie::get('token')));
  107. $path = str_replace('.', '/', $controllername) . '/' . $actionname;
  108. // 设置当前请求的URI
  109. $this->auth->setRequestUri($path);
  110. // 检测是否需要验证登录
  111. if (!$this->auth->match($this->noNeedLogin)) {
  112. //初始化
  113. $this->auth->init($token);
  114. //检测是否登录
  115. if (!$this->auth->isLogin()) {
  116. $this->error(__('Please login first'), null, 401);
  117. }
  118. // 判断是否需要验证权限
  119. /*if (!$this->auth->match($this->noNeedRight)) {
  120. // 判断控制器和方法判断是否有对应权限
  121. if (!$this->auth->check($path)) {
  122. $this->error(__('You have no permission'), null, 403);
  123. }
  124. }*/
  125. } else {
  126. // 如果有传递token才验证是否登录状态
  127. if ($token) {
  128. $this->auth->init($token);
  129. //传就必须传对
  130. if (!$this->auth->isLogin()) {
  131. $this->error(__('Please login first'), null, 401);
  132. }
  133. }
  134. }
  135. $upload = \app\common\model\Config::upload();
  136. // 上传信息配置后
  137. Hook::listen("upload_config_init", $upload);
  138. Config::set('upload', array_merge(Config::get('upload'), $upload));
  139. // 加载当前控制器语言包
  140. $this->loadlang($controllername);
  141. }
  142. /**
  143. * 加载语言文件
  144. * @param string $name
  145. */
  146. protected function loadlang($name)
  147. {
  148. $name = Loader::parseName($name);
  149. $name = preg_match("/^([a-zA-Z0-9_\.\/]+)\$/i", $name) ? $name : 'index';
  150. $lang = $this->request->langset();
  151. $lang = preg_match("/^([a-zA-Z\-_]{2,10})\$/i", $lang) ? $lang : 'zh-cn';
  152. Lang::load(APP_PATH . $this->request->module() . '/lang/' . $lang . '/' . str_replace('.', '/', $name) . '.php');
  153. }
  154. /**
  155. * 操作成功返回的数据
  156. * @param string $msg 提示信息
  157. * @param mixed $data 要返回的数据
  158. * @param int $code 错误码,默认为1
  159. * @param string $type 输出类型
  160. * @param array $header 发送的 Header 信息
  161. */
  162. protected function success($msg = '', $data = null, $code = 1, $type = null, array $header = [])
  163. {
  164. if($msg == 1){
  165. $msg = 'success';
  166. }
  167. if(empty($msg)){
  168. $msg = '操作成功';
  169. }
  170. $this->result($msg, $data, $code, $type, $header);
  171. }
  172. /**
  173. * 操作失败返回的数据
  174. * @param string $msg 提示信息
  175. * @param mixed $data 要返回的数据
  176. * @param int $code 错误码,默认为0
  177. * @param string $type 输出类型
  178. * @param array $header 发送的 Header 信息
  179. */
  180. protected function error($msg = '', $data = null, $code = 0, $type = null, array $header = [])
  181. {
  182. if(empty($msg)){
  183. $msg = __('Invalid parameters');
  184. }
  185. $this->result($msg, $data, $code, $type, $header);
  186. }
  187. /**
  188. * 返回封装后的 API 数据到客户端
  189. * @access protected
  190. * @param mixed $msg 提示信息
  191. * @param mixed $data 要返回的数据
  192. * @param int $code 错误码,默认为0
  193. * @param string $type 输出类型,支持json/xml/jsonp
  194. * @param array $header 发送的 Header 信息
  195. * @return void
  196. * @throws HttpResponseException
  197. */
  198. protected function result($msg, $data = null, $code = 0, $type = null, array $header = [])
  199. {
  200. $result = [
  201. 'code' => $code,
  202. 'msg' => __($msg),
  203. 'time' => Request::instance()->server('REQUEST_TIME'),
  204. 'data' => $data,
  205. ];
  206. //日志
  207. $this->request_log_update($result);
  208. // 如果未设置类型则使用默认类型判断
  209. $type = $type ? : $this->responseType;
  210. if (isset($header['statuscode'])) {
  211. $code = $header['statuscode'];
  212. unset($header['statuscode']);
  213. } else {
  214. //未设置状态码,根据code值判断
  215. $code = $code >= 1000 || $code < 200 ? 200 : $code;
  216. }
  217. $response = Response::create($result, $type, $code)->header($header);
  218. throw new HttpResponseException($response);
  219. }
  220. /**
  221. * 前置操作
  222. * @access protected
  223. * @param string $method 前置操作方法名
  224. * @param array $options 调用参数 ['only'=>[...]] 或者 ['except'=>[...]]
  225. * @return void
  226. */
  227. protected function beforeAction($method, $options = [])
  228. {
  229. if (isset($options['only'])) {
  230. if (is_string($options['only'])) {
  231. $options['only'] = explode(',', $options['only']);
  232. }
  233. if (!in_array($this->request->action(), $options['only'])) {
  234. return;
  235. }
  236. } elseif (isset($options['except'])) {
  237. if (is_string($options['except'])) {
  238. $options['except'] = explode(',', $options['except']);
  239. }
  240. if (in_array($this->request->action(), $options['except'])) {
  241. return;
  242. }
  243. }
  244. call_user_func([$this, $method]);
  245. }
  246. /**
  247. * 设置验证失败后是否抛出异常
  248. * @access protected
  249. * @param bool $fail 是否抛出异常
  250. * @return $this
  251. */
  252. protected function validateFailException($fail = true)
  253. {
  254. $this->failException = $fail;
  255. return $this;
  256. }
  257. /**
  258. * 验证数据
  259. * @access protected
  260. * @param array $data 数据
  261. * @param string|array $validate 验证器名或者验证规则数组
  262. * @param array $message 提示信息
  263. * @param bool $batch 是否批量验证
  264. * @param mixed $callback 回调方法(闭包)
  265. * @return array|string|true
  266. * @throws ValidateException
  267. */
  268. protected function validate($data, $validate, $message = [], $batch = false, $callback = null)
  269. {
  270. if (is_array($validate)) {
  271. $v = Loader::validate();
  272. $v->rule($validate);
  273. } else {
  274. // 支持场景
  275. if (strpos($validate, '.')) {
  276. list($validate, $scene) = explode('.', $validate);
  277. }
  278. $v = Loader::validate($validate);
  279. !empty($scene) && $v->scene($scene);
  280. }
  281. // 批量验证
  282. if ($batch || $this->batchValidate) {
  283. $v->batch(true);
  284. }
  285. // 设置错误信息
  286. if (is_array($message)) {
  287. $v->message($message);
  288. }
  289. // 使用回调验证
  290. if ($callback && is_callable($callback)) {
  291. call_user_func_array($callback, [$v, &$data]);
  292. }
  293. if (!$v->check($data)) {
  294. if ($this->failException) {
  295. throw new ValidateException($v->getError());
  296. }
  297. return $v->getError();
  298. }
  299. return true;
  300. }
  301. /**
  302. * 刷新Token
  303. */
  304. protected function token()
  305. {
  306. $token = $this->request->param('__token__');
  307. //验证Token
  308. if (!Validate::make()->check(['__token__' => $token], ['__token__' => 'require|token'])) {
  309. $this->error(__('Token verification error'), ['__token__' => $this->request->token()]);
  310. }
  311. //刷新Token
  312. $this->request->token();
  313. }
  314. /*
  315. * api 请求日志
  316. * */
  317. protected function request_log(){
  318. //api_request_log
  319. $modulename = $this->request->module();
  320. $controllername = $this->request->controller();
  321. $actionname = $this->request->action();
  322. if(strtolower($actionname) == 'callback'){
  323. return true;
  324. }
  325. defined('API_REQUEST_LOG_TYPE') or define('API_REQUEST_LOG_TYPE', $this->logType);
  326. $params = input();
  327. if ($this->logType === 1){
  328. //日志统一写入
  329. register_shutdown_function([new LogUtil, 'close']);
  330. LogUtil::getInstance('Api/'); //设置日志存入通道
  331. LogUtil::info('uid', 'Api-Middleware-Log', 'request_log', $this->auth->id);
  332. LogUtil::info('api', 'Api-Middleware-Log', 'request_log', $modulename . '/' . $controllername . '/' . $actionname);
  333. LogUtil::info('params', 'Api-Middleware-Log', 'request_log', json_encode($params));
  334. LogUtil::info('ip', 'Api-Middleware-Log', 'request_log', request()->ip());
  335. }else{
  336. $data = [
  337. 'uid' => $this->auth->id,
  338. 'api' => $modulename.'/'.$controllername.'/'.$actionname,
  339. 'params' => json_encode($params),
  340. 'addtime' => time(),
  341. 'adddatetime' => date('Y-m-d H:i:s'),
  342. 'ip' => request()->ip(),
  343. ];
  344. $request_id = db('api_request_log')->insertGetId($data);
  345. defined('API_REQUEST_ID') or define('API_REQUEST_ID', $request_id);
  346. }
  347. }
  348. protected function request_log_update($log_result){
  349. $actionname = $this->request->action();
  350. if(strtolower($actionname) == 'givegifttoyou'){
  351. //return true;
  352. }
  353. if ($this->logType === 1){
  354. if (strlen(json_encode($log_result['data'])) > 1000) {
  355. //$log_result['data'] = '数据太多,不记录';
  356. }
  357. LogUtil::info('result', 'Api-Middleware-Log', 'request_log', $log_result);
  358. }else{
  359. if(defined('API_REQUEST_ID')) { //记录app正常返回结果
  360. if(strlen(json_encode($log_result['data'])) > 1000) {
  361. //$log_result['data'] = '数据太多,不记录';
  362. }
  363. db('api_request_log')->where('id',API_REQUEST_ID)->update(['result'=>json_encode($log_result)]);
  364. }
  365. }
  366. }
  367. /**
  368. * 接口请求限制
  369. * @param int $apiLimit
  370. * @param int $apiLimitTime
  371. * @param string $key
  372. * @return bool | true:通过 false:拒绝
  373. */
  374. public function apiLimit($apiLimit = 1, $apiLimitTime = 1000, $key = '')
  375. {
  376. $userId = $this->auth->id;
  377. $controller = request()->controller();
  378. $action = request()->action();
  379. if (!$key) {
  380. $key = strtolower($controller) . '_' . strtolower($action) . '_' . $userId;
  381. }
  382. $redis = new Redis();
  383. $redisconfig = config("redis");
  384. $redis->connect($redisconfig["host"], $redisconfig["port"]);
  385. if ($redisconfig['redis_pwd']) {
  386. $redis->auth($redisconfig['redis_pwd']);
  387. }
  388. if($redisconfig['redis_selectdb'] > 0){
  389. $redis->select($redisconfig['redis_selectdb']);
  390. }
  391. //
  392. //指定键值新增+1 并获取
  393. $count = $redis->incr($key);
  394. if ($count > $apiLimit) {
  395. return false;
  396. }
  397. //设置过期时间
  398. if ($count == 1) {
  399. $redis->pExpire($key, $apiLimitTime);
  400. }
  401. return true;
  402. }
  403. }