forked from st3v/go-plugins
-
Notifications
You must be signed in to change notification settings - Fork 0
/
stats_auth.go
82 lines (72 loc) · 1.75 KB
/
stats_auth.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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
// stats_auth enables basic auth on the /stats endpoint
package stats_auth
import (
"net/http"
"github.com/micro/cli"
"github.com/micro/micro/plugin"
)
const (
defaultRealm = "Access to stats is restricted"
)
type stats_auth struct {
User string
Pass string
Realm string
}
func (sa *stats_auth) Flags() []cli.Flag {
return []cli.Flag{
cli.StringFlag{
Name: "stats_auth_user",
Usage: "Username used for basic auth for /stats endpoint",
EnvVar: "STATS_AUTH_USER",
},
cli.StringFlag{
Name: "stats_auth_pass",
Usage: "Password used for basic auth for /stats endpoint",
EnvVar: "STATS_AUTH_PASS",
},
cli.StringFlag{
Name: "stats_auth_realm",
Usage: "Realm used for basic auth for /stats endpoint. Escape spaces to add multiple words. Optional. Defaults to " + defaultRealm,
EnvVar: "STATS_AUTH_REALM",
},
}
}
func (sa *stats_auth) Commands() []cli.Command {
return nil
}
func (sa *stats_auth) Handler() plugin.Handler {
return func(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != "/stats" {
h.ServeHTTP(w, r)
return
}
if u, p, ok := r.BasicAuth(); ok {
if u == sa.User && p == sa.Pass {
h.ServeHTTP(w, r)
return
}
}
w.Header().Add("WWW-Authenticate", sa.Realm)
w.WriteHeader(http.StatusUnauthorized)
return
})
}
}
func (sa *stats_auth) Init(ctx *cli.Context) error {
sa.User = ctx.String("stats_auth_user")
sa.Pass = ctx.String("stats_auth_pass")
if ctx.IsSet("stats_auth_realm") {
sa.Realm = ctx.String("stats_auth_realm")
} else {
sa.Realm = defaultRealm
}
return nil
}
func (sa *stats_auth) String() string {
return "stats_auth"
}
func NewPlugin() plugin.Plugin {
return &stats_auth{}
}