Secure session cookie

This commit is contained in:
Meutel 2017-07-30 10:01:23 +02:00
parent 5088b4b531
commit f0bf40f412
2 changed files with 20 additions and 8 deletions

View File

@ -11,6 +11,7 @@ import (
"net/http" "net/http"
"os" "os"
"path/filepath" "path/filepath"
"time"
"github.com/gorilla/sessions" "github.com/gorilla/sessions"
) )
@ -30,6 +31,22 @@ type AuthCookie struct {
PasswordSecret string 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 // Verify Username
func (app *AuthCookie) VerifyUsername(username string) error { func (app *AuthCookie) VerifyUsername(username string) error {
if username == "" { if username == "" {

View File

@ -11,7 +11,7 @@ import (
"meutel.net/meutel/go-examples/photoblog/admin" "meutel.net/meutel/go-examples/photoblog/admin"
"meutel.net/meutel/go-examples/photoblog/photo" "meutel.net/meutel/go-examples/photoblog/photo"
"github.com/gorilla/sessions" "github.com/gorilla/context"
) )
type PhotoBlogConfig struct { type PhotoBlogConfig struct {
@ -58,12 +58,7 @@ func main() {
} }
app := photo.PhotoBlog{ app := photo.PhotoBlog{
admin.AuthCookie{ *admin.NewAuthCookie(tpl, conf.SessionSecret, conf.PasswordSecret, data),
Templates: tpl,
Store: sessions.NewCookieStore([]byte(conf.SessionSecret)),
DataDir: data,
PasswordSecret: conf.PasswordSecret,
},
} }
http.HandleFunc("/", func(res http.ResponseWriter, req *http.Request) { http.HandleFunc("/", func(res http.ResponseWriter, req *http.Request) {
@ -76,5 +71,5 @@ func main() {
http.HandleFunc("/upload", app.UploadPage) http.HandleFunc("/upload", app.UploadPage)
http.HandleFunc("/login", app.LoginPage) http.HandleFunc("/login", app.LoginPage)
http.HandleFunc("/logout", app.LogoutPage) http.HandleFunc("/logout", app.LogoutPage)
http.ListenAndServeTLS(":9443", "../cert.pem", "../key.pem", nil) http.ListenAndServeTLS(":9443", "../cert.pem", "../key.pem", context.ClearHandler(http.DefaultServeMux))
} }