Apitv.php 15 KB

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