/
middleware.go
55 lines (46 loc) · 1.02 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
package basicauth
import (
"net/http"
"strconv"
"github.com/uptrace/bunrouter"
)
type middleware struct {
realm string
check func(req bunrouter.Request) (bool, error)
}
type Option func(m *middleware)
func WithRealm(realm string) Option {
return func(m *middleware) {
m.realm = strconv.Quote(realm)
}
}
func NewMiddleware(
check func(req bunrouter.Request) (bool, error),
opts ...Option,
) bunrouter.MiddlewareFunc {
c := &middleware{
realm: "Restricted",
check: check,
}
for _, opt := range opts {
opt(c)
}
return c.Middleware
}
func (m *middleware) Middleware(next bunrouter.HandlerFunc) bunrouter.HandlerFunc {
return func(w http.ResponseWriter, req bunrouter.Request) error {
ok, err := m.check(req)
if err != nil {
return err
}
if ok {
return next(w, req)
}
return m.basicAuth(w, req)
}
}
func (m *middleware) basicAuth(w http.ResponseWriter, req bunrouter.Request) error {
w.Header().Set("WWW-Authenticate", "basic realm="+m.realm)
w.WriteHeader(http.StatusUnauthorized)
return nil
}