YouChuKoffee/app/http/middlewares/base.go

108 lines
2.9 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) {
c.ClientIP()
var tokens = strings.SplitN(c.GetHeader("Authorization"), " ", 2)
utils.Log(c, "tokens:", tokens)
if len(tokens) != 2 || tokens[0] != "Bearer" {
controllers.HandCodeRes(c, nil, errorcode.NotLogin)
c.Abort()
return
}
// 验证token
token, claims, err := utils.ParseToken(tokens[1])
if err != nil || !token.Valid {
controllers.HandCodeRes(c, nil, errorcode.NotAuth)
c.Abort()
return
}
if err == nil {
c.Set("userId", claims.Id)
c.Set("custNo", claims.CustNo)
c.Next()
return
} else {
controllers.HandCodeRes(c, nil, errorcode.NotAuth)
c.Abort()
}
}
}
func Cors() gin.HandlerFunc {
return func(c *gin.Context) {
c.Writer.Header().Set("Access-Control-Allow-Origin", "*")
//c.Writer.Header().Set("Access-Control-Allow-Origin", "http://milk.api.test.86698.cn/")
c.Writer.Header().Set("Access-Control-Allow-Credentials", "true")
c.Writer.Header().Set("Access-Control-Allow-Headers", "Content-Type, Content-Length, platform,Accept-Encoding, X-CSRF-Token, Authorization, accept, origin, Cache-Control,token, X-Requested-With")
c.Writer.Header().Set("Access-Control-Allow-Methods", "POST, OPTIONS, GET, PUT, DELETE")
if c.Request.Method == "OPTIONS" {
c.AbortWithStatus(204)
return
}
c.Next()
}
}
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()
}
}
}
}