Skip to content

Commit

Permalink
Provides functionality to set the MaxAge on the underlying securecook…
Browse files Browse the repository at this point in the history
…ie Codecs.

- Addresses gorilla#48
  • Loading branch information
elithrar committed Aug 11, 2015
1 parent 132cb5b commit ab250e0
Showing 1 changed file with 36 additions and 2 deletions.
38 changes: 36 additions & 2 deletions store.go
Original file line number Diff line number Diff line change
Expand Up @@ -51,13 +51,16 @@ type Store interface {
// Use the convenience function securecookie.GenerateRandomKey() to create
// strong keys.
func NewCookieStore(keyPairs ...[]byte) *CookieStore {
return &CookieStore{
cs := &CookieStore{
Codecs: securecookie.CodecsFromPairs(keyPairs...),
Options: &Options{
Path: "/",
MaxAge: 86400 * 30,
},
}

cs.MaxAge(cs.Options.MaxAge)
return cs
}

// CookieStore stores sessions using secure cookies.
Expand Down Expand Up @@ -110,6 +113,20 @@ func (s *CookieStore) Save(r *http.Request, w http.ResponseWriter,
return nil
}

// MaxAge sets the maximum age for the store and the underlying cookie
// implementation. Individual sessions can be deleted by setting Options.MaxAge
// = -1 for that session.
func (s *CookieStore) MaxAge(age int) {
s.Options.MaxAge = age

// Set the maxAge for each securecookie instance.
for _, codec := range s.Codecs {
if sc, ok := codec.(*securecookie.SecureCookie); ok {
sc.MaxAge(age)
}
}
}

// FilesystemStore ------------------------------------------------------------

var fileMutex sync.RWMutex
Expand All @@ -124,14 +141,17 @@ func NewFilesystemStore(path string, keyPairs ...[]byte) *FilesystemStore {
if path == "" {
path = os.TempDir()
}
return &FilesystemStore{
fs := &FilesystemStore{
Codecs: securecookie.CodecsFromPairs(keyPairs...),
Options: &Options{
Path: "/",
MaxAge: 86400 * 30,
},
path: path,
}

fs.MaxAge(fs.Options.MaxAge)
return fs
}

// FilesystemStore stores sessions in the filesystem.
Expand Down Expand Up @@ -206,6 +226,20 @@ func (s *FilesystemStore) Save(r *http.Request, w http.ResponseWriter,
return nil
}

// MaxAge sets the maximum age for the store and the underlying cookie
// implementation. Individual sessions can be deleted by setting Options.MaxAge
// = -1 for that session.
func (s *FilesystemStore) MaxAge(age int) {
s.Options.MaxAge = age

// Set the maxAge for each securecookie instance.
for _, codec := range s.Codecs {
if sc, ok := codec.(*securecookie.SecureCookie); ok {
sc.MaxAge(age)
}
}
}

// save writes encoded session.Values to a file.
func (s *FilesystemStore) save(session *Session) error {
encoded, err := securecookie.EncodeMulti(session.Name(), session.Values,
Expand Down

0 comments on commit ab250e0

Please sign in to comment.