Apic.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459
  1. <?php
  2. namespace app\common\controller;
  3. use app\common\library\Authcompany as Auth;
  4. use think\Config;
  5. use think\exception\HttpResponseException;
  6. use think\exception\ValidateException;
  7. use think\Hook;
  8. use think\Lang;
  9. use think\Loader;
  10. use think\Request;
  11. use think\Response;
  12. use think\Route;
  13. use think\Validate;
  14. use Redis;
  15. use app\utils\LogUtil;
  16. use think\Controller;
  17. /**
  18. * API控制器基类
  19. */
  20. class Apic extends Controller
  21. {
  22. /**
  23. * @var Request Request 实例
  24. */
  25. protected $request;
  26. /**
  27. * @var bool 验证失败是否抛出异常
  28. */
  29. protected $failException = false;
  30. /**
  31. * @var bool 是否批量验证
  32. */
  33. protected $batchValidate = false;
  34. /**
  35. * @var array 前置操作方法列表
  36. */
  37. protected $beforeActionList = [];
  38. /**
  39. * 无需登录的方法,同时也就不需要鉴权了
  40. * @var array
  41. */
  42. protected $noNeedLogin = [];
  43. /**
  44. * 无需鉴权的方法,但需要登录
  45. * @var array
  46. */
  47. protected $noNeedRight = [];
  48. /**
  49. * 权限Auth
  50. * @var Auth
  51. */
  52. protected $auth = null;
  53. /**
  54. * 默认响应输出类型,支持json/xml
  55. * @var string
  56. */
  57. protected $responseType = 'json';
  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. parent::__construct();//有了这一句,才有了模板
  70. $this->request = is_null($request) ? Request::instance() : $request;
  71. if(config('site.apisite_switch') == 0){
  72. $controllername = $this->request->controller();
  73. $controllername = strtolower($controllername);
  74. if(!in_array($controllername,['notify','easemob','payios'])){
  75. $notice = config('site.apisite_notice') ?: '全站维护中';
  76. $this->error($notice);
  77. }
  78. }
  79. // 控制器初始化
  80. $this->_initialize();
  81. //日志
  82. $this->request_log();
  83. // 前置操作方法
  84. if ($this->beforeActionList) {
  85. foreach ($this->beforeActionList as $method => $options) {
  86. is_numeric($method) ?
  87. $this->beforeAction($options) :
  88. $this->beforeAction($method, $options);
  89. }
  90. }
  91. }
  92. /**
  93. * 初始化操作
  94. * @access protected
  95. */
  96. protected function _initialize()
  97. {
  98. //跨域请求检测
  99. check_cors_request();
  100. // 检测IP是否允许
  101. check_ip_allowed();
  102. //移除HTML标签
  103. $this->request->filter('trim,strip_tags,htmlspecialchars');
  104. $this->auth = Auth::instance();
  105. $modulename = $this->request->module();
  106. $controllername = Loader::parseName($this->request->controller());
  107. $actionname = strtolower($this->request->action());
  108. // token
  109. $token = $this->request->server('HTTP_TOKEN', $this->request->request('token', \think\Cookie::get('token')));
  110. // $path = str_replace('.', '/', $controllername) . '/' . $actionname;
  111. $path = $modulename. '/' .str_replace('.', '/', $controllername) . '/' . $actionname;
  112. // 设置当前请求的URI
  113. $this->auth->setRequestUri($path);
  114. // 检测是否需要验证登录
  115. if (!$this->auth->match($this->noNeedLogin)) {
  116. //初始化
  117. $this->auth->init($token);
  118. //检测是否登录
  119. if (!$this->auth->isLogin()) {
  120. $this->error(__('Please login first'), null, 401);
  121. }
  122. // 判断是否需要验证权限
  123. if (!$this->auth->match($this->noNeedRight)) {
  124. // 判断控制器和方法判断是否有对应权限
  125. if (!$this->auth->check($path)) {
  126. $this->error(__('You have no permission'), null, 403,null,['statuscode'=>200]);
  127. }
  128. }
  129. } else {
  130. // 如果有传递token才验证是否登录状态
  131. if ($token) {
  132. $this->auth->init($token);
  133. //传就必须传对
  134. if (!$this->auth->isLogin()) {
  135. $this->error(__('Please login first'), null, 401);
  136. }
  137. }
  138. }
  139. $upload = \app\common\model\Config::upload();
  140. // 上传信息配置后
  141. Hook::listen("upload_config_init", $upload);
  142. Config::set('upload', array_merge(Config::get('upload'), $upload));
  143. // 加载当前控制器语言包
  144. $this->loadlang($controllername);
  145. }
  146. /**
  147. * 加载语言文件
  148. * @param string $name
  149. */
  150. protected function loadlang($name)
  151. {
  152. $name = Loader::parseName($name);
  153. $name = preg_match("/^([a-zA-Z0-9_\.\/]+)\$/i", $name) ? $name : 'index';
  154. $lang = $this->request->langset();
  155. $lang = preg_match("/^([a-zA-Z\-_]{2,10})\$/i", $lang) ? $lang : 'zh-cn';
  156. Lang::load(APP_PATH . $this->request->module() . '/lang/' . $lang . '/' . str_replace('.', '/', $name) . '.php');
  157. }
  158. /**
  159. * 操作成功返回的数据
  160. * @param string $msg 提示信息
  161. * @param mixed $data 要返回的数据
  162. * @param int $code 错误码,默认为1
  163. * @param string $type 输出类型
  164. * @param array $header 发送的 Header 信息
  165. */
  166. protected function success($msg = '', $data = null, $code = 1, $type = null, array $header = [])
  167. {
  168. if($msg == 1){
  169. $msg = 'success';
  170. }
  171. if(empty($msg)){
  172. $msg = '操作成功';
  173. }
  174. $this->result($msg, $data, $code, $type, $header);
  175. }
  176. /**
  177. * 操作失败返回的数据
  178. * @param string $msg 提示信息
  179. * @param mixed $data 要返回的数据
  180. * @param int $code 错误码,默认为0
  181. * @param string $type 输出类型
  182. * @param array $header 发送的 Header 信息
  183. */
  184. protected function error($msg = '', $data = null, $code = 0, $type = null, array $header = [])
  185. {
  186. if(empty($msg)){
  187. $msg = __('Invalid parameters');
  188. }
  189. $this->result($msg, $data, $code, $type, $header);
  190. }
  191. /**
  192. * 返回封装后的 API 数据到客户端
  193. * @access protected
  194. * @param mixed $msg 提示信息
  195. * @param mixed $data 要返回的数据
  196. * @param int $code 错误码,默认为0
  197. * @param string $type 输出类型,支持json/xml/jsonp
  198. * @param array $header 发送的 Header 信息
  199. * @return void
  200. * @throws HttpResponseException
  201. */
  202. protected function result($msg, $data = null, $code = 0, $type = null, array $header = [])
  203. {
  204. $result = [
  205. 'code' => $code,
  206. 'msg' => $msg,
  207. 'time' => Request::instance()->server('REQUEST_TIME'),
  208. 'data' => $data,
  209. ];
  210. //日志
  211. $this->request_log_update($result);
  212. // 如果未设置类型则使用默认类型判断
  213. $type = $type ? : $this->responseType;
  214. if (isset($header['statuscode'])) {
  215. $code = $header['statuscode'];
  216. unset($header['statuscode']);
  217. } else {
  218. //未设置状态码,根据code值判断
  219. $code = $code >= 1000 || $code < 200 ? 200 : $code;
  220. }
  221. $response = Response::create($result, $type, $code)->header($header);
  222. throw new HttpResponseException($response);
  223. }
  224. /**
  225. * 前置操作
  226. * @access protected
  227. * @param string $method 前置操作方法名
  228. * @param array $options 调用参数 ['only'=>[...]] 或者 ['except'=>[...]]
  229. * @return void
  230. */
  231. protected function beforeAction($method, $options = [])
  232. {
  233. if (isset($options['only'])) {
  234. if (is_string($options['only'])) {
  235. $options['only'] = explode(',', $options['only']);
  236. }
  237. if (!in_array($this->request->action(), $options['only'])) {
  238. return;
  239. }
  240. } elseif (isset($options['except'])) {
  241. if (is_string($options['except'])) {
  242. $options['except'] = explode(',', $options['except']);
  243. }
  244. if (in_array($this->request->action(), $options['except'])) {
  245. return;
  246. }
  247. }
  248. call_user_func([$this, $method]);
  249. }
  250. /**
  251. * 设置验证失败后是否抛出异常
  252. * @access protected
  253. * @param bool $fail 是否抛出异常
  254. * @return $this
  255. */
  256. protected function validateFailException($fail = true)
  257. {
  258. $this->failException = $fail;
  259. return $this;
  260. }
  261. /**
  262. * 验证数据
  263. * @access protected
  264. * @param array $data 数据
  265. * @param string|array $validate 验证器名或者验证规则数组
  266. * @param array $message 提示信息
  267. * @param bool $batch 是否批量验证
  268. * @param mixed $callback 回调方法(闭包)
  269. * @return array|string|true
  270. * @throws ValidateException
  271. */
  272. protected function validate($data, $validate, $message = [], $batch = false, $callback = null)
  273. {
  274. if (is_array($validate)) {
  275. $v = Loader::validate();
  276. $v->rule($validate);
  277. } else {
  278. // 支持场景
  279. if (strpos($validate, '.')) {
  280. list($validate, $scene) = explode('.', $validate);
  281. }
  282. $v = Loader::validate($validate);
  283. !empty($scene) && $v->scene($scene);
  284. }
  285. // 批量验证
  286. if ($batch || $this->batchValidate) {
  287. $v->batch(true);
  288. }
  289. // 设置错误信息
  290. if (is_array($message)) {
  291. $v->message($message);
  292. }
  293. // 使用回调验证
  294. if ($callback && is_callable($callback)) {
  295. call_user_func_array($callback, [$v, &$data]);
  296. }
  297. if (!$v->check($data)) {
  298. if ($this->failException) {
  299. throw new ValidateException($v->getError());
  300. }
  301. return $v->getError();
  302. }
  303. return true;
  304. }
  305. /**
  306. * 接口请求限制
  307. * @param int $apiLimit
  308. * @param int $apiLimitTime
  309. * @param string $key
  310. * @return bool | true:通过 false:拒绝
  311. */
  312. public function apiLimit($apiLimit = 1, $apiLimitTime = 1000, $key = '')
  313. {
  314. $userId = $this->auth->id;
  315. $controller = request()->controller();
  316. $action = request()->action();
  317. if (!$key) {
  318. $key = strtolower($controller) . '_' . strtolower($action) . '_' . $userId;
  319. }
  320. $redis = new Redis();
  321. $redisconfig = config("redis");
  322. $redis->connect($redisconfig["host"], $redisconfig["port"]);
  323. if ($redisconfig['redis_pwd']) {
  324. $redis->auth($redisconfig['redis_pwd']);
  325. }
  326. if($redisconfig['redis_selectdb'] > 0){
  327. $redis->select($redisconfig['redis_selectdb']);
  328. }
  329. //
  330. //指定键值新增+1 并获取
  331. $count = $redis->incr($key);
  332. if ($count > $apiLimit) {
  333. return false;
  334. }
  335. //设置过期时间
  336. if ($count == 1) {
  337. $redis->pExpire($key, $apiLimitTime);
  338. }
  339. return true;
  340. }
  341. /*
  342. * api 请求日志
  343. * */
  344. protected function request_log(){
  345. //api_request_log
  346. $modulename = $this->request->module();
  347. $controllername = $this->request->controller();
  348. $actionname = $this->request->action();
  349. if(strtolower($actionname) == 'callback'){
  350. return true;
  351. }
  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('Apic/'); //设置日志存入通道
  358. LogUtil::info('uid', 'Api-Middleware-Log', 'request_log', $this->auth->id);
  359. LogUtil::info('api', 'Api-Middleware-Log', 'request_log', $modulename . '/' . $controllername . '/' . $actionname);
  360. LogUtil::info('params', 'Api-Middleware-Log', 'request_log', json_encode($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. }