Apic.php 13 KB

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