Apitv.php 15 KB

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