Apic.php 14 KB

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