Api.php 16 KB

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