Api.php 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304
  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->request('token') ?: $this->request->cookie('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'));
  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'));
  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 string $type 输出类型
  126. * @param array $header 发送的 Header 信息
  127. */
  128. protected function success($msg = '', $data = '', $type = 'json', array $header = [])
  129. {
  130. $this->result($data, 1, $msg, $type, $header);
  131. }
  132. /**
  133. * 操作失败返回的数据
  134. * @param string $msg 提示信息
  135. * @param mixed $data 要返回的数据
  136. * @param string $type 输出类型
  137. * @param array $header 发送的 Header 信息
  138. */
  139. protected function error($msg = '', $data = '', $type = 'json', array $header = [])
  140. {
  141. $this->result($data, 0, $msg, $type, $header);
  142. }
  143. /**
  144. * 返回封装后的 API 数据到客户端
  145. * @access protected
  146. * @param mixed $data 要返回的数据
  147. * @param int $code 返回的 code
  148. * @param mixed $msg 提示信息
  149. * @param string $type 返回数据格式
  150. * @param array $header 发送的 Header 信息
  151. * @return void
  152. * @throws HttpResponseException
  153. */
  154. protected function result($data, $code = 0, $msg = '', $type = '', array $header = [])
  155. {
  156. $result = [
  157. 'code' => $code,
  158. 'msg' => $msg,
  159. 'time' => Request::instance()->server('REQUEST_TIME'),
  160. 'data' => $data,
  161. ];
  162. $type = $type ?: $this->getResponseType();
  163. $response = Response::create($result, $type)->header($header);
  164. throw new HttpResponseException($response);
  165. }
  166. /**
  167. * 未找到请求的接口
  168. */
  169. public function _empty()
  170. {
  171. return $this->error('Api not found');
  172. }
  173. /**
  174. * 前置操作
  175. * @access protected
  176. * @param string $method 前置操作方法名
  177. * @param array $options 调用参数 ['only'=>[...]] 或者 ['except'=>[...]]
  178. * @return void
  179. */
  180. protected function beforeAction($method, $options = [])
  181. {
  182. if (isset($options['only']))
  183. {
  184. if (is_string($options['only']))
  185. {
  186. $options['only'] = explode(',', $options['only']);
  187. }
  188. if (!in_array($this->request->action(), $options['only']))
  189. {
  190. return;
  191. }
  192. }
  193. elseif (isset($options['except']))
  194. {
  195. if (is_string($options['except']))
  196. {
  197. $options['except'] = explode(',', $options['except']);
  198. }
  199. if (in_array($this->request->action(), $options['except']))
  200. {
  201. return;
  202. }
  203. }
  204. call_user_func([$this, $method]);
  205. }
  206. /**
  207. * 设置验证失败后是否抛出异常
  208. * @access protected
  209. * @param bool $fail 是否抛出异常
  210. * @return $this
  211. */
  212. protected function validateFailException($fail = true)
  213. {
  214. $this->failException = $fail;
  215. return $this;
  216. }
  217. /**
  218. * 验证数据
  219. * @access protected
  220. * @param array $data 数据
  221. * @param string|array $validate 验证器名或者验证规则数组
  222. * @param array $message 提示信息
  223. * @param bool $batch 是否批量验证
  224. * @param mixed $callback 回调方法(闭包)
  225. * @return array|string|true
  226. * @throws ValidateException
  227. */
  228. protected function validate($data, $validate, $message = [], $batch = false, $callback = null)
  229. {
  230. if (is_array($validate))
  231. {
  232. $v = Loader::validate();
  233. $v->rule($validate);
  234. }
  235. else
  236. {
  237. // 支持场景
  238. if (strpos($validate, '.'))
  239. {
  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. if (is_array($message))
  250. $v->message($message);
  251. // 使用回调验证
  252. if ($callback && is_callable($callback))
  253. {
  254. call_user_func_array($callback, [$v, &$data]);
  255. }
  256. if (!$v->check($data))
  257. {
  258. if ($this->failException)
  259. {
  260. throw new ValidateException($v->getError());
  261. }
  262. return $v->getError();
  263. }
  264. return true;
  265. }
  266. }