Api.php 8.6 KB

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