| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970 |
- <?php
- declare (strict_types=1);
- namespace app\middleware;
- use app\service\IpWhiteListService;
- use app\model\UserModel;
- use think\Response;
- /**
- * IP白名单中间件
- * 用于在需要的控制器或方法中验证用户IP白名单
- */
- class IpWhiteListMiddleware
- {
- /**
- * 处理请求
- *
- * @param \think\Request $request
- * @param \Closure $next
- * @return Response
- */
- public function handle($request, \Closure $next)
- {
- // 获取当前用户登录信息
- $loginInfo = checkUserLogin();
-
- // 如果未登录,跳过IP检查(登录检查由其他中间件处理)
- if (!$loginInfo) {
- return $next($request);
- }
-
- // 获取用户信息
- $user = UserModel::where('user_id', $loginInfo['user_id'])
- ->where('merchant_id', $loginInfo['merchant_id'])
- ->find();
-
- if (!$user) {
- return json([
- 'state' => 0,
- 'code' => 401,
- 'message' => '用户信息不存在',
- 'data' => []
- ]);
- }
-
- // 获取客户端IP
- $clientIp = IpWhiteListService::getRealIp();
-
- // 检查IP白名单
- if (!IpWhiteListService::checkIpWhiteList($clientIp, $user->white_list_ip)) {
- // 记录IP限制访问日志
- trace("用户 {$user->user_name} 尝试从IP {$clientIp} 访问 {$request->pathinfo()},但不在白名单 {$user->white_list_ip} 中", 'warning');
-
- return json([
- 'state' => 0,
- 'code' => 403,
- 'message' => 'IP地址不在白名单中,禁止访问',
- 'data' => [
- 'client_ip' => $clientIp,
- 'white_list_ip' => $user->white_list_ip,
- 'requested_url' => $request->pathinfo()
- ]
- ]);
- }
-
- // IP检查通过,继续执行
- return $next($request);
- }
- }
|