Skip to content

Commit

Permalink
bugfix: correctly set a defaultMaxAge when MaxAge isn't called (#120)
Browse files Browse the repository at this point in the history
  • Loading branch information
elithrar authored Aug 26, 2019
1 parent a7479e7 commit 7b29b05
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 1 deletion.
6 changes: 5 additions & 1 deletion options.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,8 @@ import (
type Option func(*csrf)

// MaxAge sets the maximum age (in seconds) of a CSRF token's underlying cookie.
// Defaults to 12 hours.
// Defaults to 12 hours. Call csrf.MaxAge(0) to explicitly set session-only
// cookies.
func MaxAge(age int) Option {
return func(cs *csrf) {
cs.opts.MaxAge = age
Expand Down Expand Up @@ -131,6 +132,9 @@ func parseOptions(h http.Handler, opts ...Option) *csrf {
cs.opts.Secure = true
cs.opts.HttpOnly = true

// Default; only override this if the package user explicitly calls MaxAge(0)
cs.opts.MaxAge = defaultAge

// Range over each options function and apply it
// to our csrf type to configure it. Options functions are
// applied in order, with any conflicting options overriding
Expand Down
23 changes: 23 additions & 0 deletions options_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -71,3 +71,26 @@ func TestOptions(t *testing.T) {
cs.opts.CookieName, name)
}
}

func TestMaxAge(t *testing.T) {
t.Run("Ensure the default MaxAge is applied", func(t *testing.T) {
handler := Protect(testKey)(nil)
csrf := handler.(*csrf)
cs := csrf.st.(*cookieStore)

if cs.maxAge != defaultAge {
t.Fatalf("default maxAge not applied: got %d (want %d)", cs.maxAge, defaultAge)
}
})

t.Run("Support an explicit MaxAge of 0 (session-only)", func(t *testing.T) {
handler := Protect(testKey, MaxAge(0))(nil)
csrf := handler.(*csrf)
cs := csrf.st.(*cookieStore)

if cs.maxAge != 0 {
t.Fatalf("zero (0) maxAge not applied: got %d (want %d)", cs.maxAge, 0)
}
})

}

0 comments on commit 7b29b05

Please sign in to comment.