Api.php 14 KB

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