-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmiddleware.go
More file actions
62 lines (56 loc) · 1.38 KB
/
middleware.go
File metadata and controls
62 lines (56 loc) · 1.38 KB
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
package goauthlib
import (
"context"
"github.com/techpro-studio/gohttplib"
"net/http"
"strings"
)
const CurrentUserContextKey = "current_user_key"
func UserMiddlewareFactory(config JWTConfig) gohttplib.Middleware {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
tokenStr := GetTokenFromRequest(req)
if tokenStr == "" {
gohttplib.HTTP401().Write(w)
return
}
user, err := config.GetValidUserFromToken(tokenStr)
if err != nil {
gohttplib.HTTP401().Write(w)
}
if user == nil {
gohttplib.HTTP401().Write(w)
return
}
ctx := context.WithValue(req.Context(), CurrentUserContextKey, user)
next.ServeHTTP(w, req.WithContext(ctx))
})
}
}
func GetTokenFromRequest(req *http.Request) string {
tokenStr := ""
if AuthHeader := req.Header.Get("Authorization"); AuthHeader != "" {
tokenStr = strings.Split(AuthHeader, " ")[1]
}
if tokenStr == "" {
token := gohttplib.GetParameterFromURLInRequest(req, "token")
if token != nil {
tokenStr = *token
}
}
return tokenStr
}
func GetUserFromRequestWithPanic(req *http.Request) User {
usr := GetUserFromRequest(req)
if usr == nil {
panic("No current user")
}
return *usr
}
func GetUserFromRequest(req *http.Request) *User {
user, ok := req.Context().Value(CurrentUserContextKey).(*User)
if !ok {
return nil
}
return user
}