support for basic auth

master v0.14.0
bel 2022-07-09 16:27:49 -06:00
parent 7fabfcd14d
commit 3727e2ee5e
1 changed files with 19 additions and 3 deletions

22
main.go
View File

@ -31,6 +31,7 @@ var (
func main() { func main() {
fs = args.NewArgSet() fs = args.NewArgSet()
fs.Append(args.STRING, "p", "port to serve", "8100") fs.Append(args.STRING, "p", "port to serve", "8100")
fs.Append(args.STRING, "u", "user:pass for basic auth", "")
fs.Append(args.BOOL, "md", "whether to render markdown as html", true) fs.Append(args.BOOL, "md", "whether to render markdown as html", true)
fs.Append(args.BOOL, "ro", "read only mode", false) fs.Append(args.BOOL, "ro", "read only mode", false)
fs.Append(args.BOOL, "https", "https only", false) fs.Append(args.BOOL, "https", "https only", false)
@ -42,6 +43,7 @@ func main() {
} }
d := fs.Get("d").GetString() d := fs.Get("d").GetString()
userPass := fs.Get("u").GetString()
md := fs.Get("md").GetBool() md := fs.Get("md").GetBool()
ro := fs.Get("ro").GetBool() ro := fs.Get("ro").GetBool()
https := fs.Get("https").GetBool() https := fs.Get("https").GetBool()
@ -93,15 +95,15 @@ func main() {
} }
p := strings.TrimPrefix(fs.Get("p").GetString(), ":") p := strings.TrimPrefix(fs.Get("p").GetString(), ":")
http.Handle("/", http.HandlerFunc(handler(https, ro, d, md, mdCss, mdClass))) http.Handle("/", http.HandlerFunc(handler(userPass, https, ro, d, md, mdCss, mdClass)))
log.Printf("Serving %s on HTTP port: %s\n", d, p) log.Printf("Serving %s on HTTP port: %s\n", d, p)
log.Fatal(http.ListenAndServe(":"+p, nil)) log.Fatal(http.ListenAndServe(":"+p, nil))
} }
func handler(https, ro bool, d string, md bool, mdCss, mdClass string) http.HandlerFunc { func handler(userPass string, https, ro bool, d string, md bool, mdCss, mdClass string) http.HandlerFunc {
return httpsOnly(https, gzip(endpoints(ro, withDel(ro, withMD(d, md, mdCss, mdClass, fserve(d)))))) return httpsOnly(https, gzip(basicAuth(userPass, endpoints(ro, withDel(ro, withMD(d, md, mdCss, mdClass, fserve(d)))))))
} }
func writeMeta(w http.ResponseWriter) { func writeMeta(w http.ResponseWriter) {
@ -122,6 +124,20 @@ func writeForm(w http.ResponseWriter) {
`, ENDPOINT_UPLOAD) `, ENDPOINT_UPLOAD)
} }
func basicAuth(userPass string, foo http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
if userPass != "" {
u, p, ok := r.BasicAuth()
if !ok || u+":"+p != userPass {
w.Header().Set("WWW-Authenticate", "Basic")
w.WriteHeader(401)
return
}
}
foo(w, r)
}
}
func httpsOnly(https bool, foo http.HandlerFunc) http.HandlerFunc { func httpsOnly(https bool, foo http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) { return func(w http.ResponseWriter, r *http.Request) {
if https && r.URL.Scheme != "https" { if https && r.URL.Scheme != "https" {