Api.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487
  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 = input('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 = preg_match("/^([a-zA-Z\-_]{2,10})\$/i", $lang) ? $lang : 'zh-cn';
  143. Lang::load(APP_PATH . $this->request->module() . '/lang/' . $lang . '/' . str_replace('.', '/', $name) . '.php');
  144. }
  145. //结果集信息里,多个字段需要翻译
  146. protected function list_lang($list,$field){
  147. if(!$list || empty($list)){
  148. return $list;
  149. }
  150. foreach($list as $vo => $info){
  151. $list[$vo] = $this->info_lang($info,$field);
  152. }
  153. return $list;
  154. }
  155. //单条信息里,多个字段需要翻译
  156. protected function info_lang($data,$field){
  157. if(!$data || empty($data)){
  158. return $data;
  159. }
  160. foreach($data as $key => $val){
  161. if(in_array($key,$field)){
  162. if($this->lang == 'EN'){
  163. $data[$key] = $data[$key.'_en'];
  164. unset($data[$key.'_en']);
  165. }else{
  166. unset($data[$key.'_en']);
  167. }
  168. }
  169. }
  170. return $data;
  171. }
  172. /**
  173. * 操作成功返回的数据
  174. * @param string $msg 提示信息
  175. * @param mixed $data 要返回的数据
  176. * @param int $code 错误码,默认为1
  177. * @param string $type 输出类型
  178. * @param array $header 发送的 Header 信息
  179. */
  180. protected function success($msg = '', $data = null, $code = 1, $type = null, array $header = [])
  181. {
  182. if($msg == 1){
  183. $msg = 'success';
  184. }
  185. if(empty($msg)){
  186. $msg = '操作成功';
  187. }
  188. $this->result($msg, $data, $code, $type, $header);
  189. }
  190. //find查询出来的结果如果为空数组,强制转换object
  191. protected function success_find($msg = '', $data = null, $code = 1, $type = null, array $header = [])
  192. {
  193. if(empty($msg)){
  194. $msg = '操作成功';
  195. }
  196. if(is_null($data) || $data === []){
  197. $data = (object)[];
  198. }
  199. $this->result($msg, $data, $code, $type, $header);
  200. }
  201. /**
  202. * 操作失败返回的数据
  203. * @param string $msg 提示信息
  204. * @param mixed $data 要返回的数据
  205. * @param int $code 错误码,默认为0
  206. * @param string $type 输出类型
  207. * @param array $header 发送的 Header 信息
  208. */
  209. protected function error($msg = '', $data = null, $code = 0, $type = null, array $header = [])
  210. {
  211. if(empty($msg)){
  212. $msg = __('Invalid parameters');
  213. }
  214. $this->result($msg, $data, $code, $type, $header);
  215. }
  216. /**
  217. * 返回封装后的 API 数据到客户端
  218. * @access protected
  219. * @param mixed $msg 提示信息
  220. * @param mixed $data 要返回的数据
  221. * @param int $code 错误码,默认为0
  222. * @param string $type 输出类型,支持json/xml/jsonp
  223. * @param array $header 发送的 Header 信息
  224. * @return void
  225. * @throws HttpResponseException
  226. */
  227. protected function result($msg, $data = null, $code = 0, $type = null, array $header = [])
  228. {
  229. $result = [
  230. 'code' => $code,
  231. 'msg' => $msg,
  232. 'time' => Request::instance()->server('REQUEST_TIME'),
  233. 'data' => $data,
  234. ];
  235. //日志
  236. $this->request_log_update($result);
  237. // 如果未设置类型则自动判断
  238. $type = $type ? $type : ($this->request->param(config('var_jsonp_handler')) ? 'jsonp' : $this->responseType);
  239. if (isset($header['statuscode'])) {
  240. $code = $header['statuscode'];
  241. unset($header['statuscode']);
  242. } else {
  243. //未设置状态码,根据code值判断
  244. $code = $code >= 1000 || $code < 200 ? 200 : $code;
  245. }
  246. $response = Response::create($result, $type, $code)->header($header);
  247. throw new HttpResponseException($response);
  248. }
  249. /**
  250. * 前置操作
  251. * @access protected
  252. * @param string $method 前置操作方法名
  253. * @param array $options 调用参数 ['only'=>[...]] 或者 ['except'=>[...]]
  254. * @return void
  255. */
  256. protected function beforeAction($method, $options = [])
  257. {
  258. if (isset($options['only'])) {
  259. if (is_string($options['only'])) {
  260. $options['only'] = explode(',', $options['only']);
  261. }
  262. if (!in_array($this->request->action(), $options['only'])) {
  263. return;
  264. }
  265. } elseif (isset($options['except'])) {
  266. if (is_string($options['except'])) {
  267. $options['except'] = explode(',', $options['except']);
  268. }
  269. if (in_array($this->request->action(), $options['except'])) {
  270. return;
  271. }
  272. }
  273. call_user_func([$this, $method]);
  274. }
  275. /**
  276. * 设置验证失败后是否抛出异常
  277. * @access protected
  278. * @param bool $fail 是否抛出异常
  279. * @return $this
  280. */
  281. protected function validateFailException($fail = true)
  282. {
  283. $this->failException = $fail;
  284. return $this;
  285. }
  286. /**
  287. * 验证数据
  288. * @access protected
  289. * @param array $data 数据
  290. * @param string|array $validate 验证器名或者验证规则数组
  291. * @param array $message 提示信息
  292. * @param bool $batch 是否批量验证
  293. * @param mixed $callback 回调方法(闭包)
  294. * @return array|string|true
  295. * @throws ValidateException
  296. */
  297. protected function validate($data, $validate, $message = [], $batch = false, $callback = null)
  298. {
  299. if (is_array($validate)) {
  300. $v = Loader::validate();
  301. $v->rule($validate);
  302. } else {
  303. // 支持场景
  304. if (strpos($validate, '.')) {
  305. list($validate, $scene) = explode('.', $validate);
  306. }
  307. $v = Loader::validate($validate);
  308. !empty($scene) && $v->scene($scene);
  309. }
  310. // 批量验证
  311. if ($batch || $this->batchValidate) {
  312. $v->batch(true);
  313. }
  314. // 设置错误信息
  315. if (is_array($message)) {
  316. $v->message($message);
  317. }
  318. // 使用回调验证
  319. if ($callback && is_callable($callback)) {
  320. call_user_func_array($callback, [$v, &$data]);
  321. }
  322. if (!$v->check($data)) {
  323. if ($this->failException) {
  324. throw new ValidateException($v->getError());
  325. }
  326. return $v->getError();
  327. }
  328. return true;
  329. }
  330. /**
  331. * 刷新Token
  332. */
  333. protected function token()
  334. {
  335. $token = $this->request->param('__token__');
  336. //验证Token
  337. if (!Validate::make()->check(['__token__' => $token], ['__token__' => 'require|token'])) {
  338. $this->error(__('Token verification error'), ['__token__' => $this->request->token()]);
  339. }
  340. //刷新Token
  341. $this->request->token();
  342. }
  343. /*
  344. * api 请求日志
  345. * */
  346. protected function request_log(){
  347. //api_request_log
  348. $modulename = $this->request->module();
  349. $controllername = $this->request->controller();
  350. $actionname = $this->request->action();
  351. defined('API_REQUEST_LOG_TYPE') or define('API_REQUEST_LOG_TYPE', $this->logType);
  352. $params = $this->request->request();
  353. if ($this->logType === 1){
  354. //日志统一写入
  355. register_shutdown_function([new LogUtil, 'close']);
  356. LogUtil::getInstance('Api/'); //设置日志存入通道
  357. LogUtil::info('uid', 'Api-Middleware-Log', 'request_log', $this->auth->id);
  358. LogUtil::info('url', 'Api-Middleware-Log', 'request_log', $modulename . '/' . $controllername . '/' . $actionname);
  359. LogUtil::info('params', 'Api-Middleware-Log', 'request_log', $params);
  360. LogUtil::info('ip', 'Api-Middleware-Log', 'request_log', request()->ip());
  361. }else{
  362. $data = [
  363. 'uid' => $this->auth->id,
  364. 'api' => $modulename.'/'.$controllername.'/'.$actionname,
  365. 'params' => json_encode($params),
  366. 'addtime' => time(),
  367. 'adddatetime' => date('Y-m-d H:i:s'),
  368. 'ip' => request()->ip(),
  369. ];
  370. $request_id = db('api_request_log')->insertGetId($data);
  371. defined('API_REQUEST_ID') or define('API_REQUEST_ID', $request_id);
  372. }
  373. }
  374. protected function request_log_update($log_result){
  375. if ($this->logType === 1){
  376. if (strlen(json_encode($log_result['data'])) > 1000) {
  377. $log_result['data'] = '数据太多,不记录';
  378. }
  379. LogUtil::info('result', 'Api-Middleware-Log', 'request_log', $log_result);
  380. }else{
  381. if(defined('API_REQUEST_ID')) { //记录app正常返回结果
  382. if(strlen(json_encode($log_result['data'])) > 1000) {
  383. $log_result['data'] = '数据太多,不记录';
  384. }
  385. db('api_request_log')->where('id',API_REQUEST_ID)->update(['result'=>json_encode($log_result)]);
  386. }
  387. }
  388. }
  389. /**
  390. * 接口请求限制
  391. * @param int $apiLimit
  392. * @param int $apiLimitTime
  393. * @param string $key
  394. * @return bool | true:通过 false:拒绝
  395. */
  396. public function apiLimit($apiLimit = 1, $apiLimitTime = 1000, $key = '')
  397. {
  398. $userId = $this->auth->id;
  399. $controller = request()->controller();
  400. $action = request()->action();
  401. if (!$key) {
  402. $key = strtolower($controller) . '_' . strtolower($action) . '_' . $userId;
  403. }
  404. $redis = new Redis();
  405. $redisconfig = config("redis");
  406. $redis->connect($redisconfig["host"], $redisconfig["port"]);
  407. if ($redisconfig['redis_pwd']) {
  408. $redis->auth($redisconfig['redis_pwd']);
  409. }
  410. if($redisconfig['redis_selectdb'] > 0){
  411. $redis->select($redisconfig['redis_selectdb']);
  412. }
  413. $check = $redis->exists($key);
  414. if ($check) {
  415. $redis->incr($key);
  416. $count = $redis->get($key);
  417. if ($count > $apiLimit) {
  418. return false;
  419. }
  420. } else {
  421. $redis->incr($key);
  422. $redis->pExpire($key, $apiLimitTime);
  423. }
  424. return true;
  425. }
  426. }