Api.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406
  1. <?php
  2. namespace app\common\controller;
  3. use app\common\library\Auth;
  4. use think\Config;
  5. use think\Db;
  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. /**
  16. * API控制器基类
  17. */
  18. class Api
  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. protected $page;
  58. /**
  59. * 构造方法
  60. * @access public
  61. * @param Request $request Request 对象
  62. */
  63. public function __construct(Request $request = null)
  64. {
  65. $this->request = is_null($request) ? Request::instance() : $request;
  66. $this->page = input('page', 1);
  67. // 控制器初始化
  68. $this->_initialize();
  69. // 前置操作方法
  70. if ($this->beforeActionList) {
  71. foreach ($this->beforeActionList as $method => $options) {
  72. is_numeric($method) ?
  73. $this->beforeAction($options) :
  74. $this->beforeAction($method, $options);
  75. }
  76. }
  77. }
  78. /**
  79. * 初始化操作
  80. * @access protected
  81. */
  82. protected function _initialize()
  83. {
  84. //跨域请求检测
  85. check_cors_request();
  86. // 检测IP是否允许
  87. check_ip_allowed();
  88. //移除HTML标签
  89. $this->request->filter('trim,strip_tags,htmlspecialchars');
  90. $this->auth = Auth::instance();
  91. $modulename = $this->request->module();
  92. $controllername = Loader::parseName($this->request->controller());
  93. $actionname = strtolower($this->request->action());
  94. // token
  95. $token = $this->request->server('HTTP_TOKEN', $this->request->request('token', \think\Cookie::get('token')));
  96. $path = str_replace('.', '/', $controllername) . '/' . $actionname;
  97. // 设置当前请求的URI
  98. $this->auth->setRequestUri($path);
  99. // 检测是否需要验证登录
  100. if (!$this->auth->match($this->noNeedLogin)) {
  101. //初始化
  102. $this->auth->init($token);
  103. //检测是否登录
  104. if (!$this->auth->isLogin()) {
  105. $this->error(__('Please login first'), null, 401);
  106. }
  107. // 判断是否需要验证权限
  108. if (!$this->auth->match($this->noNeedRight)) {
  109. // 判断控制器和方法判断是否有对应权限
  110. if (!$this->auth->check($path)) {
  111. $this->error(__('You have no permission'), null, 403);
  112. }
  113. }
  114. } else {
  115. // 如果有传递token才验证是否登录状态
  116. if ($token) {
  117. $this->auth->init($token);
  118. }
  119. }
  120. $upload = \app\common\model\Config::upload();
  121. // 上传信息配置后
  122. Hook::listen("upload_config_init", $upload);
  123. Config::set('upload', array_merge(Config::get('upload'), $upload));
  124. // 加载当前控制器语言包
  125. $this->loadlang($controllername);
  126. //记录请求地址
  127. $user_log = [
  128. 'user_id' => $this->auth->id ? :'',
  129. 'username' => $this->auth->mobile ? :'',
  130. 'url' => $modulename . '/' . $controllername . '/' . $actionname,
  131. 'content' => json_encode(request()->param('', null, 'trim,strip_tags,htmlspecialchars'), JSON_UNESCAPED_UNICODE),
  132. 'ip' => request()->ip(),
  133. 'useragent' => substr(request()->server('HTTP_USER_AGENT'), 0, 255),
  134. 'createtime' => time()
  135. ];
  136. Db::name('user_log')->insert($user_log);
  137. //检查会员等级, 发送成长值
  138. if ($this->auth->id) {
  139. //查询今日是否登录赠送过成长值
  140. $time = strtotime(date('Y-m-d', time()));
  141. $logingrowth = config('site.logingrowth') ? (int)config('site.logingrowth') : 0;//登录成长值
  142. if ($logingrowth) {
  143. $growth_log = Db::name('user_growth_log')->where(['user_id' => $this->auth->id, 'type' => 1])->order('id', 'desc')->find();
  144. if (!$growth_log || ($growth_log['after'] == $this->auth->growthvalue && $growth_log['createtime'] < $time)) {
  145. $growth_data['user_id'] = $this->auth->id;
  146. $growth_data['growth'] = $logingrowth;
  147. $growth_data['before'] = $this->auth->growthvalue;
  148. $growth_data['after'] = $this->auth->growthvalue + $logingrowth;
  149. $growth_data['memo'] = '登录';
  150. $growth_data['createtime'] = time();
  151. Db::startTrans();
  152. $rt = Db::name('user_growth_log')->insertGetId($growth_data);
  153. $rs = Db::name('user')->where(['id' => $this->auth->id, 'growthvalue' => $this->auth->growthvalue])->setField('growthvalue', $growth_data['after']);
  154. if ($rt && $rs) {
  155. Db::commit();
  156. } else {
  157. Db::rollback();
  158. }
  159. }
  160. }
  161. //检查更新会员等级
  162. $growthvalue = Db::name('user')->where(['id' => $this->auth->id])->value('growthvalue');
  163. $vip_info = Db::name('vip')->where(['growthvalue' => ['elt', $growthvalue]])->order('id', 'desc')->find();
  164. $user_data = [];
  165. if ($vip_info['id'] > $this->auth->growthlevel) {
  166. $user_data['growthlevel'] = $vip_info['id'];
  167. //当前会员信息
  168. $last_vip_info = Db::name('vip')->find($vip_info['id']);
  169. $user_data['freenumber'] = $this->auth->freenumber + $vip_info['free'] - $last_vip_info['free'];
  170. }
  171. //检查体验会员
  172. if ($this->auth->experiencetime < time()) {
  173. //体验会员到期
  174. if ($vip_info['id'] > $this->auth->growthlevel) { //成长值会员等级更新
  175. $user_data['maxlevel'] = $vip_info['id'];
  176. } elseif ($this->auth->maxlevel != $this->auth->growthlevel) {
  177. $user_data['maxlevel'] = $this->auth->growthlevel;
  178. }
  179. } else {
  180. //体验会员没到期
  181. if ($vip_info['id'] > $this->auth->maxlevel) {
  182. $user_data['maxlevel'] = $vip_info['id'];
  183. }
  184. }
  185. if ($user_data) {
  186. Db::startTrans();
  187. $res = Db::name('user')->where(['id' => $this->auth->id])->setField($user_data);
  188. if (!$res) {
  189. Db::rollback();
  190. } else {
  191. Db::commit();
  192. }
  193. }
  194. }
  195. }
  196. /**
  197. * 加载语言文件
  198. * @param string $name
  199. */
  200. protected function loadlang($name)
  201. {
  202. $name = Loader::parseName($name);
  203. Lang::load(APP_PATH . $this->request->module() . '/lang/' . $this->request->langset() . '/' . str_replace('.', '/', $name) . '.php');
  204. }
  205. /**
  206. * 操作成功返回的数据
  207. * @param string $msg 提示信息
  208. * @param mixed $data 要返回的数据
  209. * @param int $code 错误码,默认为1
  210. * @param string $type 输出类型
  211. * @param array $header 发送的 Header 信息
  212. */
  213. protected function success($msg = '', $data = null, $code = 1, $type = null, array $header = [])
  214. {
  215. $this->result($msg, $data, $code, $type, $header);
  216. }
  217. /**
  218. * 操作失败返回的数据
  219. * @param string $msg 提示信息
  220. * @param mixed $data 要返回的数据
  221. * @param int $code 错误码,默认为0
  222. * @param string $type 输出类型
  223. * @param array $header 发送的 Header 信息
  224. */
  225. protected function error($msg = '', $data = null, $code = 0, $type = null, array $header = [])
  226. {
  227. $this->result($msg, $data, $code, $type, $header);
  228. }
  229. /**
  230. * 返回封装后的 API 数据到客户端
  231. * @access protected
  232. * @param mixed $msg 提示信息
  233. * @param mixed $data 要返回的数据
  234. * @param int $code 错误码,默认为0
  235. * @param string $type 输出类型,支持json/xml/jsonp
  236. * @param array $header 发送的 Header 信息
  237. * @return void
  238. * @throws HttpResponseException
  239. */
  240. protected function result($msg, $data = null, $code = 0, $type = null, array $header = [])
  241. {
  242. $result = [
  243. 'code' => $code,
  244. 'msg' => $msg,
  245. 'time' => Request::instance()->server('REQUEST_TIME'),
  246. 'data' => $data,
  247. ];
  248. // 如果未设置类型则自动判断
  249. $type = $type ? $type : ($this->request->param(config('var_jsonp_handler')) ? 'jsonp' : $this->responseType);
  250. if (isset($header['statuscode'])) {
  251. $code = $header['statuscode'];
  252. unset($header['statuscode']);
  253. } else {
  254. //未设置状态码,根据code值判断
  255. $code = $code >= 1000 || $code < 200 ? 200 : $code;
  256. }
  257. $response = Response::create($result, $type, $code)->header($header);
  258. throw new HttpResponseException($response);
  259. }
  260. /**
  261. * 前置操作
  262. * @access protected
  263. * @param string $method 前置操作方法名
  264. * @param array $options 调用参数 ['only'=>[...]] 或者 ['except'=>[...]]
  265. * @return void
  266. */
  267. protected function beforeAction($method, $options = [])
  268. {
  269. if (isset($options['only'])) {
  270. if (is_string($options['only'])) {
  271. $options['only'] = explode(',', $options['only']);
  272. }
  273. if (!in_array($this->request->action(), $options['only'])) {
  274. return;
  275. }
  276. } elseif (isset($options['except'])) {
  277. if (is_string($options['except'])) {
  278. $options['except'] = explode(',', $options['except']);
  279. }
  280. if (in_array($this->request->action(), $options['except'])) {
  281. return;
  282. }
  283. }
  284. call_user_func([$this, $method]);
  285. }
  286. /**
  287. * 设置验证失败后是否抛出异常
  288. * @access protected
  289. * @param bool $fail 是否抛出异常
  290. * @return $this
  291. */
  292. protected function validateFailException($fail = true)
  293. {
  294. $this->failException = $fail;
  295. return $this;
  296. }
  297. /**
  298. * 验证数据
  299. * @access protected
  300. * @param array $data 数据
  301. * @param string|array $validate 验证器名或者验证规则数组
  302. * @param array $message 提示信息
  303. * @param bool $batch 是否批量验证
  304. * @param mixed $callback 回调方法(闭包)
  305. * @return array|string|true
  306. * @throws ValidateException
  307. */
  308. protected function validate($data, $validate, $message = [], $batch = false, $callback = null)
  309. {
  310. if (is_array($validate)) {
  311. $v = Loader::validate();
  312. $v->rule($validate);
  313. } else {
  314. // 支持场景
  315. if (strpos($validate, '.')) {
  316. list($validate, $scene) = explode('.', $validate);
  317. }
  318. $v = Loader::validate($validate);
  319. !empty($scene) && $v->scene($scene);
  320. }
  321. // 批量验证
  322. if ($batch || $this->batchValidate) {
  323. $v->batch(true);
  324. }
  325. // 设置错误信息
  326. if (is_array($message)) {
  327. $v->message($message);
  328. }
  329. // 使用回调验证
  330. if ($callback && is_callable($callback)) {
  331. call_user_func_array($callback, [$v, &$data]);
  332. }
  333. if (!$v->check($data)) {
  334. if ($this->failException) {
  335. throw new ValidateException($v->getError());
  336. }
  337. return $v->getError();
  338. }
  339. return true;
  340. }
  341. /**
  342. * 刷新Token
  343. */
  344. protected function token()
  345. {
  346. $token = $this->request->param('__token__');
  347. //验证Token
  348. if (!Validate::make()->check(['__token__' => $token], ['__token__' => 'require|token'])) {
  349. $this->error(__('Token verification error'), ['__token__' => $this->request->token()]);
  350. }
  351. //刷新Token
  352. $this->request->token();
  353. }
  354. }