Use store to define session default options

This commit is contained in:
wpetit 2019-05-13 09:09:28 +02:00
parent 7c00e0c8bf
commit 35c763a6c6
3 changed files with 11 additions and 24 deletions

View File

@ -9,16 +9,17 @@ import (
// CreateCookieSessionStore creates and returns a new cookie session store
// with random authentication and encryption keys
func CreateCookieSessionStore(authKeySize, encryptKeySize int) (sessions.Store, error) {
authenticationKey, err := generateRandomBytes(64)
func CreateCookieSessionStore(authKeySize, encryptKeySize int, defaultOptions *sessions.Options) (sessions.Store, error) {
authenticationKey, err := generateRandomBytes(authKeySize)
if err != nil {
return nil, errors.Wrap(err, "error while generating cookie authentication key")
}
encryptionKey, err := generateRandomBytes(32)
encryptionKey, err := generateRandomBytes(encryptKeySize)
if err != nil {
return nil, errors.Wrap(err, "error while generating cookie encryption key")
}
store := sessions.NewCookieStore(authenticationKey, encryptionKey)
store.Options = defaultOptions
return store, nil
}

View File

@ -7,9 +7,8 @@ import (
// ServiceProvider returns a service.Provider for the
// the gorilla session service implementation
func ServiceProvider(sessionName string, store sessions.Store, defaultOptions *sessions.Options) service.Provider {
sessionService := NewSessionService(sessionName, store, defaultOptions)
func ServiceProvider(sessionName string, store sessions.Store) service.Provider {
sessionService := NewSessionService(sessionName, store)
return func(container *service.Container) (interface{}, error) {
return sessionService, nil
}

View File

@ -13,9 +13,8 @@ import (
// SessionService is an implementation of service.Session
// based on the github.com/gorilla/sessions
type SessionService struct {
sessionName string
store sessions.Store
defaultOptions *sessions.Options
sessionName string
store sessions.Store
}
// Get returns a Session associated with the given HTTP request
@ -27,26 +26,14 @@ func (s *SessionService) Get(w http.ResponseWriter, r *http.Request) (session.Se
return nil, errors.Wrap(err, "error while retrieving the session from the request")
}
}
if err != nil {
defaultOptions := s.defaultOptionsCopy()
sess.Options = &defaultOptions
if err := sess.Save(r, w); err != nil {
return nil, errors.Wrap(err, "error while saving session")
}
}
return NewSession(sess), nil
}
func (s *SessionService) defaultOptionsCopy() sessions.Options {
return *s.defaultOptions
}
// NewSessionService returns a new SessionService backed
// by the given Store
func NewSessionService(sessionName string, store sessions.Store, defaultOptions *sessions.Options) *SessionService {
func NewSessionService(sessionName string, store sessions.Store) *SessionService {
return &SessionService{
sessionName: sessionName,
store: store,
defaultOptions: defaultOptions,
sessionName: sessionName,
store: store,
}
}