-
Notifications
You must be signed in to change notification settings - Fork 10
/
middleware.go
51 lines (47 loc) · 1.48 KB
/
middleware.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
package route
import (
"net/http"
"strings"
"github.com/dgrijalva/jwt-go"
"github.com/gin-gonic/gin"
"github.com/go-micro/dashboard/config"
)
func AuthRequired() gin.HandlerFunc {
return func(ctx *gin.Context) {
if ctx.Request.Method == "OPTIONS" {
ctx.Next()
return
}
tokenString := ctx.GetHeader("Authorization")
if len(tokenString) == 0 || !strings.HasPrefix(tokenString, "Bearer ") {
ctx.AbortWithStatusJSON(http.StatusUnauthorized, "")
return
}
tokenString = tokenString[7:]
claims := jwt.StandardClaims{}
token, err := jwt.ParseWithClaims(tokenString, &claims, func(t *jwt.Token) (interface{}, error) {
return []byte(config.GetAuthConfig().TokenSecret), nil
})
if err != nil {
ctx.AbortWithError(http.StatusUnauthorized, err)
}
if !token.Valid {
ctx.AbortWithStatus(http.StatusUnauthorized)
}
ctx.Set("username", claims.Subject)
ctx.Next()
}
}
func CorsHandler(allowOrigin string) gin.HandlerFunc {
return func(ctx *gin.Context) {
ctx.Header("Access-Control-Allow-Origin", allowOrigin)
ctx.Header("Access-Control-Allow-Headers", "Content-Type, Authorization, token")
ctx.Header("Access-Control-Allow-Methods", "POST, GET, DELETE, PUT, OPTIONS")
ctx.Header("Access-Control-Expose-Headers", "Content-Length, Access-Control-Allow-Origin, Access-Control-Allow-Headers, Content-Type")
ctx.Header("Access-Control-Allow-Credentials", "true")
if ctx.Request.Method == "OPTIONS" {
ctx.AbortWithStatus(http.StatusNoContent)
}
ctx.Next()
}
}