Exemplo n.º 1
0
func TestSession(t *testing.T) {
	a := New()

	store := cookie.NewCookieStore()
	a.Use(Session(store, nil))

	a.GET("/", func(c *C) {
		session := c.Sessions("test")
		session.Set("test1", "123")
		session.Set("test2", 123)

		c.String(200, "")
	})

	a.GET("/test", func(c *C) {
		session := c.Sessions("test")
		test1 := session.GetString("test1", "")
		test2 := session.GetInt("test2", 0)

		assert.Equal(t, "123", test1)
		assert.Equal(t, 123, test2)
		c.String(200, "")
	})

	req, _ := http.NewRequest("GET", "/", nil)
	w := httptest.NewRecorder()
	a.ServeHTTP(w, req)
	cookie := w.Header().Get("Set-Cookie")

	req, _ = http.NewRequest("GET", "/test", nil)
	req.Header.Set("Cookie", cookie)
	w = httptest.NewRecorder()
	a.ServeHTTP(w, req)
}
Exemplo n.º 2
0
func TestCSRFForm(t *testing.T) {
	assert := assert.New(t)

	token := ""

	a := ace.New()
	a.Session(cookie.NewCookieStore(), nil)
	CSRF(nil)

	a.GET("/", func(c *ace.C) {
		token = Token(c)
		c.JSON(200, nil)
	})

	a.POST("/", Validate, func(c *ace.C) {
		c.String(200, "passed")
	})

	r, _ := http.NewRequest("GET", "/", nil)
	w := httptest.NewRecorder()
	a.ServeHTTP(w, r)
	assert.NotEmpty(token)

	cookie := w.Header().Get("Set-Cookie")
	r, _ = http.NewRequest("POST", "/", nil)
	r.Header.Set("Cookie", cookie)
	r.ParseForm()
	r.PostForm.Set("csrf_token", token)
	w = httptest.NewRecorder()
	a.ServeHTTP(w, r)
	assert.Equal(200, w.Code)
	assert.Equal("passed", w.Body.String())

	cookie = w.Header().Get("Set-Cookie")
	r, _ = http.NewRequest("POST", "/", nil)
	r.Header.Set("Cookie", cookie)
	r.ParseForm()
	r.PostForm.Set("csrf_token", token)
	w = httptest.NewRecorder()
	a.ServeHTTP(w, r)
	assert.Equal(500, w.Code)
	assert.Equal("Invalid CSRF Token", w.Body.String())
}