-
Notifications
You must be signed in to change notification settings - Fork 666
/
Copy pathmiddleware.go
98 lines (83 loc) · 2.43 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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
package studio
import (
"fmt"
"net/http"
"strings"
"github.com/gin-gonic/gin"
"github.com/yaoapp/kun/exception"
"github.com/yaoapp/kun/log"
"github.com/yaoapp/xun"
"github.com/yaoapp/yao/config"
"github.com/yaoapp/yao/helper"
)
// hdRecovered custom recovered
func hdRecovered(c *gin.Context, recovered interface{}) {
var code = http.StatusInternalServerError
if err, ok := recovered.(string); ok {
c.JSON(code, xun.R{
"code": code,
"message": fmt.Sprintf("%s", err),
})
} else if err, ok := recovered.(exception.Exception); ok {
code = err.Code
c.JSON(code, xun.R{
"code": code,
"message": err.Message,
})
} else if err, ok := recovered.(*exception.Exception); ok {
code = err.Code
c.JSON(code, xun.R{
"code": code,
"message": err.Message,
})
} else {
c.JSON(code, xun.R{
"code": code,
"message": fmt.Sprintf("%v", recovered),
})
}
c.AbortWithStatus(code)
}
// CORS Cross-origin
func hdCORS(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()
}
// studio API Auth
func hdAuth(c *gin.Context) {
tokenString := c.Request.Header.Get("Authorization")
// Get token from query
if c.Query("studio") != "" {
tokenString = c.Query("studio")
}
if strings.HasPrefix(tokenString, "Bearer") {
tokenString = strings.TrimSpace(strings.TrimPrefix(tokenString, "Bearer "))
if tokenString == "" {
c.JSON(403, gin.H{"code": 403, "message": "No permission"})
c.Abort()
return
}
claims := helper.JwtValidate(tokenString, []byte(config.Conf.Studio.Secret))
c.Set("__sid", claims.SID)
c.Next()
return
} else if strings.HasPrefix(tokenString, "Signature ") { // For Yao Studio
signature := strings.TrimSpace(strings.TrimPrefix(tokenString, "Signature "))
nonce := c.Request.Header.Get("Studio-Nonce")
ts := c.Request.Header.Get("Studio-Timestamp")
query := c.Request.URL.Query()
log.Trace("[Studio] %s, %s %s %v", signature, nonce, ts, query)
c.Next()
return
}
c.JSON(403, gin.H{"code": 403, "message": "No permission"})
c.Abort()
return
}