-
-
Notifications
You must be signed in to change notification settings - Fork 346
/
middleware.go
61 lines (53 loc) · 1.7 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
package route
import (
"context"
"net/http"
"github.com/google/uuid"
"github.com/jordanknott/taskcafe/internal/db"
"github.com/jordanknott/taskcafe/internal/utils"
log "github.com/sirupsen/logrus"
)
// AuthenticationMiddleware is a middleware that requires a valid JWT token to be passed via the Authorization header
type AuthenticationMiddleware struct {
repo db.Repository
}
// Middleware returns the middleware handler
func (m *AuthenticationMiddleware) Middleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
requestID := uuid.New()
foundToken := true
tokenRaw := ""
token := r.Header.Get("Authorization")
if token != "" {
tokenRaw = token
} else {
foundToken = false
}
if !foundToken {
c, err := r.Cookie("authToken")
if err != nil {
if err == http.ErrNoCookie {
log.WithError(err).Error("error while fetching authToken")
w.WriteHeader(http.StatusBadRequest)
}
log.WithError(err).Error("error while fetching authToken")
w.WriteHeader(http.StatusBadRequest)
return
}
tokenRaw = c.Value
}
authTokenID, err := uuid.Parse(tokenRaw)
ctx := r.Context()
if err == nil {
token, err := m.repo.GetAuthTokenByID(r.Context(), authTokenID)
if err == nil {
log.WithField("tokenID", authTokenID).WithField("userID", token.UserID).Info("setting auth token")
ctx = context.WithValue(ctx, utils.UserIDKey, token.UserID)
}
}
// ctx = context.WithValue(ctx, utils.RestrictedModeKey, accessClaims.Restricted)
// ctx = context.WithValue(ctx, utils.OrgRoleKey, accessClaims.OrgRole)
ctx = context.WithValue(ctx, utils.ReqIDKey, requestID)
next.ServeHTTP(w, r.WithContext(ctx))
})
}