Explorar o código

update 优化中间件;完善ip白名单

Alvin hai 8 meses
pai
achega
f2a7ca5767

+ 3 - 1
game/config/data/codeConfig.json

@@ -26,5 +26,7 @@
   {"code":16011,"message":"没有权限"},
   {"code":16012,"message":"角色不存在,或者已经被禁用"},
   {"code":16013,"message":"管理员不存在"},
-  {"code":16014,"message":"admin-超级账户不能修改角色"}
+  {"code":16014,"message":"admin-超级账户不能修改角色"},
+  {"code":16015,"message":"token验证失败"},
+  {"code":16016,"message":"Ip 禁用"}
 ]

+ 2 - 1
game/config/profile-gc.json

@@ -99,7 +99,8 @@
           "db_id_list": {
             "game_db_id": "game_db_1"
           },
-          "ref_logger": "web_admin_log"
+          "ref_logger": "web_admin_log",
+          "open_ip_whitelist": false
         },
         "enable": true
       }

+ 2 - 1
game/game_cluster/internal/code/code.go

@@ -47,5 +47,6 @@ var (
 	RoleNotExistOrDisabledUserError int32 = 16012 // 角色不存在,或者已经被禁用
 	AdminNotExistError              int32 = 16013 // 管理员不存在
 	AdminMustNotUpdateError         int32 = 16014 // admin-超级账户不能修改角色
-
+	UnauthorizedError               int32 = 16015 // token验证失败
+	ForbiddenError                  int32 = 16016 // Ip 禁用
 )

+ 52 - 0
game/game_cluster/nodes/webadmin/common/packResponse.go

@@ -16,6 +16,19 @@ func NewResult(statusCode int32) *code.Result {
 	return result
 }
 
+func NewResultWithDetailErr(statusCode int32, errMsg string) *code.Result {
+	result := &code.Result{
+		Code:    statusCode,
+		Message: code.GetMessage(statusCode),
+	}
+
+	if errMsg != "" {
+		result.Message += ": " + errMsg
+	}
+
+	return result
+}
+
 func PackOkResult(c *gin.Context, statusCode int32, data ...interface{}) {
 	result := &code.Result{
 		Code:    statusCode,
@@ -28,3 +41,42 @@ func PackOkResult(c *gin.Context, statusCode int32, data ...interface{}) {
 
 	c.JSON(http.StatusOK, result)
 }
+
+func PackDetailErrResult(c *gin.Context, statusCode int32, errMsg string) {
+	result := &code.Result{
+		Code:    statusCode,
+		Message: code.GetMessage(statusCode),
+	}
+
+	if errMsg != "" {
+		result.Message += ": " + errMsg
+	}
+
+	c.JSON(http.StatusOK, result)
+}
+
+func PackUnauthorizedResult(c *gin.Context, statusCode int32, errMsg string) {
+	result := &code.Result{
+		Code:    statusCode,
+		Message: code.GetMessage(statusCode),
+	}
+
+	if errMsg != "" {
+		result.Message += ": " + errMsg
+	}
+
+	c.AbortWithStatusJSON(http.StatusUnauthorized, result)
+}
+
+func PackForbiddenResult(c *gin.Context, statusCode int32, errMsg string) {
+	result := &code.Result{
+		Code:    statusCode,
+		Message: code.GetMessage(statusCode),
+	}
+
+	if errMsg != "" {
+		result.Message += ": " + errMsg
+	}
+
+	c.AbortWithStatusJSON(http.StatusForbidden, result)
+}

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

@@ -3,69 +3,83 @@ package router
 import (
 	"context"
 	"errors"
-	"fmt"
-	"net/http"
 	"time"
 
+	"github.com/gin-gonic/gin"
+	cfacade "github.com/mhaya/facade"
+	"github.com/mhaya/game/game_cluster/internal/code"
 	"github.com/mhaya/game/game_cluster/internal/constant"
+	"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/common"
+	mhayaLogger "github.com/mhaya/logger"
 	"go.mongodb.org/mongo-driver/bson"
-
-	"github.com/gin-gonic/gin"
-	"github.com/mhaya/game/game_cluster/internal/mdb"
+	"go.mongodb.org/mongo-driver/mongo"
 )
 
-func Auth() gin.HandlerFunc {
+func Auth(settingObj cfacade.ProfileJSON) gin.HandlerFunc {
 	return func(c *gin.Context) {
 		tokenString := c.GetHeader("Token")
 		if tokenString == "" {
-			c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{
-				"msg": "token is empty",
-			})
+			common.PackUnauthorizedResult(c, code.UnauthorizedError, "token is empty")
 			return
 		}
+
 		result, err := mdb.RDB.Get(context.Background(), tokenString).Result()
 		if err != nil {
-			c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{
-				"msg": "token is empty",
-			})
+			mhayaLogger.Warnf("Auth Get error: %s", err.Error())
+			common.PackUnauthorizedResult(c, code.InternalError, "token is empty")
 			return
 		}
 		if result == "" {
-			c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{
-				"msg": "token is invalid",
-			})
+			common.PackUnauthorizedResult(c, code.UnauthorizedError, "token is invalid")
 			return
 		}
+
 		// 获取请求URL
-		url := c.Request.URL.Path
-		s, _ := mdb.RDB.HGet(context.Background(), "admin::token::"+tokenString, url).Result()
-		ss, _ := mdb.RDB.HGet(context.Background(), "admin::token::"+tokenString, constant.AdminAccess).Result()
-		fmt.Println(ss)
+		// url := c.Request.URL.Path
+		// s, err := mdb.RDB.HGet(context.Background(), "admin::token::"+tokenString, url).Result()
+		// if err != nil {
+		// 	mhayaLogger.Warnf("Auth HGet s error: %s", err.Error())
+		// 	common.PackUnauthorizedResult(c, code.InternalError, "")
+		// 	return
+		// }
+		// mhayaLogger.Warnf("Auth s: %s", s)
+
+		ss, err := mdb.RDB.HGet(context.Background(), "admin::token::"+tokenString, constant.AdminAccess).Result()
+		if err != nil {
+			mhayaLogger.Warnf("Auth HGet ss error: %s", err.Error())
+			common.PackUnauthorizedResult(c, code.InternalError, "")
+			return
+		}
+		mhayaLogger.Warnf("Auth ss: %s", ss)
+
 		// 检查是否有权限
-		if s == "" && result == "" {
-			c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{
-				"msg": "token is no auth",
-			})
+		if ss == "" && result == "" {
+			common.PackUnauthorizedResult(c, code.UnauthorizedError, "token is no auth")
 			return
 		}
-		if result == "" {
-			if err := checkIP(c); err != nil {
-				c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{
-					"msg": "ip is no auth",
-				})
+
+		openIpWhitelist := settingObj.Get("open_ip_whitelist").ToBool()
+		mhayaLogger.Warnf("Auth open_ip_whitelist: %v", openIpWhitelist)
+		if openIpWhitelist {
+			err = checkIPWhitelist(c)
+			if err != nil {
+				mhayaLogger.Warnf("Auth checkIPWhitelist error: %s", err.Error())
+				common.PackForbiddenResult(c, code.ForbiddenError, "ip is no auth")
 				return
 			}
 		}
+
 		c.Next()
 	}
 }
 
 // checkIP
-func checkIP(c *gin.Context) error {
+func checkIPWhitelist(c *gin.Context) error {
 	// 获取请求的ip
 	ip := c.ClientIP()
-	whitelistModel := &models.Whitelist{}
+	var whitelistModel *models.Whitelist
 	collection := mdb.MDB.Collection(whitelistModel.TableName())
 
 	// 设置超时时间
@@ -74,14 +88,14 @@ func checkIP(c *gin.Context) error {
 
 	// 示例:查询 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 err != nil && err != mongo.ErrNoDocuments {
+		return err
 	}
+
 	// 根据查询结果决定是否允许访问
-	if whitelistModel != nil {
-		return nil // 允许访问
-	} else {
+	if whitelistModel == nil {
 		return errors.New("IP not in whitelist") // 拒绝访问
 	}
+
+	return nil // 允许访问
 }

+ 1 - 1
game/game_cluster/nodes/webadmin/router/router.go

@@ -37,7 +37,7 @@ func (c *Controller) SetRouter() {
 }
 
 func (c *Controller) InitApiRouter(u *gin.RouterGroup) {
-	u.Use(Auth())
+	u.Use(Auth(c.App.Settings()))
 	u.POST("/user/log/daily", controller.NewSynthesis().FindUserLogDaily)
 	u.POST("/user/retention", controller.NewSynthesis().FindUserRetention)
 	u.POST("/user/country", controller.NewSynthesis().FindUserCountryCount)