IpWhiteListMiddleware.php 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. <?php
  2. declare (strict_types=1);
  3. namespace app\middleware;
  4. use app\service\IpWhiteListService;
  5. use app\model\UserModel;
  6. use think\Response;
  7. /**
  8. * IP白名单中间件
  9. * 用于在需要的控制器或方法中验证用户IP白名单
  10. */
  11. class IpWhiteListMiddleware
  12. {
  13. /**
  14. * 处理请求
  15. *
  16. * @param \think\Request $request
  17. * @param \Closure $next
  18. * @return Response
  19. */
  20. public function handle($request, \Closure $next)
  21. {
  22. // 获取当前用户登录信息
  23. $loginInfo = checkUserLogin();
  24. // 如果未登录,跳过IP检查(登录检查由其他中间件处理)
  25. if (!$loginInfo) {
  26. return $next($request);
  27. }
  28. // 获取用户信息
  29. $user = UserModel::where('user_id', $loginInfo['user_id'])
  30. ->where('merchant_id', $loginInfo['merchant_id'])
  31. ->find();
  32. if (!$user) {
  33. return json([
  34. 'state' => 0,
  35. 'code' => 401,
  36. 'message' => '用户信息不存在',
  37. 'data' => []
  38. ]);
  39. }
  40. // 获取客户端IP
  41. $clientIp = getClientIp();
  42. // 检查IP白名单
  43. if (!IpWhiteListService::checkIpWhiteList($clientIp, $user->white_list_ip)) {
  44. return json([
  45. 'state' => 0,
  46. 'code' => 403,
  47. 'message' => 'IP地址不在白名单中,禁止访问',
  48. 'data' => [
  49. 'client_ip' => $clientIp,
  50. 'white_list_ip' => $user->white_list_ip,
  51. 'requested_url' => $request->pathinfo()
  52. ]
  53. ]);
  54. }
  55. // IP检查通过,继续执行
  56. return $next($request);
  57. }
  58. }