Example #1
0
func InitCsrf(authKey []byte, opts ...Option) *CsrfProtection {
	cs := parseOptions(nil, opts...)

	// Set the defaults if no options have been specified
	if cs.Opts.ErrorHandler == nil {
		cs.Opts.ErrorHandler = http.HandlerFunc(unauthorizedHandler)
	}

	if cs.Opts.MaxAge < 1 {
		// Default of 12 hours
		cs.Opts.MaxAge = defaultAge
	}

	if cs.Opts.FieldName == "" {
		cs.Opts.FieldName = fieldName
	}

	if cs.Opts.CookieName == "" {
		cs.Opts.CookieName = CookieName
	}

	if cs.Opts.RequestHeader == "" {
		cs.Opts.RequestHeader = headerName
	}

	// Create an authenticated securecookie instance.
	if cs.Sc == nil {
		cs.Sc = securecookie.New(authKey, nil)
		// Use JSON serialization (faster than one-off gob encoding)
		cs.Sc.SetSerializer(securecookie.JSONEncoder{})
		// Set the MaxAge of the underlying securecookie.
		cs.Sc.MaxAge(cs.Opts.MaxAge)
	}

	if cs.St == nil {
		// Default to the cookieStore
		cs.St = &cookieStore{
			name:     cs.Opts.CookieName,
			maxAge:   cs.Opts.MaxAge,
			secure:   cs.Opts.Secure,
			httpOnly: cs.Opts.HttpOnly,
			path:     cs.Opts.Path,
			domain:   cs.Opts.Domain,
			sc:       cs.Sc,
		}
	}

	return cs
}
Example #2
0
// TestCookieEncode tests that an invalid cookie store returns an encoding error.
func TestCookieEncode(t *testing.T) {
	var age = 3600

	// Test with a nil hash key
	sc := securecookie.New(nil, nil)
	sc.MaxAge(age)
	st := &cookieStore{CookieName, age, true, true, "", "", sc}

	rr := httptest.NewRecorder()

	err := st.Save(nil, rr)
	if err == nil {
		t.Fatal("cookiestore did not report an invalid hashkey on encode")
	}
}
Example #3
0
// TestCookieDecode tests that an invalid cookie store returns a decoding error.
func TestCookieDecode(t *testing.T) {
	r, err := http.NewRequest("GET", "/", nil)
	if err != nil {
		t.Fatal(err)
	}

	var age = 3600

	// Test with a nil hash key
	sc := securecookie.New(nil, nil)
	sc.MaxAge(age)
	st := &cookieStore{CookieName, age, true, true, "", "", sc}

	// Set a fake cookie value so r.Cookie passes.
	r.Header.Set("Cookie", fmt.Sprintf("%s=%s", CookieName, "notacookie"))

	_, err = st.Get(r)
	if err == nil {
		t.Fatal("cookiestore did not report an invalid hashkey on decode")
	}
}