Api.php 15 KB

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