Api.php 14 KB

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