Protect books files

This commit is contained in:
Meutel 2017-09-09 18:03:59 +02:00
parent 9a50ccd2fc
commit 12f79cc852
3 changed files with 24 additions and 3 deletions

View File

@ -6,9 +6,9 @@ Bouquins in Go
* translations
* tests
* auth downloads
* csrf
* userdb commands (init, migrate, add/remove user/email)
* error pages
## Minify JS

View File

@ -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)
}
})
}

View File

@ -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)