Apitv.php 16 KB

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