forked from YaoApp/yao
-
Notifications
You must be signed in to change notification settings - Fork 0
/
guard.go
46 lines (38 loc) · 1.23 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
package service
import (
"strings"
"github.com/gin-gonic/gin"
"github.com/yaoapp/yao/helper"
"github.com/yaoapp/yao/table"
)
// Guards 服务中间件
var Guards = map[string]gin.HandlerFunc{
"bearer-jwt": bearerJWT, // JWT 鉴权
"cross-domain": crossDomain, // 跨域许可
"table-guard": table.Guard, // Table Guard
}
// JWT 鉴权
func bearerJWT(c *gin.Context) {
tokenString := c.Request.Header.Get("Authorization")
tokenString = strings.TrimSpace(strings.TrimPrefix(tokenString, "Bearer "))
if tokenString == "" {
c.JSON(403, gin.H{"code": 403, "message": "无权访问该页面"})
c.Abort()
return
}
claims := helper.JwtValidate(tokenString)
c.Set("__sid", claims.SID)
c.Next()
}
// 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()
}