diff --git a/README.md b/README.md index fd5ce4f..c294986 100644 --- a/README.md +++ b/README.md @@ -6,9 +6,9 @@ Bouquins in Go * translations * tests -* auth downloads * csrf * userdb commands (init, migrate, add/remove user/email) +* error pages ## Minify JS diff --git a/bouquins/bouquins.go b/bouquins/bouquins.go index 6a19344..7f3374d 100644 --- a/bouquins/bouquins.go +++ b/bouquins/bouquins.go @@ -65,6 +65,9 @@ const ( URLCalibre = "/calibre/" ) +// UnprotectedCalibreSuffix lists suffixe of calibre file not protected by auth +var UnprotectedCalibreSuffix = [1]string{"jpg"} + // Conf App configuration type Conf struct { BindAddress string `json:"bind-address"` @@ -486,3 +489,21 @@ func (app *Bouquins) IndexPage(res http.ResponseWriter, req *http.Request) error } return app.render(res, tplIndex, model) } + +func (app *Bouquins) CalibreFileServer() http.Handler { + calibre := app.Conf.CalibrePath + handler := http.StripPrefix(URLCalibre, http.FileServer(http.Dir(calibre))) + return http.HandlerFunc(func(res http.ResponseWriter, req *http.Request) { + for _, suffix := range UnprotectedCalibreSuffix { + if strings.HasSuffix(req.URL.Path, suffix) { + handler.ServeHTTP(res, req) + } + } + // check auth + if app.Username(req) == "" { + http.Error(res, "401 Unauthorized", http.StatusUnauthorized) + } else { + handler.ServeHTTP(res, req) + } + }) +} diff --git a/main.go b/main.go index 39fc05a..4981f82 100644 --- a/main.go +++ b/main.go @@ -81,7 +81,6 @@ func initApp() *bouquins.Bouquins { if err != nil { log.Fatalln(err) } - assets(conf.CalibrePath) router(app) return app } @@ -90,7 +89,6 @@ func assets(calibre string) { http.Handle(bouquins.URLJs, http.StripPrefix("/"+bouquins.Version, http.FileServer(http.Dir("assets")))) http.Handle(bouquins.URLCss, http.StripPrefix("/"+bouquins.Version, http.FileServer(http.Dir("assets")))) http.Handle(bouquins.URLFonts, http.StripPrefix("/"+bouquins.Version, http.FileServer(http.Dir("assets")))) - http.Handle(bouquins.URLCalibre, http.StripPrefix(bouquins.URLCalibre, http.FileServer(http.Dir(calibre)))) } func handle(f func(res http.ResponseWriter, req *http.Request) error) func(res http.ResponseWriter, req *http.Request) { @@ -108,6 +106,8 @@ func handleURL(url string, f func(res http.ResponseWriter, req *http.Request) er } func router(app *bouquins.Bouquins) { + assets(app.Conf.CalibrePath) + http.Handle(bouquins.URLCalibre, app.CalibreFileServer()) handleURL(bouquins.URLIndex, app.IndexPage) handleURL(bouquins.URLLogin, app.LoginPage) handleURL(bouquins.URLLogout, app.LogoutPage)