Apic.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512
  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. // $this->user_active();
  82. // 前置操作方法
  83. if ($this->beforeActionList) {
  84. foreach ($this->beforeActionList as $method => $options) {
  85. is_numeric($method) ?
  86. $this->beforeAction($options) :
  87. $this->beforeAction($method, $options);
  88. }
  89. }
  90. }
  91. /**
  92. * 初始化操作
  93. * @access protected
  94. */
  95. protected function _initialize()
  96. {
  97. //跨域请求检测
  98. check_cors_request();
  99. // 检测IP是否允许
  100. check_ip_allowed();
  101. //移除HTML标签
  102. $this->request->filter('trim,strip_tags,htmlspecialchars');
  103. $this->auth = Auth::instance();
  104. $modulename = $this->request->module();
  105. $controllername = Loader::parseName($this->request->controller());
  106. $actionname = strtolower($this->request->action());
  107. // token
  108. $token = $this->request->server('HTTP_TOKEN', $this->request->request('token', \think\Cookie::get('token')));
  109. $path = str_replace('.', '/', $controllername) . '/' . $actionname;
  110. // 设置当前请求的URI
  111. $this->auth->setRequestUri($path);
  112. // 检测是否需要验证登录
  113. if (!$this->auth->match($this->noNeedLogin)) {
  114. //初始化
  115. $this->auth->init($token);
  116. //检测是否登录
  117. if (!$this->auth->isLogin()) {
  118. $this->error(__('Please login first'), null, 401);
  119. }
  120. // 判断是否需要验证权限
  121. /*if (!$this->auth->match($this->noNeedRight)) {
  122. // 判断控制器和方法判断是否有对应权限
  123. if (!$this->auth->check($path)) {
  124. $this->error(__('You have no permission'), null, 403);
  125. }
  126. }*/
  127. } else {
  128. // 如果有传递token才验证是否登录状态
  129. if ($token) {
  130. $this->auth->init($token);
  131. //传就必须传对
  132. if (!$this->auth->isLogin()) {
  133. $this->error(__('Please login first'), null, 401);
  134. }
  135. }
  136. }
  137. $upload = \app\common\model\Config::upload();
  138. // 上传信息配置后
  139. Hook::listen("upload_config_init", $upload);
  140. Config::set('upload', array_merge(Config::get('upload'), $upload));
  141. // 加载当前控制器语言包
  142. $this->loadlang($controllername);
  143. }
  144. /**
  145. * 加载语言文件
  146. * @param string $name
  147. */
  148. protected function loadlang($name)
  149. {
  150. $name = Loader::parseName($name);
  151. $name = preg_match("/^([a-zA-Z0-9_\.\/]+)\$/i", $name) ? $name : 'index';
  152. $lang = $this->request->langset();
  153. $lang = preg_match("/^([a-zA-Z\-_]{2,10})\$/i", $lang) ? $lang : 'zh-cn';
  154. Lang::load(APP_PATH . $this->request->module() . '/lang/' . $lang . '/' . str_replace('.', '/', $name) . '.php');
  155. }
  156. //结果集信息里,多个字段需要翻译
  157. protected function list_lang($list,$field){
  158. if(!$list || empty($list)){
  159. return $list;
  160. }
  161. foreach($list as $vo => $info){
  162. $list[$vo] = $this->info_lang($info,$field);
  163. }
  164. return $list;
  165. }
  166. //单条信息里,多个字段需要翻译
  167. protected function info_lang($data,$field){
  168. if(!$data || empty($data)){
  169. return $data;
  170. }
  171. foreach($data as $key => $val){
  172. if(in_array($key,$field)){
  173. if($this->lang == 'en'){
  174. $data[$key] = $data[$key.'_en'];
  175. unset($data[$key.'_en']);
  176. }else{
  177. unset($data[$key.'_en']);
  178. }
  179. }
  180. }
  181. return $data;
  182. }
  183. /**
  184. * 操作成功返回的数据
  185. * @param string $msg 提示信息
  186. * @param mixed $data 要返回的数据
  187. * @param int $code 错误码,默认为1
  188. * @param string $type 输出类型
  189. * @param array $header 发送的 Header 信息
  190. */
  191. protected function success($msg = '', $data = null, $code = 1, $type = null, array $header = [])
  192. {
  193. if($msg == 1){
  194. $msg = 'success';
  195. }
  196. if(empty($msg)){
  197. $msg = '操作成功';
  198. }
  199. $this->result($msg, $data, $code, $type, $header);
  200. }
  201. //find查询出来的结果如果为空数组,强制转换object
  202. protected function success_find($msg = '', $data = null, $code = 1, $type = null, array $header = [])
  203. {
  204. if(empty($msg)){
  205. $msg = '操作成功';
  206. }
  207. if(is_null($data) || $data === []){
  208. $data = (object)[];
  209. }
  210. $this->result($msg, $data, $code, $type, $header);
  211. }
  212. /**
  213. * 操作失败返回的数据
  214. * @param string $msg 提示信息
  215. * @param mixed $data 要返回的数据
  216. * @param int $code 错误码,默认为0
  217. * @param string $type 输出类型
  218. * @param array $header 发送的 Header 信息
  219. */
  220. protected function error($msg = '', $data = null, $code = 0, $type = null, array $header = [])
  221. {
  222. if(empty($msg)){
  223. $msg = __('Invalid parameters');
  224. }
  225. $this->result($msg, $data, $code, $type, $header);
  226. }
  227. /**
  228. * 返回封装后的 API 数据到客户端
  229. * @access protected
  230. * @param mixed $msg 提示信息
  231. * @param mixed $data 要返回的数据
  232. * @param int $code 错误码,默认为0
  233. * @param string $type 输出类型,支持json/xml/jsonp
  234. * @param array $header 发送的 Header 信息
  235. * @return void
  236. * @throws HttpResponseException
  237. */
  238. protected function result($msg, $data = null, $code = 0, $type = null, array $header = [])
  239. {
  240. $result = [
  241. 'code' => $code,
  242. 'msg' => __($msg),
  243. 'time' => Request::instance()->server('REQUEST_TIME'),
  244. 'data' => $data,
  245. ];
  246. //日志
  247. $this->request_log_update($result);
  248. // 如果未设置类型则使用默认类型判断
  249. $type = $type ? : $this->responseType;
  250. if (isset($header['statuscode'])) {
  251. $code = $header['statuscode'];
  252. unset($header['statuscode']);
  253. } else {
  254. //未设置状态码,根据code值判断
  255. $code = $code >= 1000 || $code < 200 ? 200 : $code;
  256. }
  257. $response = Response::create($result, $type, $code)->header($header);
  258. throw new HttpResponseException($response);
  259. }
  260. /**
  261. * 前置操作
  262. * @access protected
  263. * @param string $method 前置操作方法名
  264. * @param array $options 调用参数 ['only'=>[...]] 或者 ['except'=>[...]]
  265. * @return void
  266. */
  267. protected function beforeAction($method, $options = [])
  268. {
  269. if (isset($options['only'])) {
  270. if (is_string($options['only'])) {
  271. $options['only'] = explode(',', $options['only']);
  272. }
  273. if (!in_array($this->request->action(), $options['only'])) {
  274. return;
  275. }
  276. } elseif (isset($options['except'])) {
  277. if (is_string($options['except'])) {
  278. $options['except'] = explode(',', $options['except']);
  279. }
  280. if (in_array($this->request->action(), $options['except'])) {
  281. return;
  282. }
  283. }
  284. call_user_func([$this, $method]);
  285. }
  286. /**
  287. * 设置验证失败后是否抛出异常
  288. * @access protected
  289. * @param bool $fail 是否抛出异常
  290. * @return $this
  291. */
  292. protected function validateFailException($fail = true)
  293. {
  294. $this->failException = $fail;
  295. return $this;
  296. }
  297. /**
  298. * 验证数据
  299. * @access protected
  300. * @param array $data 数据
  301. * @param string|array $validate 验证器名或者验证规则数组
  302. * @param array $message 提示信息
  303. * @param bool $batch 是否批量验证
  304. * @param mixed $callback 回调方法(闭包)
  305. * @return array|string|true
  306. * @throws ValidateException
  307. */
  308. protected function validate($data, $validate, $message = [], $batch = false, $callback = null)
  309. {
  310. if (is_array($validate)) {
  311. $v = Loader::validate();
  312. $v->rule($validate);
  313. } else {
  314. // 支持场景
  315. if (strpos($validate, '.')) {
  316. list($validate, $scene) = explode('.', $validate);
  317. }
  318. $v = Loader::validate($validate);
  319. !empty($scene) && $v->scene($scene);
  320. }
  321. // 批量验证
  322. if ($batch || $this->batchValidate) {
  323. $v->batch(true);
  324. }
  325. // 设置错误信息
  326. if (is_array($message)) {
  327. $v->message($message);
  328. }
  329. // 使用回调验证
  330. if ($callback && is_callable($callback)) {
  331. call_user_func_array($callback, [$v, &$data]);
  332. }
  333. if (!$v->check($data)) {
  334. if ($this->failException) {
  335. throw new ValidateException($v->getError());
  336. }
  337. return $v->getError();
  338. }
  339. return true;
  340. }
  341. /**
  342. * 刷新Token
  343. */
  344. protected function token()
  345. {
  346. $token = $this->request->param('__token__');
  347. //验证Token
  348. if (!Validate::make()->check(['__token__' => $token], ['__token__' => 'require|token'])) {
  349. $this->error(__('Token verification error'), ['__token__' => $this->request->token()]);
  350. }
  351. //刷新Token
  352. $this->request->token();
  353. }
  354. /*
  355. * api 请求日志
  356. * */
  357. protected function request_log(){
  358. //api_request_log
  359. $modulename = $this->request->module();
  360. $controllername = $this->request->controller();
  361. $actionname = $this->request->action();
  362. if(strtolower($actionname) == 'callback'){
  363. return true;
  364. }
  365. defined('API_REQUEST_LOG_TYPE') or define('API_REQUEST_LOG_TYPE', $this->logType);
  366. $params = $this->request->request();
  367. if ($this->logType === 1){
  368. //日志统一写入
  369. register_shutdown_function([new LogUtil, 'close']);
  370. LogUtil::getInstance('Api/'); //设置日志存入通道
  371. LogUtil::info('uid', 'Api-Middleware-Log', 'request_log', $this->auth->id);
  372. LogUtil::info('api', 'Api-Middleware-Log', 'request_log', $modulename . '/' . $controllername . '/' . $actionname);
  373. LogUtil::info('params', 'Api-Middleware-Log', 'request_log', json_encode($params));
  374. LogUtil::info('ip', 'Api-Middleware-Log', 'request_log', request()->ip());
  375. }else{
  376. $data = [
  377. 'uid' => $this->auth->id,
  378. 'api' => $modulename.'/'.$controllername.'/'.$actionname,
  379. 'params' => json_encode($params),
  380. 'addtime' => time(),
  381. 'adddatetime' => date('Y-m-d H:i:s'),
  382. 'ip' => request()->ip(),
  383. ];
  384. $request_id = db('api_request_log')->insertGetId($data);
  385. defined('API_REQUEST_ID') or define('API_REQUEST_ID', $request_id);
  386. }
  387. }
  388. protected function request_log_update($log_result){
  389. $actionname = $this->request->action();
  390. if(strtolower($actionname) == 'givegifttoyou'){
  391. //return true;
  392. }
  393. if ($this->logType === 1){
  394. if (strlen(json_encode($log_result['data'])) > 1000) {
  395. $log_result['data'] = '数据太多,不记录';
  396. }
  397. LogUtil::info('result', 'Api-Middleware-Log', 'request_log', $log_result);
  398. }else{
  399. if(defined('API_REQUEST_ID')) { //记录app正常返回结果
  400. if(strlen(json_encode($log_result['data'])) > 1000) {
  401. $log_result['data'] = '数据太多,不记录';
  402. }
  403. db('api_request_log')->where('id',API_REQUEST_ID)->update(['result'=>json_encode($log_result)]);
  404. }
  405. }
  406. }
  407. /**
  408. * 接口请求限制
  409. * @param int $apiLimit
  410. * @param int $apiLimitTime
  411. * @param string $key
  412. * @return bool | true:通过 false:拒绝
  413. */
  414. public function apiLimit($apiLimit = 1, $apiLimitTime = 1000, $key = '')
  415. {
  416. $userId = $this->auth->id;
  417. $controller = request()->controller();
  418. $action = request()->action();
  419. if (!$key) {
  420. $key = strtolower($controller) . '_' . strtolower($action) . '_' . $userId;
  421. }
  422. $redis = new Redis();
  423. $redisconfig = config("redis");
  424. $redis->connect($redisconfig["host"], $redisconfig["port"]);
  425. if ($redisconfig['redis_pwd']) {
  426. $redis->auth($redisconfig['redis_pwd']);
  427. }
  428. if($redisconfig['redis_selectdb'] > 0){
  429. $redis->select($redisconfig['redis_selectdb']);
  430. }
  431. //
  432. //指定键值新增+1 并获取
  433. $count = $redis->incr($key);
  434. if ($count > $apiLimit) {
  435. return false;
  436. }
  437. //设置过期时间
  438. if ($count == 1) {
  439. $redis->pExpire($key, $apiLimitTime);
  440. }
  441. return true;
  442. }
  443. }