You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

324 lines
9.6 KiB

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