Api.php 16 KB

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