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