Api.php 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314
  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. // 加载当前控制器语言包
  116. $this->loadlang($controllername);
  117. }
  118. /**
  119. * 加载语言文件
  120. * @param string $name
  121. */
  122. protected function loadlang($name)
  123. {
  124. Lang::load(APP_PATH . $this->request->module() . '/lang/' . Lang::detect() . '/' . str_replace('.', '/', $name) . '.php');
  125. }
  126. /**
  127. * 操作成功返回的数据
  128. * @param string $msg 提示信息
  129. * @param mixed $data 要返回的数据
  130. * @param int $code 错误码,默认为1
  131. * @param string $type 输出类型
  132. * @param array $header 发送的 Header 信息
  133. */
  134. protected function success($msg = '', $data = null, $code = 1, $type = null, array $header = [])
  135. {
  136. $this->result($msg, $data, $code, $type, $header);
  137. }
  138. /**
  139. * 操作失败返回的数据
  140. * @param string $msg 提示信息
  141. * @param mixed $data 要返回的数据
  142. * @param int $code 错误码,默认为0
  143. * @param string $type 输出类型
  144. * @param array $header 发送的 Header 信息
  145. */
  146. protected function error($msg = '', $data = null, $code = 0, $type = null, array $header = [])
  147. {
  148. $this->result($msg, $data, $code, $type, $header);
  149. }
  150. /**
  151. * 返回封装后的 API 数据到客户端
  152. * @access protected
  153. * @param mixed $msg 提示信息
  154. * @param mixed $data 要返回的数据
  155. * @param int $code 错误码,默认为0
  156. * @param string $type 输出类型,支持json/xml/jsonp
  157. * @param array $header 发送的 Header 信息
  158. * @return void
  159. * @throws HttpResponseException
  160. */
  161. protected function result($msg, $data = null, $code = 0, $type = null, array $header = [])
  162. {
  163. $result = [
  164. 'code' => $code,
  165. 'msg' => $msg,
  166. 'time' => Request::instance()->server('REQUEST_TIME'),
  167. 'data' => $data,
  168. ];
  169. // 如果未设置类型则自动判断
  170. $type = $type ? $type : ($this->request->param(config('var_jsonp_handler')) ? 'jsonp' : $this->responseType);
  171. if (isset($header['statuscode']))
  172. {
  173. $code = $header['statuscode'];
  174. unset($header['statuscode']);
  175. }
  176. else
  177. {
  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. {
  195. if (is_string($options['only']))
  196. {
  197. $options['only'] = explode(',', $options['only']);
  198. }
  199. if (!in_array($this->request->action(), $options['only']))
  200. {
  201. return;
  202. }
  203. }
  204. elseif (isset($options['except']))
  205. {
  206. if (is_string($options['except']))
  207. {
  208. $options['except'] = explode(',', $options['except']);
  209. }
  210. if (in_array($this->request->action(), $options['except']))
  211. {
  212. return;
  213. }
  214. }
  215. call_user_func([$this, $method]);
  216. }
  217. /**
  218. * 设置验证失败后是否抛出异常
  219. * @access protected
  220. * @param bool $fail 是否抛出异常
  221. * @return $this
  222. */
  223. protected function validateFailException($fail = true)
  224. {
  225. $this->failException = $fail;
  226. return $this;
  227. }
  228. /**
  229. * 验证数据
  230. * @access protected
  231. * @param array $data 数据
  232. * @param string|array $validate 验证器名或者验证规则数组
  233. * @param array $message 提示信息
  234. * @param bool $batch 是否批量验证
  235. * @param mixed $callback 回调方法(闭包)
  236. * @return array|string|true
  237. * @throws ValidateException
  238. */
  239. protected function validate($data, $validate, $message = [], $batch = false, $callback = null)
  240. {
  241. if (is_array($validate))
  242. {
  243. $v = Loader::validate();
  244. $v->rule($validate);
  245. }
  246. else
  247. {
  248. // 支持场景
  249. if (strpos($validate, '.'))
  250. {
  251. list($validate, $scene) = explode('.', $validate);
  252. }
  253. $v = Loader::validate($validate);
  254. !empty($scene) && $v->scene($scene);
  255. }
  256. // 批量验证
  257. if ($batch || $this->batchValidate)
  258. $v->batch(true);
  259. // 设置错误信息
  260. if (is_array($message))
  261. $v->message($message);
  262. // 使用回调验证
  263. if ($callback && is_callable($callback))
  264. {
  265. call_user_func_array($callback, [$v, &$data]);
  266. }
  267. if (!$v->check($data))
  268. {
  269. if ($this->failException)
  270. {
  271. throw new ValidateException($v->getError());
  272. }
  273. return $v->getError();
  274. }
  275. return true;
  276. }
  277. }