Cron_Admin/app/http/middlewares/base.go

83 lines
2.1 KiB
Go

package middlewares
import (
"cron_admin/app/constants/errorcode"
"cron_admin/app/http/controllers"
"cron_admin/app/http/requestmapping"
"cron_admin/app/utils"
"fmt"
"github.com/gin-gonic/gin"
"strings"
)
func Auth() gin.HandlerFunc {
return func(c *gin.Context) {
c.ClientIP()
var tokens = strings.SplitN(c.GetHeader("Authorization"), " ", 2)
if len(tokens) != 2 || tokens[0] != "Bearer" {
controllers.HandRes(c, nil, errorcode.NotLogin)
c.Abort()
return
}
// 验证token
token, claims, err := utils.ParseToken(tokens[1])
if err != nil || !token.Valid {
controllers.HandRes(c, nil, errorcode.NotAuth)
c.Abort()
return
}
if err == nil {
c.Set("userId", claims.Id)
c.Set("phone", claims.Phone)
c.Next()
return
} else {
controllers.HandRes(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-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 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.HandRes(c, nil, errorcode.NotFound)
} else {
v := handler()
msg, err := controllers.GenRequest(c, v)
if err != nil {
utils.Log(c, "path", path)
controllers.HandRes(c, nil, errorcode.ParamError.Wrap(fmt.Errorf("%s", strings.Join(msg, ","))))
} else {
c.Set("request", v)
c.Next()
}
}
}
}