StaffApi.php 10.0 KB

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