Api.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371
  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 = false;
  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. public $page = 1;
  56. public $limit = 10;
  57. /**
  58. * 构造方法
  59. * @access public
  60. * @param Request $request Request 对象
  61. */
  62. public function __construct(Request $request = null)
  63. {
  64. $this->request = is_null($request) ? Request::instance() : $request;
  65. $this->page = input('page',1);
  66. // 控制器初始化
  67. $this->_initialize();
  68. //日志
  69. $this->request_log();
  70. // 前置操作方法
  71. if ($this->beforeActionList) {
  72. foreach ($this->beforeActionList as $method => $options) {
  73. is_numeric($method) ?
  74. $this->beforeAction($options) :
  75. $this->beforeAction($method, $options);
  76. }
  77. }
  78. }
  79. /**
  80. * 初始化操作
  81. * @access protected
  82. */
  83. protected function _initialize()
  84. {
  85. //跨域请求检测
  86. check_cors_request();
  87. // 检测IP是否允许
  88. check_ip_allowed();
  89. //移除HTML标签
  90. $this->request->filter('trim,strip_tags,htmlspecialchars');
  91. $this->auth = Auth::instance();
  92. $modulename = $this->request->module();
  93. $controllername = Loader::parseName($this->request->controller());
  94. $actionname = strtolower($this->request->action());
  95. // token
  96. $token = $this->request->server('HTTP_TOKEN', $this->request->request('token', \think\Cookie::get('token')));
  97. $path = str_replace('.', '/', $controllername) . '/' . $actionname;
  98. // 设置当前请求的URI
  99. $this->auth->setRequestUri($path);
  100. // 检测是否需要验证登录
  101. if (!$this->auth->match($this->noNeedLogin)) {
  102. //初始化
  103. $this->auth->init($token);
  104. //检测是否登录
  105. if (!$this->auth->isLogin()) {
  106. $this->error(__('Please login first'), null, 401);
  107. }
  108. // 判断是否需要验证权限
  109. if (!$this->auth->match($this->noNeedRight)) {
  110. // 判断控制器和方法判断是否有对应权限
  111. if (!$this->auth->check($path)) {
  112. $this->error(__('You have no permission'), null, 403);
  113. }
  114. }
  115. } else {
  116. // 如果有传递token才验证是否登录状态
  117. if ($token) {
  118. $this->auth->init($token);
  119. }
  120. }
  121. $upload = \app\common\model\Config::upload();
  122. // 上传信息配置后
  123. Hook::listen("upload_config_init", $upload);
  124. Config::set('upload', array_merge(Config::get('upload'), $upload));
  125. // 加载当前控制器语言包
  126. $this->loadlang($controllername);
  127. }
  128. /**
  129. * 加载语言文件
  130. * @param string $name
  131. */
  132. protected function loadlang($name)
  133. {
  134. $name = Loader::parseName($name);
  135. Lang::load(APP_PATH . $this->request->module() . '/lang/' . $this->request->langset() . '/' . str_replace('.', '/', $name) . '.php');
  136. }
  137. /**
  138. * 操作成功返回的数据
  139. * @param string $msg 提示信息
  140. * @param mixed $data 要返回的数据
  141. * @param int $code 错误码,默认为1
  142. * @param string $type 输出类型
  143. * @param array $header 发送的 Header 信息
  144. */
  145. protected function success($msg = '', $data = null, $code = 1, $type = null, array $header = [])
  146. {
  147. if(empty($msg)){
  148. $msg = '操作成功';
  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. if(empty($msg)){
  163. $msg = __('Invalid parameters');
  164. }
  165. $this->result($msg, $data, $code, $type, $header);
  166. }
  167. /**
  168. * 返回封装后的 API 数据到客户端
  169. * @access protected
  170. * @param mixed $msg 提示信息
  171. * @param mixed $data 要返回的数据
  172. * @param int $code 错误码,默认为0
  173. * @param string $type 输出类型,支持json/xml/jsonp
  174. * @param array $header 发送的 Header 信息
  175. * @return void
  176. * @throws HttpResponseException
  177. */
  178. protected function result($msg, $data = null, $code = 0, $type = null, array $header = [])
  179. {
  180. $result = [
  181. 'code' => $code,
  182. 'msg' => $msg,
  183. 'time' => Request::instance()->server('REQUEST_TIME'),
  184. 'data' => $data,
  185. ];
  186. //日志
  187. $this->request_log_update($result);
  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. /**
  282. * 刷新Token
  283. */
  284. protected function token()
  285. {
  286. $token = $this->request->param('__token__');
  287. //验证Token
  288. if (!Validate::make()->check(['__token__' => $token], ['__token__' => 'require|token'])) {
  289. $this->error(__('Token verification error'), ['__token__' => $this->request->token()]);
  290. }
  291. //刷新Token
  292. $this->request->token();
  293. }
  294. /*
  295. * api 请求日志
  296. * */
  297. protected function request_log(){
  298. //api_request_log
  299. $modulename = $this->request->module();
  300. $controllername = $this->request->controller();
  301. $actionname = $this->request->action();
  302. $data = [
  303. 'uid' => $this->auth->id,
  304. 'api' => $modulename.'/'.$controllername.'/'.$actionname,
  305. 'params' => json_encode($this->request->request()),
  306. 'addtime' => time(),
  307. 'adddatetime' => date('Y-m-d H:i:s'),
  308. 'ip' => request()->ip(),
  309. ];
  310. $request_id = db('api_request_log')->insertGetId($data);
  311. defined('API_REQUEST_ID') or define('API_REQUEST_ID', $request_id);
  312. }
  313. protected function request_log_update($log_result){
  314. if(defined('API_REQUEST_ID')) { //记录app正常返回结果
  315. if(strlen(json_encode($log_result['data'])) > 10000) {
  316. $log_result['data'] = '数据太多,不记录';
  317. }
  318. db('api_request_log')->where('id',API_REQUEST_ID)->update(['result'=>json_encode($log_result)]);
  319. }
  320. }
  321. }