-
Notifications
You must be signed in to change notification settings - Fork 2
/
middleware.go
48 lines (39 loc) · 1.26 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
package users
import (
"context"
"net/http"
"github.com/octavore/nagax/router"
)
type UserTokenKey struct{}
func (m *Module) WithAuth(next router.Handle) router.Handle {
return m.WithAuthList(m.Authenticators, next)
}
func (m *Module) MustWithAuth(next router.Handle) router.Handle {
return m.MustWithAuthList(m.Authenticators, next)
}
func (m *Module) WithAuthList(authenticators []Authenticator, next router.Handle) router.Handle {
return func(rw http.ResponseWriter, req *http.Request, par router.Params) error {
_, userToken, err := m.AuthenticateWithList(authenticators, rw, req)
if err != nil {
return err
}
if userToken != nil {
ctx := context.WithValue(req.Context(), UserTokenKey{}, *userToken)
req = req.WithContext(ctx)
}
return next(rw, req, par)
}
}
func (m *Module) MustWithAuthList(authenticators []Authenticator, next router.Handle) router.Handle {
return func(rw http.ResponseWriter, req *http.Request, par router.Params) error {
handled, userToken, err := m.AuthenticateWithList(authenticators, rw, req)
if err != nil {
return err
}
if !handled || userToken == nil {
return router.ErrNotAuthorized
}
ctx := context.WithValue(req.Context(), UserTokenKey{}, *userToken)
return next(rw, req.WithContext(ctx), par)
}
}