Sfoglia il codice sorgente

feat(allowanddenyip): 添加 IP 重复检查功能

- 在 AddAllowAndDenyIps 和 EditAllowAndDenyIps 方法中增加 IP 重复检查
- 新增 GetIpCount 方法用于查询特定主机下特定 IP 的数量- 实现 IsExistIp 方法来判断 IP 是否已存在
fusu 3 settimane fa
parent
commit
01c0fe7dba

+ 9 - 0
internal/repository/allowanddenyip.go

@@ -12,6 +12,7 @@ type AllowAndDenyIpRepository interface {
 	EditAllowAndDenyIps(ctx context.Context, req model.AllowAndDenyIp) error
 	DeleteAllowAndDenyIps(ctx context.Context, id int64) error
 	GetAllowAndDenyIpsAllByHostId(ctx context.Context, hostId int64) ([]*model.AllowAndDenyIp, error)
+	GetIpCount(ctx context.Context,hostId int64,ip string) (int64, error)
 }
 
 func NewAllowAndDenyIpRepository(
@@ -64,4 +65,12 @@ func (r *allowAndDenyIpRepository) GetAllowAndDenyIpsAllByHostId(ctx context.Con
 		return nil, err
 	}
 	return res, nil
+}
+
+func (r *allowAndDenyIpRepository) GetIpCount(ctx context.Context,hostId int64,ip string) (int64, error) {
+	var count int64
+	if err := r.DB(ctx).Where("host_id = ?", hostId).Where("ip = ?", ip).Count(&count).Error; err != nil {
+		return 0, err
+	}
+	return count, nil
 }

+ 25 - 0
internal/service/allowanddenyip.go

@@ -2,6 +2,7 @@ package service
 
 import (
     "context"
+	"fmt"
 	v1 "github.com/go-nunu/nunu-layout-advanced/api/v1"
 	"github.com/go-nunu/nunu-layout-advanced/internal/model"
 	"github.com/go-nunu/nunu-layout-advanced/internal/repository"
@@ -53,6 +54,13 @@ func (s *allowAndDenyIpService) GetAllowAndDenyIpsAllByHostId(ctx context.Contex
 }
 
 func (s *allowAndDenyIpService) AddAllowAndDenyIps(ctx context.Context, req v1.AllowAndDenyIpRequest) error {
+	// 判断ip是否存在
+	err := s.IsExistIp(ctx, int64(req.HostId), req.Ip)
+	if err != nil {
+		return err
+	}
+
+
 	gatewayGroupIps, err := s.gatewayGroupIp.GetGateWayGroupIpByHostId(ctx, req.HostId)
 	if err != nil {
 		return err
@@ -77,6 +85,13 @@ func (s *allowAndDenyIpService) AddAllowAndDenyIps(ctx context.Context, req v1.A
 }
 
 func (s *allowAndDenyIpService) EditAllowAndDenyIps(ctx context.Context, req v1.AllowAndDenyIpRequest) error {
+	// 判断ip是否存在
+	err := s.IsExistIp(ctx, int64(req.HostId), req.Ip)
+	if err != nil {
+		return err
+	}
+
+
 	gatewayGroupIps, err := s.gatewayGroupIp.GetGateWayGroupIpByHostId(ctx, req.HostId)
 	if err != nil {
 		return err
@@ -139,3 +154,13 @@ func (s *allowAndDenyIpService) DeleteAllowAndDenyIps(ctx context.Context, req v
 	return nil
 }
 
+func (s *allowAndDenyIpService) IsExistIp(ctx context.Context, hostId int64, Ip string) error {
+	count, err := s.allowAndDenyIpRepository.GetIpCount(ctx, hostId, Ip)
+	if err != nil {
+		return err
+	}
+	if count > 0 {
+		return fmt.Errorf("ip已存在,请勿重复添加")
+	}
+	return nil
+}