-
Notifications
You must be signed in to change notification settings - Fork 2
/
authn.go
40 lines (34 loc) · 882 Bytes
/
authn.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
package authn
import (
"net/http"
"github.com/moonrhythm/parapet/pkg/header"
)
// Authenticator middleware
//
//nolint:govet
type Authenticator struct {
Type string
Authenticate func(*http.Request) error
Forbidden func(w http.ResponseWriter, r *http.Request, err error)
}
// ServeHandler implements middleware interface
func (m Authenticator) ServeHandler(h http.Handler) http.Handler {
if m.Authenticate == nil {
return h
}
if m.Forbidden == nil {
m.Forbidden = func(w http.ResponseWriter, r *http.Request, err error) {
http.Error(w, "Unauthorized", http.StatusUnauthorized)
}
}
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if err := m.Authenticate(r); err != nil {
if m.Type != "" {
header.Set(w.Header(), header.WWWAuthenticate, m.Type)
}
m.Forbidden(w, r, err)
return
}
h.ServeHTTP(w, r)
})
}