forked from YaoApp/yao
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathguard.go
67 lines (56 loc) · 1.85 KB
/
guard.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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
package service
import (
"fmt"
"strings"
"github.com/dgrijalva/jwt-go"
"github.com/gin-gonic/gin"
"github.com/yaoapp/kun/log"
"github.com/yaoapp/yao/config"
"github.com/yaoapp/yao/helper"
)
// Guards 服务中间件
var Guards = map[string]gin.HandlerFunc{
"bearer-jwt": bearerJWT, // JWT 鉴权
"cross-domain": crossDomain, // 跨域许可
}
// JWT 鉴权
func bearerJWT(c *gin.Context) {
tokenString := c.Request.Header.Get("Authorization")
if tokenString == "" {
c.JSON(403, gin.H{"code": 403, "message": "无权访问该页面"})
c.Abort()
return
}
tokenString = strings.TrimSpace(strings.TrimPrefix(tokenString, "Bearer "))
log.Debug("JWT: %s Secret: %s", tokenString, config.Conf.JWTSecret)
token, err := jwt.ParseWithClaims(tokenString, &helper.JwtClaims{}, func(token *jwt.Token) (interface{}, error) {
return []byte(config.Conf.JWTSecret), nil
})
if err != nil {
log.Error("JWT ParseWithClaims Error: %s", err)
c.JSON(403, gin.H{"code": 403, "message": fmt.Sprintf("登录已过期或令牌失效(%s)", err)})
c.Abort()
return
}
if claims, ok := token.Claims.(*helper.JwtClaims); ok && token.Valid {
c.Set("__sid", claims.SID)
c.Next()
return
}
// fmt.Println("bearer-JWT", token.Claims.Valid())
c.JSON(403, gin.H{"code": 403, "message": "无权访问该页面"})
c.Abort()
return
}
// crossDomain 跨域访问
func crossDomain(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, Accept-Encoding, X-CSRF-Token, Authorization, accept, origin, Cache-Control, X-Requested-With")
c.Writer.Header().Set("Access-Control-Allow-Methods", "POST, OPTIONS, GET, PUT")
if c.Request.Method == "OPTIONS" {
c.AbortWithStatus(204)
return
}
c.Next()
}