From f0bf40f412c782223be6c11799b687136cc26b46 Mon Sep 17 00:00:00 2001 From: Meutel Date: Sun, 30 Jul 2017 10:01:23 +0200 Subject: [PATCH] Secure session cookie --- photoblog/admin/admin.go | 17 +++++++++++++++++ photoblog/main.go | 11 +++-------- 2 files changed, 20 insertions(+), 8 deletions(-) diff --git a/photoblog/admin/admin.go b/photoblog/admin/admin.go index 6eeb768..939874a 100644 --- a/photoblog/admin/admin.go +++ b/photoblog/admin/admin.go @@ -11,6 +11,7 @@ import ( "net/http" "os" "path/filepath" + "time" "github.com/gorilla/sessions" ) @@ -30,6 +31,22 @@ type AuthCookie struct { PasswordSecret string } +// Constructor AuthCookie +func NewAuthCookie(tpl *template.Template, sessionSecret, passwordSecret string, data *os.File) *AuthCookie { + app := &AuthCookie{ + Templates: tpl, + Store: sessions.NewCookieStore([]byte(sessionSecret)), + DataDir: data, + PasswordSecret: passwordSecret, + } + app.Store.Options = &sessions.Options{ + Secure: true, + HttpOnly: true, + MaxAge: int((24 * time.Hour) / time.Second), + } + return app +} + // Verify Username func (app *AuthCookie) VerifyUsername(username string) error { if username == "" { diff --git a/photoblog/main.go b/photoblog/main.go index 6e08f2f..ea64348 100644 --- a/photoblog/main.go +++ b/photoblog/main.go @@ -11,7 +11,7 @@ import ( "meutel.net/meutel/go-examples/photoblog/admin" "meutel.net/meutel/go-examples/photoblog/photo" - "github.com/gorilla/sessions" + "github.com/gorilla/context" ) type PhotoBlogConfig struct { @@ -58,12 +58,7 @@ func main() { } app := photo.PhotoBlog{ - admin.AuthCookie{ - Templates: tpl, - Store: sessions.NewCookieStore([]byte(conf.SessionSecret)), - DataDir: data, - PasswordSecret: conf.PasswordSecret, - }, + *admin.NewAuthCookie(tpl, conf.SessionSecret, conf.PasswordSecret, data), } http.HandleFunc("/", func(res http.ResponseWriter, req *http.Request) { @@ -76,5 +71,5 @@ func main() { http.HandleFunc("/upload", app.UploadPage) http.HandleFunc("/login", app.LoginPage) http.HandleFunc("/logout", app.LogoutPage) - http.ListenAndServeTLS(":9443", "../cert.pem", "../key.pem", nil) + http.ListenAndServeTLS(":9443", "../cert.pem", "../key.pem", context.ClearHandler(http.DefaultServeMux)) }