Api.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395
  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. /**
  15. * API控制器基类
  16. */
  17. class Api
  18. {
  19. /**
  20. * @var Request Request 实例
  21. */
  22. protected $request;
  23. /**
  24. * @var bool 验证失败是否抛出异常
  25. */
  26. protected $failException = false;
  27. /**
  28. * @var bool 是否批量验证
  29. */
  30. protected $batchValidate = false;
  31. /**
  32. * @var array 前置操作方法列表
  33. */
  34. protected $beforeActionList = [];
  35. /**
  36. * 无需登录的方法,同时也就不需要鉴权了
  37. * @var array
  38. */
  39. protected $noNeedLogin = [];
  40. /**
  41. * 无需鉴权的方法,但需要登录
  42. * @var array
  43. */
  44. protected $noNeedRight = [];
  45. /**
  46. * 需要加锁的方法,所有用户,success自动解除
  47. * @var array
  48. */
  49. protected $lockAllUser = [];
  50. /**
  51. * 需要加锁的方法,只限制当前用户,success自动解除
  52. * @var array
  53. */
  54. protected $lockUserId = [];
  55. /**
  56. * @var null
  57. */
  58. protected $redis = null;
  59. /**
  60. * 权限Auth
  61. * @var Auth
  62. */
  63. protected $auth = null;
  64. /**
  65. * 默认响应输出类型,支持json/xml
  66. * @var string
  67. */
  68. protected $responseType = 'json';
  69. /**
  70. * 构造方法
  71. * @access public
  72. * @param Request $request Request 对象
  73. */
  74. public function __construct(Request $request = null)
  75. {
  76. $this->request = is_null($request) ? Request::instance() : $request;
  77. // 控制器初始化
  78. $this->_initialize();
  79. // 前置操作方法
  80. if ($this->beforeActionList) {
  81. foreach ($this->beforeActionList as $method => $options) {
  82. is_numeric($method) ?
  83. $this->beforeAction($options) :
  84. $this->beforeAction($method, $options);
  85. }
  86. }
  87. }
  88. /**
  89. * 初始化操作
  90. * @access protected
  91. */
  92. protected function _initialize()
  93. {
  94. //跨域请求检测
  95. // check_cors_request();
  96. // 检测IP是否允许
  97. check_ip_allowed();
  98. //移除HTML标签
  99. $this->request->filter('trim,strip_tags,htmlspecialchars');
  100. $this->auth = Auth::instance();
  101. $this->redis = $this->auth->redis;
  102. $modulename = $this->request->module();
  103. $controllername = Loader::parseName($this->request->controller());
  104. $actionname = strtolower($this->request->action());
  105. // token
  106. $token = $this->request->server('HTTP_TOKEN', $this->request->request('token', \think\Cookie::get('token')));
  107. $path = str_replace('.', '/', $controllername) . '/' . $actionname;
  108. // 设置当前请求的URI
  109. $this->auth->setRequestUri($path);
  110. // 检测是否需要验证登录
  111. if (!$this->auth->match($this->noNeedLogin)) {
  112. //初始化
  113. $this->auth->init($token);
  114. //检测是否登录
  115. if (!$this->auth->isLogin()) {
  116. throw new HttpResponseException(Response::create(['code' => '401', 'msg' => '请登录', 'data' => null], 'json', 200));
  117. // $this->error(__('Please login first'), null, 401);
  118. }
  119. // 判断是否需要验证权限
  120. if (!$this->auth->match($this->noNeedRight)) {
  121. // 判断控制器和方法判断是否有对应权限
  122. if (!$this->auth->check($path)) {
  123. throw new HttpResponseException(Response::create(['code' => '403', 'msg' => '权限不足', 'data' => null], 'json', 200));
  124. // $this->error(__('You have no permission'), null, 403);
  125. }
  126. }
  127. } else {
  128. // 如果有传递token才验证是否登录状态
  129. if ($token) {
  130. $this->auth->init($token);
  131. }
  132. }
  133. // 检查是否需要锁,全部用户
  134. if ($this->auth->match($this->lockAllUser) && !$this->auth->lock()) {
  135. $this->error('操作过快');
  136. }
  137. // 检查是否需要锁,当前用户
  138. if ($this->auth->isLogin() && $this->auth->match($this->lockUserId) && !$this->auth->lock($this->auth->id)) {
  139. $this->error('操作过快');
  140. }
  141. $upload = \app\common\model\Config::upload();
  142. // 上传信息配置后
  143. Hook::listen("upload_config_init", $upload);
  144. Config::set('upload', array_merge(Config::get('upload'), $upload));
  145. // 加载当前控制器语言包
  146. $this->loadlang($controllername);
  147. }
  148. /**
  149. * 加载语言文件
  150. * @param string $name
  151. */
  152. protected function loadlang($name)
  153. {
  154. $name = Loader::parseName($name);
  155. Lang::load(APP_PATH . $this->request->module() . '/lang/' . $this->request->langset() . '/' . str_replace('.', '/', $name) . '.php');
  156. }
  157. /**
  158. * 操作成功返回的数据
  159. * @param string $msg 提示信息
  160. * @param mixed $data 要返回的数据
  161. * @param int $code 错误码,默认为1
  162. * @param string $type 输出类型
  163. * @param array $header 发送的 Header 信息
  164. */
  165. protected function success($msg = '', $data = null, $code = 1, $type = null, array $header = [])
  166. {
  167. // 解锁全部用户
  168. $this->auth->match($this->lockAllUser) and $this->auth->unlock();
  169. // 解锁当前用户
  170. $this->auth->isLogin() and $this->auth->match($this->lockUserId) and $this->auth->unlock($this->auth->id);
  171. $this->result($msg, $data, $code, $type, $header);
  172. }
  173. /**
  174. * 操作失败返回的数据
  175. * @param string $msg 提示信息
  176. * @param mixed $data 要返回的数据
  177. * @param int $code 错误码,默认为0
  178. * @param string $type 输出类型
  179. * @param array $header 发送的 Header 信息
  180. */
  181. protected function error($msg = '', $data = null, $code = 0, $type = null, array $header = [])
  182. {
  183. $this->result($msg, $data, $code, $type, $header);
  184. }
  185. /**
  186. * 返回封装后的 API 数据到客户端
  187. * @access protected
  188. * @param mixed $msg 提示信息
  189. * @param mixed $data 要返回的数据
  190. * @param int $code 错误码,默认为0
  191. * @param string $type 输出类型,支持json/xml/jsonp
  192. * @param array $header 发送的 Header 信息
  193. * @return void
  194. * @throws HttpResponseException
  195. */
  196. protected function result($msg, $data = null, $code = 0, $type = null, array $header = [])
  197. {
  198. $result = [
  199. 'code' => $code,
  200. 'msg' => $msg,
  201. 'data' => $data,
  202. ];
  203. // 如果未设置类型则自动判断
  204. $type = $type ? $type : ($this->request->param(config('var_jsonp_handler')) ? 'jsonp' : $this->responseType);
  205. if (isset($header['statuscode'])) {
  206. $code = $header['statuscode'];
  207. unset($header['statuscode']);
  208. } else {
  209. //未设置状态码,根据code值判断
  210. $code = $code >= 1000 || $code < 200 ? 200 : $code;
  211. }
  212. $response = Response::create($result, $type, $code)->header($header);
  213. throw new HttpResponseException($response);
  214. }
  215. /**
  216. * 前置操作
  217. * @access protected
  218. * @param string $method 前置操作方法名
  219. * @param array $options 调用参数 ['only'=>[...]] 或者 ['except'=>[...]]
  220. * @return void
  221. */
  222. protected function beforeAction($method, $options = [])
  223. {
  224. if (isset($options['only'])) {
  225. if (is_string($options['only'])) {
  226. $options['only'] = explode(',', $options['only']);
  227. }
  228. if (!in_array($this->request->action(), $options['only'])) {
  229. return;
  230. }
  231. } elseif (isset($options['except'])) {
  232. if (is_string($options['except'])) {
  233. $options['except'] = explode(',', $options['except']);
  234. }
  235. if (in_array($this->request->action(), $options['except'])) {
  236. return;
  237. }
  238. }
  239. call_user_func([$this, $method]);
  240. }
  241. /**
  242. * 设置验证失败后是否抛出异常
  243. * @access protected
  244. * @param bool $fail 是否抛出异常
  245. * @return $this
  246. */
  247. protected function validateFailException($fail = true)
  248. {
  249. $this->failException = $fail;
  250. return $this;
  251. }
  252. /**
  253. * 验证数据
  254. * @access protected
  255. * @param array $data 数据
  256. * @param string|array $validate 验证器名或者验证规则数组
  257. * @param array $message 提示信息
  258. * @param bool $batch 是否批量验证
  259. * @param mixed $callback 回调方法(闭包)
  260. * @return array|string|true
  261. * @throws ValidateException
  262. */
  263. protected function validate($data, $validate, $message = [], $batch = false, $callback = null)
  264. {
  265. if (is_array($validate)) {
  266. $v = Loader::validate();
  267. $v->rule($validate);
  268. } else {
  269. // 支持场景
  270. if (strpos($validate, '.')) {
  271. list($validate, $scene) = explode('.', $validate);
  272. }
  273. $v = Loader::validate($validate);
  274. !empty($scene) && $v->scene($scene);
  275. }
  276. // 批量验证
  277. if ($batch || $this->batchValidate) {
  278. $v->batch(true);
  279. }
  280. // 设置错误信息
  281. if (is_array($message)) {
  282. $v->message($message);
  283. }
  284. // 使用回调验证
  285. if ($callback && is_callable($callback)) {
  286. call_user_func_array($callback, [$v, &$data]);
  287. }
  288. if (!$v->check($data)) {
  289. if ($this->failException) {
  290. throw new ValidateException($v->getError());
  291. }
  292. return $v->getError();
  293. }
  294. return true;
  295. }
  296. /**
  297. * 刷新Token
  298. */
  299. protected function token()
  300. {
  301. $token = $this->request->param('__token__');
  302. //验证Token
  303. if (!Validate::make()->check(['__token__' => $token], ['__token__' => 'require|token'])) {
  304. $this->error(__('Token verification error'), ['__token__' => $this->request->token()]);
  305. }
  306. //刷新Token
  307. $this->request->token();
  308. }
  309. /**
  310. * 上锁
  311. * @param string $key 琐标识
  312. * @param int $expire 锁定时长
  313. * @return bool
  314. * @author fuyelk <fuyelk@fuyelk.com>
  315. */
  316. public function lock($key = '', $expire = 3)
  317. {
  318. if (!$this->auth->lock($key, $expire)) {
  319. $this->error('操作过快');
  320. }
  321. return true;
  322. }
  323. /**
  324. * 解锁
  325. * @param string $key 琐标识
  326. * @author fuyelk <fuyelk@fuyelk.com>
  327. */
  328. public function unlock($key = '')
  329. {
  330. // 解锁指定用户
  331. if (!empty($key)) {
  332. return $this->auth->unlock($key);
  333. }
  334. // 解锁锁全部用户
  335. return $this->auth->unlock();
  336. }
  337. }