Api.php 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247
  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\Paginator;
  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 array 前置操作方法列表
  26. */
  27. protected array $beforeActionList = [];
  28. /**
  29. * 无需登录的方法,同时也就不需要鉴权了
  30. * @var array
  31. */
  32. protected array $noNeedLogin = [];
  33. /**
  34. * 权限Auth
  35. * @var Auth
  36. */
  37. protected Auth $auth;
  38. /**
  39. * 默认响应输出类型,支持json/xml
  40. * @var string
  41. */
  42. protected string $responseType = 'json';
  43. /**
  44. * 每页条数
  45. * @var int
  46. */
  47. protected int $pageSize = 10;
  48. /**
  49. * 构造方法
  50. * @param Request|null $request
  51. */
  52. public function __construct(Request $request = null)
  53. {
  54. $this->request = is_null($request) ? Request::instance() : $request;
  55. // 控制器初始化
  56. $this->_initialize();
  57. // 前置操作方法
  58. if ($this->beforeActionList) {
  59. foreach ($this->beforeActionList as $method => $options) {
  60. is_numeric($method) ?
  61. $this->beforeAction($options) :
  62. $this->beforeAction($method, $options);
  63. }
  64. }
  65. }
  66. /**
  67. * 初始化操作
  68. * @access protected
  69. */
  70. protected function _initialize()
  71. {
  72. //跨域请求检测
  73. check_cors_request();
  74. // 检测IP是否允许
  75. check_ip_allowed();
  76. //移除HTML标签
  77. $this->request->filter('trim,strip_tags,htmlspecialchars');
  78. $this->auth = Auth::instance();
  79. $controllername = Loader::parseName($this->request->controller());
  80. $actionname = strtolower($this->request->action());
  81. // 请求头里的加密过的token
  82. $token = $this->request->header("Token", "");
  83. $path = str_replace('.', '/', $controllername) . '/' . $actionname;
  84. // 设置当前请求的URI
  85. $this->auth->setRequestUri($path);
  86. // 检测是否需要验证登录
  87. if (!$this->auth->match($this->noNeedLogin)) {
  88. //初始化
  89. $this->auth->init($token);
  90. //检测是否登录
  91. if (!$this->auth->isLogin()) {
  92. $this->error(__('Please login first'), null,14999); // 未登录时,返回特定的code
  93. }
  94. }
  95. $upload = \app\common\model\Config::upload();
  96. // 上传信息配置后
  97. Hook::listen("upload_config_init", $upload);
  98. Config::set('upload', array_merge(Config::get('upload'), $upload));
  99. // 加载当前控制器语言包
  100. $this->loadlang($controllername);
  101. }
  102. /**
  103. * 加载语言文件
  104. * @param string $name
  105. */
  106. protected function loadlang($name)
  107. {
  108. $name = Loader::parseName($name);
  109. $name = preg_match("/^([a-zA-Z0-9_\.\/]+)\$/i", $name) ? $name : 'index';
  110. $lang = $this->request->langset();
  111. $lang = preg_match("/^([a-zA-Z\-_]{2,10})\$/i", $lang) ? $lang : 'zh-cn';
  112. Lang::load(APP_PATH . $this->request->module() . '/lang/' . $lang . '/' . str_replace('.', '/', $name) . '.php');
  113. }
  114. /**
  115. * 操作成功返回的数据
  116. * @param string $msg 提示信息
  117. * @param mixed $data 要返回的数据
  118. * @param int $code 错误码,默认为1
  119. * @param string|null $type 输出类型
  120. * @param array $header 发送的 Header 信息
  121. */
  122. protected function success(string $msg = '', $data = null, int $code = 200, string $type = null, array $header = [])
  123. {
  124. if (empty($msg)) {
  125. $msg = "操作成功";
  126. }
  127. $this->result($msg, $data, $code, $type, $header);
  128. }
  129. /**
  130. * 操作失败返回的数据
  131. * @param string $msg 提示信息
  132. * @param mixed $data 要返回的数据
  133. * @param int $code 错误码,默认为0
  134. * @param string|null $type 输出类型
  135. * @param array $header 发送的 Header 信息
  136. */
  137. protected function error(string $msg = '', $data = null, int $code = 15000, string $type = null, array $header = [])
  138. {
  139. if (empty($msg)) {
  140. $msg = "操作失败";
  141. }
  142. $this->result($msg, $data, $code, $type, $header);
  143. }
  144. /**
  145. * 返回封装后的 API 数据到客户端
  146. * @access protected
  147. * @param mixed $msg 提示信息
  148. * @param mixed $data 要返回的数据
  149. * @param int $code 错误码,默认为0
  150. * @param string|null $type 输出类型,支持json/xml/jsonp
  151. * @param array $header 发送的 Header 信息
  152. * @return void
  153. * @throws HttpResponseException
  154. */
  155. protected function result($msg, $data = null, int $code = 0, string $type = null, array $header = [])
  156. {
  157. $result = [
  158. 'code' => $code,
  159. 'msg' => $msg,
  160. 'time' => Request::instance()->server('REQUEST_TIME'),
  161. 'data' => $data,
  162. ];
  163. // 如果未设置类型则自动判断
  164. $type = $type ? $type : ($this->request->param(config('var_jsonp_handler')) ? 'jsonp' : $this->responseType);
  165. if (isset($header['statuscode'])) {
  166. $code = $header['statuscode'];
  167. unset($header['statuscode']);
  168. } else {
  169. //未设置状态码,根据code值判断
  170. $code = $code >= 1000 || $code < 200 ? 200 : $code;
  171. }
  172. $response = Response::create($result, $type, $code)->header($header);
  173. throw new HttpResponseException($response);
  174. }
  175. /**
  176. * 前置操作
  177. * @access protected
  178. * @param string $method 前置操作方法名
  179. * @param array $options 调用参数 ['only'=>[...]] 或者 ['except'=>[...]]
  180. * @return void
  181. */
  182. protected function beforeAction(string $method, array $options = [])
  183. {
  184. if (isset($options['only'])) {
  185. if (is_string($options['only'])) {
  186. $options['only'] = explode(',', $options['only']);
  187. }
  188. if (!in_array($this->request->action(), $options['only'])) {
  189. return;
  190. }
  191. } elseif (isset($options['except'])) {
  192. if (is_string($options['except'])) {
  193. $options['except'] = explode(',', $options['except']);
  194. }
  195. if (in_array($this->request->action(), $options['except'])) {
  196. return;
  197. }
  198. }
  199. call_user_func([$this, $method]);
  200. }
  201. /**
  202. * 构造分页的相应
  203. * @param Paginator $paginator
  204. * @return array
  205. */
  206. protected function buildResp(int $total, int $currentPage, array $rows): array
  207. {
  208. return [
  209. 'total' => $total,
  210. 'current_page' => $currentPage,
  211. 'rows' => $rows,
  212. ];
  213. }
  214. }