Browse Source

怎么ip 白名单功能

zp 9 tháng trước cách đây
mục cha
commit
c442cd796b

+ 14 - 0
game/game_cluster/internal/mdb/models/whitelist.go

@@ -0,0 +1,14 @@
+package models
+
+// Whitelist ip白名单
+type Whitelist struct {
+	Id        string `gorm:"column:id;primaryKey" json:"id" bson:"_id"`
+	IP        string `json:"ip" bson:"ip"` // Ip
+	Desc      string `gorm:"column:desc;comment:描述" json:"desc" bson:"desc"`
+	CreatedAt uint64 `gorm:"column:created_at;autoCreateTime" json:"created_at" bson:"created_at"`
+	DeletedAt uint64 `gorm:"column:deleted_at;" json:"deleted_at" bson:"deleted_at"`
+}
+
+func (w *Whitelist) TableName() string {
+	return "whitelist"
+}

+ 104 - 0
game/game_cluster/nodes/webadmin/controller/whitelist.go

@@ -0,0 +1,104 @@
+package controller
+
+import (
+	"github.com/gin-gonic/gin"
+	"github.com/mhaya/game/game_cluster/nodes/webadmin/entity"
+	"github.com/mhaya/game/game_cluster/nodes/webadmin/service"
+)
+
+type Whitelist struct {
+}
+
+func NewWhitelist() *Whitelist {
+	return &Whitelist{}
+}
+
+// GetWhitelist 获取白名单
+// @Summary 获取白名单
+// @Description 获取白名单
+// @Tags 白名单
+// @Accept json
+// @Produce json
+// @Param req body entity.WhitelistListReq true "请求参数"
+// @Success 200 {object} entity.WhitelistListResp "返回结果"
+// @Router /v1/admin/whitelist/getWhitelist [post]
+func (w *Whitelist) GetWhitelist(ctx *gin.Context) {
+	req := &entity.WhitelistListReq{}
+	if err := ctx.ShouldBindJSON(req); err != nil {
+		ctx.JSON(200, gin.H{
+			"code": 400,
+			"msg":  err.Error(),
+		})
+		return
+	}
+	whitelists, err := new(service.Whitelist).GetAll(req)
+	if err != nil {
+		ctx.JSON(200, gin.H{
+			"code": 400,
+			"msg":  err.Error(),
+		})
+		return
+	}
+	ctx.JSON(200, gin.H{
+		"code": 200,
+		"data": whitelists,
+	})
+}
+
+// AddWhitelist 新增白名单
+// @Summary 新增白名单
+// @Description 新增白名单
+// @Tags 白名单
+// @Accept json
+// @Produce json
+// @Param req body entity.WhitelistAddReq true "请求参数"
+// @Success 200 {object} entity.WhitelistAddResp "返回结果"
+// @Router /v1/admin/whitelist/addWhitelist [post]
+func (w *Whitelist) AddWhitelist(ctx *gin.Context) {
+	req := &entity.WhitelistAddReq{}
+	if err := ctx.ShouldBindJSON(req); err != nil {
+		ctx.JSON(200, gin.H{
+			"code": 400,
+			"msg":  err.Error(),
+		})
+		return
+	}
+	err := new(service.Whitelist).Add(req.IP)
+	if err != nil {
+		ctx.JSON(200, gin.H{
+			"code": 400,
+			"msg":  err.Error(),
+		})
+		return
+	}
+}
+
+// RemoveWhitelist 删除白名单
+// @Summary 删除白名单
+// @Description 删除白名单
+// @Tags 白名单
+// @Accept json
+// @Produce json
+// @Param req body entity.WhitelistRemoveReq true "请求参数"
+// @Success 200 {object} entity.WhitelistRemoveResp "返回结果"
+func (w *Whitelist) RemoveWhitelist(ctx *gin.Context) {
+	req := &entity.WhitelistRemoveReq{}
+	if err := ctx.ShouldBindJSON(req); err != nil {
+		ctx.JSON(200, gin.H{
+			"code": 400,
+			"msg":  err.Error(),
+		})
+		return
+	}
+	err := new(service.Whitelist).Remove(req.IP)
+	if err != nil {
+		ctx.JSON(200, gin.H{
+			"code": 400,
+			"msg":  err.Error(),
+		})
+		return
+	}
+	ctx.JSON(200, gin.H{
+		"code": 200,
+	})
+}

+ 16 - 0
game/game_cluster/nodes/webadmin/entity/whitelist.go

@@ -0,0 +1,16 @@
+package entity
+
+type WhitelistListReq struct {
+	Page int    `json:"page" binding:"required"`
+	Size int    `json:"size" binding:"required"`
+	IP   string `json:"ip"`
+}
+
+type WhitelistAddReq struct {
+	IP   string `json:"ip" binding:"required"`
+	Desc string `json:"desc"`
+}
+
+type WhitelistRemoveReq struct {
+	IP string `json:"ip" binding:"required"`
+}

+ 36 - 0
game/game_cluster/nodes/webadmin/router/middleware.go

@@ -2,7 +2,12 @@ package router
 
 import (
 	"context"
+	"errors"
+	"fmt"
+	"github.com/mhaya/game/game_cluster/internal/mdb/models"
+	"go.mongodb.org/mongo-driver/bson"
 	"net/http"
+	"time"
 
 	"github.com/gin-gonic/gin"
 	"github.com/mhaya/game/game_cluster/internal/constant"
@@ -39,6 +44,37 @@ func Auth() gin.HandlerFunc {
 			})
 			return
 		}
+		if err := checkIP(c); err != nil {
+			c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{
+				"msg": "ip is no auth",
+			})
+			return
+		}
 		c.Next()
 	}
 }
+
+// checkIP
+func checkIP(c *gin.Context) error {
+	// 获取请求的ip
+	ip := c.ClientIP()
+	whitelistModel := &models.Whitelist{}
+	collection := mdb.MDB.Collection(whitelistModel.TableName())
+
+	// 设置超时时间
+	ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
+	defer cancel() // 确保在函数退出时取消上下文
+
+	// 示例:查询 IP 是否在白名单中
+	err := collection.FindOne(ctx, bson.M{"ip": ip}).Decode(&whitelistModel)
+	if err != nil {
+		// 处理查询错误
+		return fmt.Errorf("failed to check IP in whitelist: %w", err)
+	}
+	// 根据查询结果决定是否允许访问
+	if whitelistModel != nil {
+		return nil // 允许访问
+	} else {
+		return errors.New("IP not in whitelist") // 拒绝访问
+	}
+}

+ 3 - 0
game/game_cluster/nodes/webadmin/router/router.go

@@ -64,6 +64,9 @@ func (c *Controller) InitApiRouter(u *gin.RouterGroup) {
 	u.POST("/role/admin_unbind_role", controller.NewRole().AdminUnBindRole)
 	u.POST("/role/admin_bind_role", controller.NewRole().AdminBindRole)
 	u.POST("/role/admin_role_info", controller.NewRole().GetAdminRole)
+	u.POST("/whitelist/add", controller.NewWhitelist().AddWhitelist)
+	u.POST("/whitelist/remove", controller.NewWhitelist().RemoveWhitelist)
+	u.POST("/whitelist/list", controller.NewWhitelist().GetWhitelist)
 }
 
 // func (c *Controller) InitMdb() {

+ 125 - 0
game/game_cluster/nodes/webadmin/service/whitelist.go

@@ -0,0 +1,125 @@
+package service
+
+import (
+	"context"
+	"errors"
+	"fmt"
+	"github.com/mhaya/game/game_cluster/internal/mdb"
+	"github.com/mhaya/game/game_cluster/internal/mdb/models"
+	"github.com/mhaya/game/game_cluster/nodes/webadmin/entity"
+	"go.mongodb.org/mongo-driver/bson"
+	"go.mongodb.org/mongo-driver/mongo"
+	"go.mongodb.org/mongo-driver/mongo/options"
+	"log"
+	"time"
+)
+
+type Whitelist struct {
+}
+
+func NewWhitelist() *Whitelist {
+	return &Whitelist{}
+}
+
+// Add 添加IP白名单
+func (w *Whitelist) Add(ip string) error {
+	whitelistModel := models.Whitelist{}
+	collection := mdb.MDB.Collection(whitelistModel.TableName())
+	ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
+	defer cancel()
+	// 判断是否已经存在
+	err := collection.FindOne(ctx, bson.M{"ip": ip}).Decode(&whitelistModel)
+	if err == nil {
+		return fmt.Errorf("IP %s already exists in the whitelist", ip)
+	}
+	_, err = collection.InsertOne(ctx, models.Whitelist{
+		IP: ip,
+	})
+	if err != nil {
+		log.Printf("Error inserting IP %s into whitelist: %v", ip, err)
+		if errors.Is(err, mongo.ErrNoDocuments) {
+			return fmt.Errorf("IP %s already exists in the whitelist", ip)
+		}
+		return fmt.Errorf("failed to insert IP %s into whitelist: %v", ip, err)
+	}
+	return nil
+}
+
+// Remove 删除IP白名单
+func (w *Whitelist) Remove(ip string) error {
+	whitelistModel := models.Whitelist{}
+	collection := mdb.MDB.Collection(whitelistModel.TableName())
+	ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
+	defer cancel()
+	_, err := collection.DeleteOne(ctx, bson.M{"ip": ip})
+	if err != nil {
+		log.Printf("Error deleting IP %s from whitelist: %v", ip, err)
+		return fmt.Errorf("failed to delete IP %s from whitelist: %v", ip, err)
+	}
+	return nil
+}
+
+// Check 检查IP是否在白名单中
+func (w *Whitelist) Check(ip string) error {
+	whitelistModel := models.Whitelist{}
+	collection := mdb.MDB.Collection(whitelistModel.TableName())
+	ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
+	defer cancel()
+	// 判断是否已经存在
+	err := collection.FindOne(ctx, bson.M{"ip": ip}).Decode(&whitelistModel)
+	if err == nil {
+		return fmt.Errorf("IP %s already exists in the whitelist", ip)
+	}
+	return nil
+}
+
+// GetAll 获取所有白名单数据
+func (w *Whitelist) GetAll(req *entity.WhitelistListReq) ([]models.Whitelist, error) {
+	// 定义集合
+	whitelistModel := models.Whitelist{}
+	collection := mdb.MDB.Collection(whitelistModel.TableName())
+
+	// 设置上下文
+	ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
+	defer cancel()
+
+	// 解析分页参数
+	page := req.Page
+	pageSize := req.Size
+	if page == 0 {
+		page = 1
+	}
+	if pageSize == 0 {
+		pageSize = 10
+	}
+
+	// 设置分页选项
+	skip := (page - 1) * pageSize
+	findOptions := options.Find().SetSkip(int64(skip)).SetLimit(int64(pageSize))
+
+	// 查询数据库
+	var results []models.Whitelist
+	cursor, err := collection.Find(ctx, bson.D{}, findOptions)
+	if err != nil {
+		log.Printf("Error finding documents: %v", err)
+		return nil, err
+	}
+	defer cursor.Close(ctx)
+
+	// 解析查询结果
+	for cursor.Next(ctx) {
+		var whitelist models.Whitelist
+		if err := cursor.Decode(&whitelist); err != nil {
+			log.Printf("Error decoding document: %v", err)
+			return nil, err
+		}
+		results = append(results, whitelist)
+	}
+
+	if err := cursor.Err(); err != nil {
+		log.Printf("Cursor error: %v", err)
+		return nil, err
+	}
+
+	return results, nil
+}