示例#1
0
func TestCanRead(t *testing.T) {
	setup()
	defer tearDown()

	// Create article with author
	author := &testuser{}
	author.Username = "******"
	db.Create(author)

	art := &article{}
	art.Author = author
	art.Permission = goal.Permission{
		Read:  `["admin", "ceo"]`,
		Write: `["admin", "ceo"]`,
	}
	art.Title = "Top Secret"

	err := db.Create(art).Error
	if err != nil {
		fmt.Println("error create article ", err)
	}

	res := httptest.NewRecorder()

	var json = []byte(`{"username":"******", "password": "******"}`)
	req, _ := http.NewRequest("POST", "/auth/register", bytes.NewBuffer(json))

	goal.SharedAPI().Mux().ServeHTTP(res, req)

	// Make sure cookies is set properly
	hdr := res.Header()
	cookies, ok := hdr["Set-Cookie"]
	if !ok || len(cookies) != 1 {
		t.Fatal("No cookies. Header:", hdr)
	}

	artURL := fmt.Sprint(server.URL, "/article/", art.ID)

	// Make sure user is the same with current user from session
	nextReq, _ := http.NewRequest("GET", artURL, nil)
	nextReq.Header.Add("Cookie", cookies[0])

	// Get response
	client := &http.Client{}
	resp, err := client.Do(nextReq)
	resp.Body.Close()

	if resp.StatusCode != 403 || err != nil {
		t.Error("Request should be unauthorized because thomasdao doesn't have admin role")
	}
}
示例#2
0
func TestAuth(t *testing.T) {
	setup()
	defer tearDown()

	recorder := httptest.NewRecorder()

	var json = []byte(`{"username":"******", "password": "******"}`)
	req, _ := http.NewRequest("POST", "/auth/register", bytes.NewBuffer(json))
	goal.SharedAPI().Mux().ServeHTTP(recorder, req)

	// Make sure cookies is set properly
	hdr := recorder.Header()
	cookies, ok := hdr["Set-Cookie"]
	if !ok || len(cookies) != 1 {
		t.Fatal("No cookies. Header:", hdr)
	}

	// Make sure db has one object
	var user testuser
	err := db.Where("username = ?", "thomasdao").First(&user).Error
	if err != nil {
		t.Error("Fail to save object to database")
		return
	}

	// Make sure user is the same with current user from session
	logoutReq, _ := http.NewRequest("POST", "/auth/logout", nil)
	logoutReq.Header.Add("Cookie", cookies[0])
	currentUser, err := goal.GetCurrentUser(logoutReq)
	if err != nil {
		t.Error(err)
	}

	if !reflect.DeepEqual(&user, currentUser) {
		t.Error("Get invalid current user from request")
	}

	// Logout
	recorder = httptest.NewRecorder()
	goal.SharedAPI().Mux().ServeHTTP(recorder, logoutReq)

	// Make sure cookies is cleared after logout
	hdr = recorder.Header()
	cookies, ok = hdr["Set-Cookie"]
	if ok || len(cookies) == 1 {
		t.Fatal("Cookies should be cleared after logout")
	}

	// Test login
	loginReq, _ := http.NewRequest("POST", "/auth/login", bytes.NewBuffer(json))

	// Login
	recorder = httptest.NewRecorder()
	goal.SharedAPI().Mux().ServeHTTP(recorder, loginReq)

	// Make sure cookies is set properly
	hdr = recorder.Header()
	cookies, ok = hdr["Set-Cookie"]
	if !ok || len(cookies) != 1 {
		t.Fatal("No cookies. Header:", hdr)
	}

}