Api.php 8.7 KB

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