Api.php 14 KB

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