Api.php 12 KB

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