InspectionApi.php 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315
  1. <?php
  2. namespace app\common\controller;
  3. use app\common\library\InspectionAuth;
  4. use think\Request;
  5. use think\Lang;
  6. use think\Loader;
  7. use think\exception\HttpResponseException;
  8. use think\Response;
  9. use think\Config;
  10. use think\exception\ValidateException;
  11. use think\Hook;
  12. use think\Route;
  13. use think\Validate;
  14. use app\common\model\inspection\InspectionApplication;
  15. use app\common\Enum\StatusEnum;
  16. class InspectionApi
  17. {
  18. /**
  19. * @var Request Request 实例
  20. */
  21. protected $request;
  22. /**
  23. * @var bool 验证失败是否抛出异常
  24. */
  25. protected $failException = false;
  26. /**
  27. * @var bool 是否批量验证
  28. */
  29. protected $batchValidate = false;
  30. /**
  31. * @var array 前置操作方法列表
  32. */
  33. protected $beforeActionList = [];
  34. /**
  35. * 无需登录的方法,同时也就不需要鉴权了
  36. * @var array
  37. */
  38. protected $noNeedLogin = [];
  39. /**
  40. * 无需鉴权的方法,但需要登录
  41. * @var array
  42. */
  43. protected $noNeedRight = [];
  44. /**
  45. * 权限Auth
  46. * @var Auth
  47. */
  48. protected $auth = null;
  49. protected $application = null;
  50. protected $user = null;
  51. /**
  52. * 默认响应输出类型,支持json/xml
  53. * @var string
  54. */
  55. protected $responseType = 'json';
  56. public function __construct(Request $request = null)
  57. {
  58. $this->request = is_null($request) ? Request::instance() : $request;
  59. $this->_initialize();
  60. }
  61. protected function _initialize()
  62. {
  63. // 跨域检测
  64. check_cors_request();
  65. // IP 检查
  66. check_ip_allowed();
  67. // 过滤请求
  68. $this->request->filter('trim,strip_tags,htmlspecialchars');
  69. $this->auth = InspectionAuth::instance();
  70. // 检查是否需要登录
  71. $action = $this->request->action();
  72. if (!$this->auth->match($this->noNeedLogin)) {
  73. // token获取
  74. $token = $this->request->server('HTTP_TOKEN', $this->request->request('token', \think\Cookie::get('inspection_token')));
  75. // 初始化验货员身份
  76. if (!$this->auth->init($token)) {
  77. $this->error($this->auth->getError() ?: '请先登录', null, 401);
  78. }
  79. if (!$this->auth->isLogin()) {
  80. $this->error('请先登录', null, 401);
  81. }
  82. $this->application = $this->auth->getApplication();
  83. $this->user = $this->auth->getUser();
  84. // 检查审核状态
  85. if (!$this->application || $this->application->audit_status != InspectionApplication::AUDIT_STATUS_PASSED) {
  86. $this->error('验货员未通过审核', null);
  87. }
  88. // 检查启用状态
  89. if (!$this->application || $this->application->status != StatusEnum::ENABLED) {
  90. $this->error('验货员账号已被禁用', null);
  91. }
  92. // 检查供应商绑定
  93. if (!$this->application->supplier_id) {
  94. $this->error('未绑定供应商', null);
  95. }
  96. // 检查权限
  97. if (!$this->auth->match($this->noNeedRight)) {
  98. // 这里可以添加具体的权限检查逻辑
  99. // 暂时允许所有已登录的验货员访问
  100. }
  101. }
  102. // 加载语言包
  103. $controllername = strtolower($this->request->controller());
  104. $lang = $this->request->langset();
  105. $lang = preg_match("/^([a-zA-Z\-_]{2,10})$/i", $lang) ? $lang : 'zh-cn';
  106. Lang::load(ADDON_PATH . 'shop/lang/' . $lang . '/' . str_replace('.', '/', $controllername) . '.php');
  107. }
  108. /**
  109. * 加载语言文件
  110. * @param string $name
  111. */
  112. protected function loadlang($name)
  113. {
  114. $name = Loader::parseName($name);
  115. $name = preg_match("/^([a-zA-Z0-9_\.\/]+)\$/i", $name) ? $name : 'index';
  116. $lang = $this->request->langset();
  117. $lang = preg_match("/^([a-zA-Z\-_]{2,10})\$/i", $lang) ? $lang : 'zh-cn';
  118. Lang::load(APP_PATH . $this->request->module() . '/lang/' . $lang . '/' . str_replace('.', '/', $name) . '.php');
  119. }
  120. /**
  121. * 操作成功返回的数据
  122. * @param string $msg 提示信息
  123. * @param mixed $data 要返回的数据
  124. * @param int $code 错误码,默认为1
  125. * @param string $type 输出类型
  126. * @param array $header 发送的 Header 信息
  127. */
  128. protected function success($msg = '', $data = null, $code = 1, $type = null, array $header = [])
  129. {
  130. $this->result($msg, $data, $code, $type, $header);
  131. }
  132. /**
  133. * 操作失败返回的数据
  134. * @param string $msg 提示信息
  135. * @param mixed $data 要返回的数据
  136. * @param int $code 错误码,默认为0
  137. * @param string $type 输出类型
  138. * @param array $header 发送的 Header 信息
  139. */
  140. protected function error($msg = '', $data = null, $code = 0, $type = null, array $header = [])
  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 $type 输出类型,支持json/xml/jsonp
  151. * @param array $header 发送的 Header 信息
  152. * @return void
  153. * @throws HttpResponseException
  154. */
  155. protected function result($msg, $data = null, $code = 0, $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 ? : $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($method, $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. * @access protected
  204. * @param bool $fail 是否抛出异常
  205. * @return $this
  206. */
  207. protected function validateFailException($fail = true)
  208. {
  209. $this->failException = $fail;
  210. return $this;
  211. }
  212. /**
  213. * 验证数据
  214. * @access protected
  215. * @param array $data 数据
  216. * @param string|array $validate 验证器名或者验证规则数组
  217. * @param array $message 提示信息
  218. * @param bool $batch 是否批量验证
  219. * @param mixed $callback 回调方法(闭包)
  220. * @return array|string|true
  221. * @throws ValidateException
  222. */
  223. protected function validate($data, $validate, $message = [], $batch = false, $callback = null)
  224. {
  225. if (is_array($validate)) {
  226. $v = Loader::validate();
  227. $v->rule($validate);
  228. } else {
  229. // 支持场景
  230. if (strpos($validate, '.')) {
  231. list($validate, $scene) = explode('.', $validate);
  232. }
  233. $v = Loader::validate($validate);
  234. !empty($scene) && $v->scene($scene);
  235. }
  236. // 批量验证
  237. if ($batch || $this->batchValidate) {
  238. $v->batch(true);
  239. }
  240. // 设置错误信息
  241. if (is_array($message)) {
  242. $v->message($message);
  243. }
  244. // 使用回调验证
  245. if ($callback && is_callable($callback)) {
  246. call_user_func_array($callback, [$v, &$data]);
  247. }
  248. if (!$v->check($data)) {
  249. if ($this->failException) {
  250. throw new ValidateException($v->getError());
  251. }
  252. return $v->getError();
  253. }
  254. return true;
  255. }
  256. /**
  257. * 刷新Token
  258. */
  259. protected function token()
  260. {
  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. }