XinYeYouKu/app/http/middlewares/base.go

83 lines
2.2 KiB
Go

package middlewares
import (
"context"
"errors"
"github.com/gin-gonic/gin"
"github.com/qit-team/snow-core/redis"
"qteam/app/constants/common"
"qteam/app/constants/errorcode"
"qteam/app/http/controllers"
"qteam/app/http/requestmapping"
"qteam/app/utils"
"strings"
)
func Auth() gin.HandlerFunc {
return func(c *gin.Context) {
var token = c.GetHeader("token")
//将token放入redis
var playerId, err = redis.GetRedis().Get(context.Background(), utils.GetRealKey(common.TOKEN_PRE+token)).Result()
if rs, errRedis := redis.GetRedis().SIsMember(context.Background(), "disabled_uids", playerId).Result(); errRedis == nil && rs {
err = errors.New(errorcode.GetMsg(errorcode.NotFound, ""))
redis.GetRedis().SRem(context.Background(), "disabled_uids", playerId)
}
if err == nil {
c.Set("playerId", playerId)
c.Next()
return
} else {
controllers.HandCodeRes(c, nil, errorcode.Forbidden)
c.Abort()
}
}
}
func AdminAuth() gin.HandlerFunc {
return func(c *gin.Context) {
var token = c.GetHeader("token")
//将token放入redis
var playerId, err = redis.GetRedis().Get(context.Background(), utils.GetRealKey(common.TOKEN_Admin+token)).Result()
if rs, errRedis := redis.GetRedis().SIsMember(context.Background(), "disabled_uids", playerId).Result(); errRedis == nil && rs {
err = errors.New(errorcode.GetMsg(errorcode.NotFound, ""))
redis.GetRedis().SRem(context.Background(), "disabled_uids", playerId)
}
if err == nil {
c.Set("playerId", playerId)
c.Next()
return
} else {
controllers.HandCodeRes(c, nil, errorcode.Forbidden)
c.Abort()
}
}
}
func ValidateRequest() gin.HandlerFunc {
return func(c *gin.Context) {
var path = c.FullPath()
var handler func() interface{}
if strings.Index(path, "admin") >= 0 {
handler = requestmapping.BackendRequestMap[path]
} else {
handler = requestmapping.FrontRequestMap[path]
}
if handler == nil {
utils.Log(c, "path", path)
controllers.HandCodeRes(c, nil, errorcode.NotFound)
} else {
v := handler()
msg, err := controllers.GenRequest(c, v)
if err != nil {
utils.Log(c, "path", path)
controllers.Error(c, errorcode.ParamError, msg...)
} else {
c.Set("request", v)
c.Next()
}
}
}
}