Api.php 14 KB

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