-
Notifications
You must be signed in to change notification settings - Fork 2
/
middleware.go
59 lines (51 loc) · 1.62 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
package auth
import (
"context"
"fmt"
"github.com/golang/glog"
"net/http"
)
// see: https://blog.golang.org/context#TOC_3.2.
type key int
const (
// CtxPrincipalKey in ctx
CtxPrincipalKey key = iota
)
// AuthenticationMiddleware is a middleware for auth process
type AuthenticationMiddleware struct {
tokenValidator TokenValidator
principalRetriever PrincipalRetriever
}
// NewAuthenticationMiddleware return instance of AuthenticationMiddleware
func NewAuthenticationMiddleware(validator TokenValidator, principalRetriever PrincipalRetriever) (*AuthenticationMiddleware, error) {
if validator == nil {
return nil, fmt.Errorf("token validator must not be nil")
}
if principalRetriever == nil {
return nil, fmt.Errorf("principal retriever must not be nil")
}
middleware := &AuthenticationMiddleware{
tokenValidator: validator,
principalRetriever: principalRetriever,
}
return middleware, nil
}
// AddAuthentication add new auth method
func (a *AuthenticationMiddleware) AddAuthentication(next http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
if err := a.tokenValidator.ValidateRequest(r); err != nil {
glog.Warningf("Error validating request for %s: %s", r.URL.Path, err)
w.WriteHeader(http.StatusUnauthorized)
return
}
principal, err := a.principalRetriever.RetrieveCurrentPrincipal(ctx, r)
if err != nil {
glog.Warningf("could not get current principal: %s", err)
w.WriteHeader(http.StatusUnauthorized)
return
}
ctx = context.WithValue(r.Context(), CtxPrincipalKey, principal)
next.ServeHTTP(w, r.WithContext(ctx))
}
}