Api.php 9.5 KB

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