Api.php 13 KB

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