-
Notifications
You must be signed in to change notification settings - Fork 497
/
middlewares.go
67 lines (61 loc) · 1.96 KB
/
middlewares.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 users
import (
"github.com/dgrijalva/jwt-go"
"github.com/dgrijalva/jwt-go/request"
"github.com/gothinkster/golang-gin-realworld-example-app/common"
"github.com/gin-gonic/gin"
"net/http"
"strings"
)
// Strips 'TOKEN ' prefix from token string
func stripBearerPrefixFromTokenString(tok string) (string, error) {
// Should be a bearer token
if len(tok) > 5 && strings.ToUpper(tok[0:6]) == "TOKEN " {
return tok[6:], nil
}
return tok, nil
}
// Extract token from Authorization header
// Uses PostExtractionFilter to strip "TOKEN " prefix from header
var AuthorizationHeaderExtractor = &request.PostExtractionFilter{
request.HeaderExtractor{"Authorization"},
stripBearerPrefixFromTokenString,
}
// Extractor for OAuth2 access tokens. Looks in 'Authorization'
// header then 'access_token' argument for a token.
var MyAuth2Extractor = &request.MultiExtractor{
AuthorizationHeaderExtractor,
request.ArgumentExtractor{"access_token"},
}
// A helper to write user_id and user_model to the context
func UpdateContextUserModel(c *gin.Context, my_user_id uint) {
var myUserModel UserModel
if my_user_id != 0 {
db := common.GetDB()
db.First(&myUserModel, my_user_id)
}
c.Set("my_user_id", my_user_id)
c.Set("my_user_model", myUserModel)
}
// You can custom middlewares yourself as the doc: https://github.com/gin-gonic/gin#custom-middleware
// r.Use(AuthMiddleware(true))
func AuthMiddleware(auto401 bool) gin.HandlerFunc {
return func(c *gin.Context) {
UpdateContextUserModel(c, 0)
token, err := request.ParseFromRequest(c.Request, MyAuth2Extractor, func(token *jwt.Token) (interface{}, error) {
b := ([]byte(common.NBSecretPassword))
return b, nil
})
if err != nil {
if auto401 {
c.AbortWithError(http.StatusUnauthorized, err)
}
return
}
if claims, ok := token.Claims.(jwt.MapClaims); ok && token.Valid {
my_user_id := uint(claims["id"].(float64))
//fmt.Println(my_user_id,claims["id"])
UpdateContextUserModel(c, my_user_id)
}
}
}