Api.php 10 KB

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