1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980 |
- 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"
- "github.com/mhaya/game/game_cluster/internal/mdb"
- )
- func Auth() gin.HandlerFunc {
- return func(c *gin.Context) {
- tokenString := c.GetHeader("Token")
- if tokenString == "" {
- c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{
- "msg": "token is empty",
- })
- return
- }
- result, err := mdb.RDB.Get(context.Background(), tokenString).Result()
- if err != nil {
- return
- }
- if result == "" {
- c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{
- "msg": "token is invalid",
- })
- return
- }
- // 获取请求URL
- url := c.Request.URL.Path
- s, _ := mdb.RDB.HGet(context.Background(), "admin::token::"+tokenString, url).Result()
- admin, _ := mdb.RDB.HGet(context.Background(), "admin::token::"+tokenString, constant.AdminAccess).Result()
- // 检查是否有权限
- if s == "" && admin == "" {
- c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{
- "msg": "token is no auth",
- })
- 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") // 拒绝访问
- }
- }
|