Api.php 9.3 KB

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