Api.php 10 KB

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