Api.php 13 KB

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