Apitv.php 15 KB

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