Api.php 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591
  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. use app\utils\LogUtil;
  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. * @var int 日志类型 1 文件;2sql
  61. */
  62. public $logType = 2;
  63. /**
  64. * 构造方法
  65. * @access public
  66. * @param Request $request Request 对象
  67. */
  68. public function __construct(Request $request = null)
  69. {
  70. $this->request = is_null($request) ? Request::instance() : $request;
  71. $this->page = input('page',1);
  72. $this->listrow= input('listrow',10);
  73. if(config('site.apisite_switch') == 0){
  74. $controllername = $this->request->controller();
  75. $controllername = strtolower($controllername);
  76. if(!in_array($controllername,['notifynew','easemob','payios'])){
  77. $notice = config('site.apisite_notice') ?: '全站维护中';
  78. $this->error($notice);
  79. }
  80. }
  81. // 控制器初始化
  82. $this->_initialize();
  83. //日志
  84. $this->request_log();
  85. //用户活跃
  86. $this->user_active();
  87. // 前置操作方法
  88. if ($this->beforeActionList) {
  89. foreach ($this->beforeActionList as $method => $options) {
  90. is_numeric($method) ?
  91. $this->beforeAction($options) :
  92. $this->beforeAction($method, $options);
  93. }
  94. }
  95. }
  96. /**
  97. * 初始化操作
  98. * @access protected
  99. */
  100. protected function _initialize()
  101. {
  102. //跨域请求检测
  103. check_cors_request();
  104. // 检测IP是否允许
  105. check_ip_allowed();
  106. //移除HTML标签
  107. $this->request->filter('trim,strip_tags,htmlspecialchars');
  108. $this->auth = Auth::instance();
  109. $modulename = $this->request->module();
  110. $controllername = Loader::parseName($this->request->controller());
  111. $actionname = strtolower($this->request->action());
  112. // token
  113. $token = $this->request->server('HTTP_TOKEN', $this->request->request('token', \think\Cookie::get('token')));
  114. $path = str_replace('.', '/', $controllername) . '/' . $actionname;
  115. // 设置当前请求的URI
  116. $this->auth->setRequestUri($path);
  117. // 检测是否需要验证登录
  118. if (!$this->auth->match($this->noNeedLogin)) {
  119. //初始化
  120. $this->auth->init($token);
  121. //检测是否登录
  122. if (!$this->auth->isLogin()) {
  123. $this->error(__('Please login first'), null, 401);
  124. }
  125. // 判断是否需要验证权限
  126. /*if (!$this->auth->match($this->noNeedRight)) {
  127. // 判断控制器和方法判断是否有对应权限
  128. if (!$this->auth->check($path)) {
  129. $this->error(__('You have no permission'), null, 403);
  130. }
  131. }*/
  132. } else {
  133. // 如果有传递token才验证是否登录状态
  134. if ($token) {
  135. $this->auth->init($token);
  136. //传就必须传对
  137. if (!$this->auth->isLogin()) {
  138. $this->error(__('Please login first'), null, 401);
  139. }
  140. }
  141. }
  142. $upload = \app\common\model\Config::upload();
  143. // 上传信息配置后
  144. Hook::listen("upload_config_init", $upload);
  145. Config::set('upload', array_merge(Config::get('upload'), $upload));
  146. // 加载当前控制器语言包
  147. $this->loadlang($controllername);
  148. }
  149. /**
  150. * 加载语言文件
  151. * @param string $name
  152. */
  153. protected function loadlang($name)
  154. {
  155. $name = Loader::parseName($name);
  156. Lang::load(APP_PATH . $this->request->module() . '/lang/' . $this->request->langset() . '/' . str_replace('.', '/', $name) . '.php');
  157. }
  158. /**
  159. * 操作成功返回的数据
  160. * @param string $msg 提示信息
  161. * @param mixed $data 要返回的数据
  162. * @param int $code 错误码,默认为1
  163. * @param string $type 输出类型
  164. * @param array $header 发送的 Header 信息
  165. */
  166. protected function success($msg = '', $data = null, $code = 1, $type = null, array $header = [])
  167. {
  168. if($msg == 1){
  169. $msg = 'success';
  170. }
  171. if(empty($msg)){
  172. $msg = '操作成功';
  173. }
  174. $this->result($msg, $data, $code, $type, $header);
  175. }
  176. //find查询出来的结果如果为空数组,强制转换object
  177. protected function success_find($msg = '', $data = null, $code = 1, $type = null, array $header = [])
  178. {
  179. if(empty($msg)){
  180. $msg = '操作成功';
  181. }
  182. if(is_null($data) || $data === []){
  183. $data = (object)[];
  184. }
  185. $this->result($msg, $data, $code, $type, $header);
  186. }
  187. /**
  188. * 操作失败返回的数据
  189. * @param string $msg 提示信息
  190. * @param mixed $data 要返回的数据
  191. * @param int $code 错误码,默认为0
  192. * @param string $type 输出类型
  193. * @param array $header 发送的 Header 信息
  194. */
  195. protected function error($msg = '', $data = null, $code = 0, $type = null, array $header = [])
  196. {
  197. if(empty($msg)){
  198. $msg = __('Invalid parameters');
  199. }
  200. $this->result($msg, $data, $code, $type, $header);
  201. }
  202. /**
  203. * 返回封装后的 API 数据到客户端
  204. * @access protected
  205. * @param mixed $msg 提示信息
  206. * @param mixed $data 要返回的数据
  207. * @param int $code 错误码,默认为0
  208. * @param string $type 输出类型,支持json/xml/jsonp
  209. * @param array $header 发送的 Header 信息
  210. * @return void
  211. * @throws HttpResponseException
  212. */
  213. protected function result($msg, $data = null, $code = 0, $type = null, array $header = [])
  214. {
  215. $result = [
  216. 'code' => $code,
  217. 'msg' => $msg,
  218. 'time' => Request::instance()->server('REQUEST_TIME'),
  219. 'data' => $data,
  220. ];
  221. //日志
  222. $this->request_log_update($result);
  223. // 如果未设置类型则自动判断
  224. $type = $type ? $type : ($this->request->param(config('var_jsonp_handler')) ? 'jsonp' : $this->responseType);
  225. if (isset($header['statuscode'])) {
  226. $code = $header['statuscode'];
  227. unset($header['statuscode']);
  228. } else {
  229. //未设置状态码,根据code值判断
  230. $code = $code >= 1000 || $code < 200 ? 200 : $code;
  231. }
  232. $response = Response::create($result, $type, $code)->header($header);
  233. throw new HttpResponseException($response);
  234. }
  235. /**
  236. * 前置操作
  237. * @access protected
  238. * @param string $method 前置操作方法名
  239. * @param array $options 调用参数 ['only'=>[...]] 或者 ['except'=>[...]]
  240. * @return void
  241. */
  242. protected function beforeAction($method, $options = [])
  243. {
  244. if (isset($options['only'])) {
  245. if (is_string($options['only'])) {
  246. $options['only'] = explode(',', $options['only']);
  247. }
  248. if (!in_array($this->request->action(), $options['only'])) {
  249. return;
  250. }
  251. } elseif (isset($options['except'])) {
  252. if (is_string($options['except'])) {
  253. $options['except'] = explode(',', $options['except']);
  254. }
  255. if (in_array($this->request->action(), $options['except'])) {
  256. return;
  257. }
  258. }
  259. call_user_func([$this, $method]);
  260. }
  261. /**
  262. * 设置验证失败后是否抛出异常
  263. * @access protected
  264. * @param bool $fail 是否抛出异常
  265. * @return $this
  266. */
  267. protected function validateFailException($fail = true)
  268. {
  269. $this->failException = $fail;
  270. return $this;
  271. }
  272. /**
  273. * 验证数据
  274. * @access protected
  275. * @param array $data 数据
  276. * @param string|array $validate 验证器名或者验证规则数组
  277. * @param array $message 提示信息
  278. * @param bool $batch 是否批量验证
  279. * @param mixed $callback 回调方法(闭包)
  280. * @return array|string|true
  281. * @throws ValidateException
  282. */
  283. protected function validate($data, $validate, $message = [], $batch = false, $callback = null)
  284. {
  285. if (is_array($validate)) {
  286. $v = Loader::validate();
  287. $v->rule($validate);
  288. } else {
  289. // 支持场景
  290. if (strpos($validate, '.')) {
  291. list($validate, $scene) = explode('.', $validate);
  292. }
  293. $v = Loader::validate($validate);
  294. !empty($scene) && $v->scene($scene);
  295. }
  296. // 批量验证
  297. if ($batch || $this->batchValidate) {
  298. $v->batch(true);
  299. }
  300. // 设置错误信息
  301. if (is_array($message)) {
  302. $v->message($message);
  303. }
  304. // 使用回调验证
  305. if ($callback && is_callable($callback)) {
  306. call_user_func_array($callback, [$v, &$data]);
  307. }
  308. if (!$v->check($data)) {
  309. if ($this->failException) {
  310. throw new ValidateException($v->getError());
  311. }
  312. return $v->getError();
  313. }
  314. return true;
  315. }
  316. /**
  317. * 刷新Token
  318. */
  319. protected function token()
  320. {
  321. $token = $this->request->param('__token__');
  322. //验证Token
  323. if (!Validate::make()->check(['__token__' => $token], ['__token__' => 'require|token'])) {
  324. $this->error(__('Token verification error'), ['__token__' => $this->request->token()]);
  325. }
  326. //刷新Token
  327. $this->request->token();
  328. }
  329. /*
  330. * api 请求日志
  331. * */
  332. protected function request_log(){
  333. //api_request_log
  334. $modulename = $this->request->module();
  335. $controllername = $this->request->controller();
  336. $actionname = $this->request->action();
  337. if(strtolower($actionname) == 'callback'){
  338. return true;
  339. }
  340. defined('API_REQUEST_LOG_TYPE') or define('API_REQUEST_LOG_TYPE', $this->logType);
  341. $params = $this->request->request();
  342. if ($this->logType === 1){
  343. //日志统一写入
  344. register_shutdown_function([new LogUtil, 'close']);
  345. LogUtil::getInstance('Api/'); //设置日志存入通道
  346. LogUtil::info('uid', 'Api-Middleware-Log', 'request_log', $this->auth->id);
  347. LogUtil::info('url', 'Api-Middleware-Log', 'request_log', $modulename . '/' . $controllername . '/' . $actionname);
  348. LogUtil::info('params', 'Api-Middleware-Log', 'request_log', $params);
  349. LogUtil::info('ip', 'Api-Middleware-Log', 'request_log', request()->ip());
  350. }else{
  351. $data = [
  352. 'uid' => $this->auth->id,
  353. 'api' => $modulename.'/'.$controllername.'/'.$actionname,
  354. 'params' => json_encode($params),
  355. 'addtime' => time(),
  356. 'adddatetime' => date('Y-m-d H:i:s'),
  357. 'ip' => request()->ip(),
  358. ];
  359. $request_id = db('api_request_log')->insertGetId($data);
  360. defined('API_REQUEST_ID') or define('API_REQUEST_ID', $request_id);
  361. }
  362. }
  363. //更新用户活跃
  364. protected function user_active(){
  365. if($this->auth->isLogin()){
  366. db('user_active')->where('user_id',$this->auth->id)->update(['requesttime'=>time()]);
  367. if($this->auth->is_active == 0){
  368. db('user')->where('id',$this->auth->id)->update(['is_active'=>1]);
  369. }
  370. }
  371. }
  372. protected function request_log_update($log_result){
  373. $actionname = $this->request->action();
  374. if(strtolower($actionname) == 'givegifttoyou'){
  375. //return true;
  376. }
  377. if ($this->logType === 1){
  378. if (strlen(json_encode($log_result['data'])) > 1000) {
  379. $log_result['data'] = '数据太多,不记录';
  380. }
  381. LogUtil::info('result', 'Api-Middleware-Log', 'request_log', $log_result);
  382. }else{
  383. if(defined('API_REQUEST_ID')) { //记录app正常返回结果
  384. if(strlen(json_encode($log_result['data'])) > 1000) {
  385. $log_result['data'] = '数据太多,不记录';
  386. }
  387. db('api_request_log')->where('id',API_REQUEST_ID)->update(['result'=>json_encode($log_result)]);
  388. }
  389. }
  390. }
  391. /**
  392. * 接口请求限制
  393. * @param int $apiLimit
  394. * @param int $apiLimitTime
  395. * @param string $key
  396. * @return bool | true:通过 false:拒绝
  397. */
  398. public function apiLimit($apiLimit = 1, $apiLimitTime = 1000, $key = '')
  399. {
  400. $userId = $this->auth->id;
  401. $controller = request()->controller();
  402. $action = request()->action();
  403. if (!$key) {
  404. $key = strtolower($controller) . '_' . strtolower($action) . '_' . $userId;
  405. }
  406. $redis = new Redis();
  407. $redisconfig = config("redis");
  408. $redis->connect($redisconfig["host"], $redisconfig["port"]);
  409. if ($redisconfig['redis_pwd']) {
  410. $redis->auth($redisconfig['redis_pwd']);
  411. }
  412. if($redisconfig['redis_selectdb'] > 0){
  413. $redis->select($redisconfig['redis_selectdb']);
  414. }
  415. //
  416. //指定键值新增+1 并获取
  417. $count = $redis->incr($key);
  418. if ($count > $apiLimit) {
  419. return false;
  420. }
  421. //设置过期时间
  422. if ($count == 1) {
  423. $redis->pExpire($key, $apiLimitTime);
  424. }
  425. return true;
  426. }
  427. //获取用户是否活跃,7200秒,2小时
  428. //1活跃,0不活跃
  429. protected function user_activeinfo($user_id,$requesttime = 0){
  430. if(empty($requesttime)){
  431. $requesttime = db('user_active')->where('user_id',$user_id)->value('requesttime');
  432. }
  433. $result = [
  434. 'is_active' => 1,
  435. 'active_text' => get_last_time($requesttime).'在线',
  436. ];
  437. if(time() - $requesttime > 7200){
  438. $result = [
  439. 'is_active' => 0,
  440. 'active_text' => '离线',
  441. ];
  442. }
  443. return $result;
  444. }
  445. //获取用户是否vip,1是,0否
  446. protected function is_vip($user_id){
  447. $result = 0;
  448. $vip_endtime = db('user_wallet')->where('user_id',$user_id)->value('vip_endtime');
  449. $result = $vip_endtime > time() ? 1 : 0;
  450. return $result;
  451. }
  452. //用户是否有某项权限
  453. //1有,0没有
  454. protected function user_power($user_id,$power = ''){
  455. /*$is_vip = $this->is_vip($user_id);
  456. if($is_vip != 1){
  457. return 0;
  458. }*/
  459. $power = db('user_power')->where('user_id',$user_id)->value($power);
  460. return $power;
  461. }
  462. //是否关注
  463. protected function is_follow($uid,$follow_uid){
  464. $where = [
  465. 'uid' => $uid,
  466. 'follow_uid' => $follow_uid,
  467. ];
  468. $check = db('user_follow')->where($where)->find();
  469. if($check){
  470. return 1;
  471. }else{
  472. return 0;
  473. }
  474. }
  475. //是否好友
  476. protected function is_friend($uid,$follow_uid){
  477. $is_follow = $this->is_follow($uid,$follow_uid);
  478. $be_follow = $this->is_follow($follow_uid,$uid);
  479. if($is_follow && $be_follow){
  480. return 1;
  481. }
  482. return 0;
  483. }
  484. //用户是否拉黑
  485. protected function is_black($uid,$black_uid){
  486. $where = [
  487. 'uid' => $uid,
  488. 'black_uid' => $black_uid,
  489. ];
  490. $check = db('user_black')->where($where)->find();
  491. if($check){
  492. return 1;
  493. }else{
  494. return 0;
  495. }
  496. }
  497. //实名认证限制功能
  498. //true 不需要实名认证,不受限
  499. //false 需要实名认证,受限
  500. protected function user_auth_limit(){
  501. if($this->auth->idcard_status == 1){
  502. return true; //已实名,不受限
  503. }else{
  504. return false;
  505. }
  506. }
  507. }