Api.php 15 KB

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