-
Notifications
You must be signed in to change notification settings - Fork 0
/
checkTokenMiddleware.go
48 lines (44 loc) · 1.13 KB
/
checkTokenMiddleware.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
package tokenauth
import (
"context"
"encoding/json"
"github.com/gin-gonic/gin"
"net/http"
"time"
)
const tokenHeader = "token"
const TokenDataContextKey = "tokenData"
var pathToExclude = []string{"/refreshToken", "/connect"}
func CheckTokenMiddleware(baseToken TokenBase) gin.HandlerFunc {
return func(c *gin.Context) {
for _, p := range pathToExclude {
if p == c.FullPath() {
c.Next()
return
}
}
token := c.GetHeader(tokenHeader)
plainData, protectedData, err := baseToken.ValidateAndGetData(context.Background(), time.Now(), token)
if err != nil {
c.JSON(http.StatusUnauthorized, gin.H{"Message": "Unauthorized"})
c.Abort()
return
}
tokenData := make(map[string]interface{})
for k, v := range plainData {
tokenData[k] = v
}
for k, v := range protectedData {
tokenData[k] = v
}
tokenDataJson, err := json.Marshal(tokenData)
if err != nil {
c.JSON(http.StatusUnauthorized, gin.H{"Message": "wrong data format"})
c.Abort()
return
}
ctx := context.WithValue(c.Request.Context(), TokenDataContextKey, string(tokenDataJson))
c.Request = c.Request.WithContext(ctx)
c.Next()
}
}