Api.php 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307
  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. * 构造方法
  48. * @access public
  49. * @param Request $request Request 对象
  50. */
  51. public function __construct(Request $request = null)
  52. {
  53. $this->request = is_null($request) ? Request::instance() : $request;
  54. // 控制器初始化
  55. $this->_initialize();
  56. // 前置操作方法
  57. if ($this->beforeActionList)
  58. {
  59. foreach ($this->beforeActionList as $method => $options)
  60. {
  61. is_numeric($method) ?
  62. $this->beforeAction($options) :
  63. $this->beforeAction($method, $options);
  64. }
  65. }
  66. }
  67. /**
  68. * 初始化操作
  69. * @access protected
  70. */
  71. protected function _initialize()
  72. {
  73. $this->auth = Auth::instance();
  74. $modulename = $this->request->module();
  75. $controllername = strtolower($this->request->controller());
  76. $actionname = strtolower($this->request->action());
  77. // token
  78. $token = $this->request->server('HTTP_TOKEN', $this->request->request('token', \think\Cookie::get('token')));
  79. $path = str_replace('.', '/', $controllername) . '/' . $actionname;
  80. // 设置当前请求的URI
  81. $this->auth->setRequestUri($path);
  82. // 检测是否需要验证登录
  83. if (!$this->auth->match($this->noNeedLogin))
  84. {
  85. //初始化
  86. $this->auth->init($token);
  87. //检测是否登录
  88. if (!$this->auth->isLogin())
  89. {
  90. $this->error(__('Please login first'), null, 401);
  91. }
  92. // 判断是否需要验证权限
  93. if (!$this->auth->match($this->noNeedRight))
  94. {
  95. // 判断控制器和方法判断是否有对应权限
  96. if (!$this->auth->check($path))
  97. {
  98. $this->error(__('You have no permission'), null, 403);
  99. }
  100. }
  101. }
  102. else
  103. {
  104. // 如果有传递token才验证是否登录状态
  105. if ($token)
  106. {
  107. $this->auth->init($token);
  108. }
  109. }
  110. // 加载当前控制器语言包
  111. $this->loadlang($controllername);
  112. }
  113. /**
  114. * 加载语言文件
  115. * @param string $name
  116. */
  117. protected function loadlang($name)
  118. {
  119. Lang::load(APP_PATH . $this->request->module() . '/lang/' . Lang::detect() . '/' . str_replace('.', '/', $name) . '.php');
  120. }
  121. /**
  122. * 操作成功返回的数据
  123. * @param string $msg 提示信息
  124. * @param mixed $data 要返回的数据
  125. * @param int $code 错误码,默认为1
  126. * @param string $type 输出类型
  127. * @param array $header 发送的 Header 信息
  128. */
  129. protected function success($msg = '', $data = null, $code = 1, $type = 'json', array $header = [])
  130. {
  131. $this->result($msg, $data, $code, $type, $header);
  132. }
  133. /**
  134. * 操作失败返回的数据
  135. * @param string $msg 提示信息
  136. * @param mixed $data 要返回的数据
  137. * @param int $code 错误码,默认为0
  138. * @param string $type 输出类型
  139. * @param array $header 发送的 Header 信息
  140. */
  141. protected function error($msg = '', $data = null, $code = 0, $type = 'json', array $header = [])
  142. {
  143. $this->result($msg, $data, $code, $type, $header);
  144. }
  145. /**
  146. * 返回封装后的 API 数据到客户端
  147. * @access protected
  148. * @param mixed $msg 提示信息
  149. * @param mixed $data 要返回的数据
  150. * @param int $code 返回的 code
  151. * @param string $type 返回数据格式
  152. * @param array $header 发送的 Header 信息
  153. * @return void
  154. * @throws HttpResponseException
  155. */
  156. protected function result($msg, $data = null, $code = 0, $type = 'json', array $header = [])
  157. {
  158. $result = [
  159. 'code' => $code,
  160. 'msg' => $msg,
  161. 'time' => Request::instance()->server('REQUEST_TIME'),
  162. 'data' => $data,
  163. ];
  164. $type = $type ?: $this->getResponseType();
  165. if (isset($header['statuscode']))
  166. {
  167. $code = $header['statuscode'];
  168. unset($header['statuscode']);
  169. }
  170. else
  171. {
  172. $code = $code >= 1000 ? 200 : $code;
  173. }
  174. $response = Response::create($result, $type, $code)->header($header);
  175. throw new HttpResponseException($response);
  176. }
  177. /**
  178. * 前置操作
  179. * @access protected
  180. * @param string $method 前置操作方法名
  181. * @param array $options 调用参数 ['only'=>[...]] 或者 ['except'=>[...]]
  182. * @return void
  183. */
  184. protected function beforeAction($method, $options = [])
  185. {
  186. if (isset($options['only']))
  187. {
  188. if (is_string($options['only']))
  189. {
  190. $options['only'] = explode(',', $options['only']);
  191. }
  192. if (!in_array($this->request->action(), $options['only']))
  193. {
  194. return;
  195. }
  196. }
  197. elseif (isset($options['except']))
  198. {
  199. if (is_string($options['except']))
  200. {
  201. $options['except'] = explode(',', $options['except']);
  202. }
  203. if (in_array($this->request->action(), $options['except']))
  204. {
  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. {
  236. $v = Loader::validate();
  237. $v->rule($validate);
  238. }
  239. else
  240. {
  241. // 支持场景
  242. if (strpos($validate, '.'))
  243. {
  244. list($validate, $scene) = explode('.', $validate);
  245. }
  246. $v = Loader::validate($validate);
  247. !empty($scene) && $v->scene($scene);
  248. }
  249. // 批量验证
  250. if ($batch || $this->batchValidate)
  251. $v->batch(true);
  252. // 设置错误信息
  253. if (is_array($message))
  254. $v->message($message);
  255. // 使用回调验证
  256. if ($callback && is_callable($callback))
  257. {
  258. call_user_func_array($callback, [$v, &$data]);
  259. }
  260. if (!$v->check($data))
  261. {
  262. if ($this->failException)
  263. {
  264. throw new ValidateException($v->getError());
  265. }
  266. return $v->getError();
  267. }
  268. return true;
  269. }
  270. }