-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmiddlware.go
57 lines (49 loc) · 1.34 KB
/
middlware.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
package auth
import (
"context"
"net/http"
"strings"
"github.com/rest-go/rest/pkg/log"
)
type AuthUserCtxKey string
const (
AuthorizationHeader = "Authorization"
AuthUserKey = AuthUserCtxKey("auth-user")
)
// Middleware is a type alias for http handler middleware
type Middleware func(http.Handler) http.Handler
// NewMiddleware create a middleware using provided secret
func NewMiddleware(secret []byte) Middleware {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
user := &User{}
tokenString := strings.TrimPrefix(r.Header.Get(AuthorizationHeader), "Bearer ")
if tokenString != "" {
data, err := ParseJWTToken(secret, tokenString)
if err == nil {
user = &User{ID: int64(data["user_id"].(float64))}
if isAdmin, ok := data["is_admin"]; ok {
user.IsAdmin = isAdmin.(bool)
}
} else {
log.Warn("parse jwt token with error: ", err)
}
}
// add the user to the context
ctx := context.WithValue(r.Context(), AuthUserKey, user)
r = r.WithContext(ctx)
// call the next handler
next.ServeHTTP(w, r)
})
}
}
// GetUser return the user in request context
func GetUser(r *http.Request) *User {
v := r.Context().Value(AuthUserKey)
if v != nil {
if user, ok := v.(*User); ok {
return user
}
}
return &User{}
}