StaffApi.php 9.2 KB

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