Api.php 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // |
  4. // +----------------------------------------------------------------------
  5. // |
  6. // +----------------------------------------------------------------------
  7. // |
  8. // +----------------------------------------------------------------------
  9. // |
  10. // +----------------------------------------------------------------------
  11. // | Original reference: https://gitee.com/karson/fastadmin
  12. // +----------------------------------------------------------------------
  13. // +----------------------------------------------------------------------
  14. // | API控制器基类
  15. // +----------------------------------------------------------------------
  16. namespace app\common\controller;
  17. use app\common\library\Auth;
  18. use think\App;
  19. use think\exception\HttpResponseException;
  20. use think\exception\ValidateException;
  21. use think\facade\Config;
  22. use think\facade\Event;
  23. use think\Response;
  24. use think\Validate;
  25. class Api
  26. {
  27. /**
  28. * @var Request Request 实例
  29. */
  30. protected $request;
  31. /**
  32. * 应用实例
  33. * @var \think\App
  34. */
  35. protected $app;
  36. /**
  37. * @var bool 验证失败是否抛出异常
  38. */
  39. protected $failException = true;
  40. /**
  41. * 是否批量验证
  42. * @var bool
  43. */
  44. protected $batchValidate = false;
  45. /**
  46. * @var array 前置操作方法列表
  47. */
  48. protected $beforeActionList = [];
  49. /**
  50. * 无需登录的方法,同时也就不需要鉴权了
  51. * @var array
  52. */
  53. protected $noNeedLogin = [];
  54. /**
  55. * 无需鉴权的方法,但需要登录
  56. * @var array
  57. */
  58. protected $noNeedRight = [];
  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(App $app)
  75. {
  76. $this->app = $app;
  77. $this->request = is_null($this->app->request) ? \think\facade\Request::instance() : $this->app->request;
  78. // 控制器初始化
  79. $this->initialize();
  80. // 前置操作方法
  81. if ($this->beforeActionList) {
  82. foreach ($this->beforeActionList as $method => $options) {
  83. is_numeric($method) ?
  84. $this->beforeAction($options) :
  85. $this->beforeAction($method, $options);
  86. }
  87. }
  88. }
  89. /**
  90. * 初始化操作
  91. * @access protected
  92. */
  93. protected function initialize()
  94. {
  95. //移除HTML标签
  96. $this->request->filter('trim,strip_tags,htmlspecialchars');
  97. $this->auth = Auth::instance();
  98. $modulename = $this->app->http->getName();
  99. $controller = preg_replace_callback('/\.[A-Z]/', function ($d) {
  100. return strtolower($d[0]);
  101. }, $this->request->controller());
  102. $controllername = parse_name($controller);
  103. $actionname = strtolower($this->request->action());
  104. // token
  105. $token = $this->request->server('HTTP_TOKEN', (string) $this->request->request('token', \think\facade\Cookie::get('token')));
  106. $path = str_replace('.', '/', $controllername) . '/' . $actionname;
  107. // 设置当前请求的URI
  108. $this->auth->setRequestUri($path);
  109. // 检测是否需要验证登录
  110. if (!$this->auth->match($this->noNeedLogin)) {
  111. //初始化
  112. $this->auth->init($token);
  113. //检测是否登录
  114. if (!$this->auth->isLogin()) {
  115. $this->error('请先登陆', null, 401);
  116. }
  117. // 判断是否需要验证权限
  118. if (!$this->auth->match($this->noNeedRight)) {
  119. // 判断控制器和方法判断是否有对应权限
  120. /*if (!$this->auth->check($path)) {
  121. $this->error(__('You have no permission'), null, 403);
  122. }*/
  123. }
  124. } else {
  125. // 如果有传递token才验证是否登录状态
  126. if ($token) {
  127. $this->auth->init($token);
  128. }
  129. }
  130. // 上传信息配置后
  131. $upload = array_merge(\app\common\model\Config::upload(), ...Event::trigger("upload_config_init"));
  132. Config::set(array_merge(Config::get('upload'), $upload), 'upload');
  133. }
  134. /**
  135. * 操作成功返回的数据
  136. * @param string $msg 提示信息
  137. * @param mixed $data 要返回的数据
  138. * @param int $code 错误码,默认为1
  139. * @param string $type 输出类型
  140. * @param array $header 发送的 Header 信息
  141. */
  142. protected function success($msg = '', $data = null, $code = 1, $type = null, array $header = [])
  143. {
  144. $this->result($msg, $data, $code, $type, $header);
  145. }
  146. /**
  147. * 操作失败返回的数据
  148. * @param string $msg 提示信息
  149. * @param mixed $data 要返回的数据
  150. * @param int $code 错误码,默认为0
  151. * @param string $type 输出类型
  152. * @param array $header 发送的 Header 信息
  153. */
  154. protected function error($msg = '', $data = null, $code = 0, $type = null, array $header = [])
  155. {
  156. $this->result($msg, $data, $code, $type, $header);
  157. }
  158. /**
  159. * 返回封装后的 API 数据到客户端
  160. * @access protected
  161. * @param mixed $msg 提示信息
  162. * @param mixed $data 要返回的数据
  163. * @param int $code 错误码,默认为0
  164. * @param string $type 输出类型,支持json/xml/jsonp
  165. * @param array $header 发送的 Header 信息
  166. * @return void
  167. * @throws HttpResponseException
  168. */
  169. protected function result($msg, $data = null, $code = 0, $type = null, array $header = [])
  170. {
  171. $result = [
  172. 'code' => $code,
  173. 'msg' => $msg,
  174. 'time' => $this->request->server('REQUEST_TIME'),
  175. 'data' => $data,
  176. ];
  177. // 如果未设置类型则自动判断
  178. $type = $type ?: $this->responseType;
  179. if (isset($header['statuscode'])) {
  180. $code = $header['statuscode'];
  181. unset($header['statuscode']);
  182. } else {
  183. //未设置状态码,根据code值判断
  184. $code = $code >= 1000 || $code < 200 ? 200 : $code;
  185. }
  186. $response = Response::create($result, $type, $code)->header($header);
  187. throw new HttpResponseException($response);
  188. }
  189. /**
  190. * 前置操作
  191. * @access protected
  192. * @param string $method 前置操作方法名
  193. * @param array $options 调用参数 ['only'=>[...]] 或者 ['except'=>[...]]
  194. * @return void
  195. */
  196. protected function beforeAction($method, $options = [])
  197. {
  198. if (isset($options['only'])) {
  199. if (is_string($options['only'])) {
  200. $options['only'] = explode(',', $options['only']);
  201. }
  202. if (!in_array($this->request->action(), $options['only'])) {
  203. return;
  204. }
  205. } elseif (isset($options['except'])) {
  206. if (is_string($options['except'])) {
  207. $options['except'] = explode(',', $options['except']);
  208. }
  209. if (in_array($this->request->action(), $options['except'])) {
  210. return;
  211. }
  212. }
  213. call_user_func([$this, $method]);
  214. }
  215. /**
  216. * 设置验证失败后是否抛出异常
  217. * @access protected
  218. * @param bool $fail 是否抛出异常
  219. * @return $this
  220. */
  221. protected function validateFailException($fail = true)
  222. {
  223. $this->failException = $fail;
  224. return $this;
  225. }
  226. /**
  227. * 验证数据
  228. * @access protected
  229. * @param array $data 数据
  230. * @param string|array $validate 验证器名或者验证规则数组
  231. * @param array $message 提示信息
  232. * @param bool $batch 是否批量验证
  233. * @return array|string|true
  234. * @throws ValidateException
  235. */
  236. protected function validate(array $data, string | array $validate, array $message = [], bool $batch = false)
  237. {
  238. if (is_array($validate)) {
  239. $v = new Validate();
  240. $v->rule($validate);
  241. } else {
  242. if (strpos($validate, '.')) {
  243. // 支持场景
  244. [$validate, $scene] = explode('.', $validate);
  245. }
  246. $class = false !== strpos($validate, '\\') ? $validate : $this->app->parseClass('validate', $validate);
  247. $v = new $class();
  248. if (!empty($scene)) {
  249. $v->scene($scene);
  250. }
  251. }
  252. $v->message($message);
  253. // 是否批量验证
  254. if ($batch || $this->batchValidate) {
  255. $v->batch(true);
  256. }
  257. return $v->failException($this->failException)->check($data);
  258. }
  259. //刷新Token
  260. protected function token()
  261. {
  262. $check = $this->request->checkToken('__token__');
  263. // 刷新token
  264. $token = $this->request->buildToken();
  265. if ($this->request->isAjax()) {
  266. header('__token__: ' . $token);
  267. }
  268. if (false === $check) {
  269. $this->error('令牌错误!', '', ['__token__' => $token]);
  270. }
  271. }
  272. }