Api.php 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351
  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\Paginator;
  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. * 每页条数
  58. * @var int
  59. */
  60. protected $pageSize = 10;
  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. if ($this->beforeActionList) {
  73. foreach ($this->beforeActionList as $method => $options) {
  74. is_numeric($method) ?
  75. $this->beforeAction($options) :
  76. $this->beforeAction($method, $options);
  77. }
  78. }
  79. }
  80. /**
  81. * 初始化操作
  82. * @access protected
  83. */
  84. protected function _initialize()
  85. {
  86. //跨域请求检测
  87. check_cors_request();
  88. // 检测IP是否允许
  89. check_ip_allowed();
  90. //移除HTML标签
  91. $this->request->filter('trim,strip_tags,htmlspecialchars');
  92. $this->auth = Auth::instance();
  93. $modulename = $this->request->module();
  94. $controllername = Loader::parseName($this->request->controller());
  95. $actionname = strtolower($this->request->action());
  96. // token
  97. $token = $this->request->server('HTTP_TOKEN', $this->request->request('token', \think\Cookie::get('token')));
  98. $path = str_replace('.', '/', $controllername) . '/' . $actionname;
  99. // 设置当前请求的URI
  100. $this->auth->setRequestUri($path);
  101. // 检测是否需要验证登录
  102. if (!$this->auth->match($this->noNeedLogin)) {
  103. //初始化
  104. $this->auth->init($token);
  105. //检测是否登录
  106. if (!$this->auth->isLogin()) {
  107. $this->error(__('Please login first'), null, 401);
  108. }
  109. // 判断是否需要验证权限
  110. if (!$this->auth->match($this->noNeedRight)) {
  111. // 判断控制器和方法判断是否有对应权限
  112. if (!$this->auth->check($path)) {
  113. $this->error(__('You have no permission'), null, 403);
  114. }
  115. }
  116. } else {
  117. // 如果有传递token才验证是否登录状态
  118. if ($token) {
  119. $this->auth->init($token);
  120. }
  121. }
  122. $upload = \app\common\model\Config::upload();
  123. // 上传信息配置后
  124. Hook::listen("upload_config_init", $upload);
  125. Config::set('upload', array_merge(Config::get('upload'), $upload));
  126. // 加载当前控制器语言包
  127. $this->loadlang($controllername);
  128. }
  129. /**
  130. * 加载语言文件
  131. * @param string $name
  132. */
  133. protected function loadlang($name)
  134. {
  135. $name = Loader::parseName($name);
  136. $name = preg_match("/^([a-zA-Z0-9_\.\/]+)\$/i", $name) ? $name : 'index';
  137. $lang = $this->request->langset();
  138. $lang = preg_match("/^([a-zA-Z\-_]{2,10})\$/i", $lang) ? $lang : 'zh-cn';
  139. Lang::load(APP_PATH . $this->request->module() . '/lang/' . $lang . '/' . str_replace('.', '/', $name) . '.php');
  140. }
  141. /**
  142. * 操作成功返回的数据
  143. * @param string $msg 提示信息
  144. * @param mixed $data 要返回的数据
  145. * @param int $code 错误码,默认为1
  146. * @param string $type 输出类型
  147. * @param array $header 发送的 Header 信息
  148. */
  149. protected function success($msg = '', $data = null, $code = 1, $type = null, array $header = [])
  150. {
  151. $this->result($msg, $data, $code, $type, $header);
  152. }
  153. /**
  154. * 操作失败返回的数据
  155. * @param string $msg 提示信息
  156. * @param mixed $data 要返回的数据
  157. * @param int $code 错误码,默认为0
  158. * @param string $type 输出类型
  159. * @param array $header 发送的 Header 信息
  160. */
  161. protected function error($msg = '', $data = null, $code = 0, $type = null, array $header = [])
  162. {
  163. $this->result($msg, $data, $code, $type, $header);
  164. }
  165. /**
  166. * 返回封装后的 API 数据到客户端
  167. * @access protected
  168. * @param mixed $msg 提示信息
  169. * @param mixed $data 要返回的数据
  170. * @param int $code 错误码,默认为0
  171. * @param string $type 输出类型,支持json/xml/jsonp
  172. * @param array $header 发送的 Header 信息
  173. * @return void
  174. * @throws HttpResponseException
  175. */
  176. protected function result($msg, $data = null, $code = 0, $type = null, array $header = [])
  177. {
  178. $result = [
  179. 'code' => $code,
  180. 'msg' => $msg,
  181. 'time' => Request::instance()->server('REQUEST_TIME'),
  182. 'data' => $data,
  183. ];
  184. // 如果未设置类型则自动判断
  185. $type = $type ? $type : ($this->request->param(config('var_jsonp_handler')) ? 'jsonp' : $this->responseType);
  186. if (isset($header['statuscode'])) {
  187. $code = $header['statuscode'];
  188. unset($header['statuscode']);
  189. } else {
  190. //未设置状态码,根据code值判断
  191. $code = $code >= 1000 || $code < 200 ? 200 : $code;
  192. }
  193. $response = Response::create($result, $type, $code)->header($header);
  194. throw new HttpResponseException($response);
  195. }
  196. /**
  197. * 前置操作
  198. * @access protected
  199. * @param string $method 前置操作方法名
  200. * @param array $options 调用参数 ['only'=>[...]] 或者 ['except'=>[...]]
  201. * @return void
  202. */
  203. protected function beforeAction($method, $options = [])
  204. {
  205. if (isset($options['only'])) {
  206. if (is_string($options['only'])) {
  207. $options['only'] = explode(',', $options['only']);
  208. }
  209. if (!in_array($this->request->action(), $options['only'])) {
  210. return;
  211. }
  212. } elseif (isset($options['except'])) {
  213. if (is_string($options['except'])) {
  214. $options['except'] = explode(',', $options['except']);
  215. }
  216. if (in_array($this->request->action(), $options['except'])) {
  217. return;
  218. }
  219. }
  220. call_user_func([$this, $method]);
  221. }
  222. /**
  223. * 设置验证失败后是否抛出异常
  224. * @access protected
  225. * @param bool $fail 是否抛出异常
  226. * @return $this
  227. */
  228. protected function validateFailException($fail = true)
  229. {
  230. $this->failException = $fail;
  231. return $this;
  232. }
  233. /**
  234. * 验证数据
  235. * @access protected
  236. * @param array $data 数据
  237. * @param string|array $validate 验证器名或者验证规则数组
  238. * @param array $message 提示信息
  239. * @param bool $batch 是否批量验证
  240. * @param mixed $callback 回调方法(闭包)
  241. * @return array|string|true
  242. * @throws ValidateException
  243. */
  244. protected function validate($data, $validate, $message = [], $batch = false, $callback = null)
  245. {
  246. if (is_array($validate)) {
  247. $v = Loader::validate();
  248. $v->rule($validate);
  249. } else {
  250. // 支持场景
  251. if (strpos($validate, '.')) {
  252. list($validate, $scene) = explode('.', $validate);
  253. }
  254. $v = Loader::validate($validate);
  255. !empty($scene) && $v->scene($scene);
  256. }
  257. // 批量验证
  258. if ($batch || $this->batchValidate) {
  259. $v->batch(true);
  260. }
  261. // 设置错误信息
  262. if (is_array($message)) {
  263. $v->message($message);
  264. }
  265. // 使用回调验证
  266. if ($callback && is_callable($callback)) {
  267. call_user_func_array($callback, [$v, &$data]);
  268. }
  269. if (!$v->check($data)) {
  270. if ($this->failException) {
  271. throw new ValidateException($v->getError());
  272. }
  273. return $v->getError();
  274. }
  275. return true;
  276. }
  277. /**
  278. * 刷新Token
  279. */
  280. protected function token()
  281. {
  282. $token = $this->request->param('__token__');
  283. //验证Token
  284. if (!Validate::make()->check(['__token__' => $token], ['__token__' => 'require|token'])) {
  285. $this->error(__('Token verification error'), ['__token__' => $this->request->token()]);
  286. }
  287. //刷新Token
  288. $this->request->token();
  289. }
  290. /**
  291. * 构造分页的相应
  292. * @param Paginator $paginator
  293. * @return array
  294. */
  295. protected function buildResp(int $total, int $currentPage, array $rows): array
  296. {
  297. return [
  298. 'total' => $total,
  299. 'current_page' => $currentPage,
  300. 'rows' => $rows,
  301. ];
  302. }
  303. }