Api.php 10.0 KB

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