æ·feat: commplete init process
This commit is contained in:
@@ -0,0 +1,26 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"github.com/gin-gonic/gin"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
// Cors 直接放行所有跨域请求并放行所有 OPTIONS 方法
|
||||
func Cors() gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
method := c.Request.Method
|
||||
origin := c.Request.Header.Get("Origin")
|
||||
c.Header("Access-Control-Allow-Origin", origin)
|
||||
c.Header("Access-Control-Allow-Headers", "Content-Type,AccessToken,X-CSRF-Token, Authorization, Token,X-Token,X-User-Id,M-Token")
|
||||
c.Header("Access-Control-Allow-Methods", "POST, GET, OPTIONS,DELETE,PUT")
|
||||
c.Header("Access-Control-Expose-Headers", "Content-Length, Access-Control-Allow-Origin, Access-Control-Allow-Headers, Content-Type, New-Token, New-Expires-At")
|
||||
c.Header("Access-Control-Allow-Credentials", "true")
|
||||
|
||||
// 放行所有OPTIONS方法
|
||||
if method == "OPTIONS" {
|
||||
c.AbortWithStatus(http.StatusNoContent)
|
||||
}
|
||||
// 处理请求
|
||||
c.Next()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"github.com/dgrijalva/jwt-go"
|
||||
"net/http"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
|
||||
"message-nest/pkg/e"
|
||||
"message-nest/pkg/util"
|
||||
)
|
||||
|
||||
var ExcludedRoutes = []string{
|
||||
"/api/v1/message/send",
|
||||
}
|
||||
|
||||
// JWT is jwt middleware
|
||||
func JWT() gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
path := c.FullPath()
|
||||
for _, route := range ExcludedRoutes {
|
||||
if path == route {
|
||||
c.Next()
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
var code int
|
||||
var data interface{}
|
||||
code = e.SUCCESS
|
||||
token := c.Request.Header.Get("M-Token")
|
||||
|
||||
if token == "" {
|
||||
code = e.ERROR_AUTH_NO_TOKEN
|
||||
} else {
|
||||
claims, err := util.ParseToken(token)
|
||||
if err != nil {
|
||||
switch err.(*jwt.ValidationError).Errors {
|
||||
case jwt.ValidationErrorExpired:
|
||||
code = e.ERROR_AUTH_CHECK_TOKEN_TIMEOUT
|
||||
default:
|
||||
code = e.ERROR_AUTH_CHECK_TOKEN_FAIL
|
||||
}
|
||||
} else {
|
||||
c.Set("currentUserName", claims.Username)
|
||||
}
|
||||
}
|
||||
|
||||
if code != e.SUCCESS {
|
||||
c.JSON(http.StatusUnauthorized, gin.H{
|
||||
"code": code,
|
||||
"msg": e.GetMsg(code),
|
||||
"data": data,
|
||||
})
|
||||
c.Abort()
|
||||
return
|
||||
}
|
||||
|
||||
c.Next()
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user