-
Notifications
You must be signed in to change notification settings - Fork 4
/
access_control_test.go
84 lines (65 loc) · 1.97 KB
/
access_control_test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
package goal_test
import (
"bytes"
"fmt"
"net/http"
"net/http/httptest"
"reflect"
"testing"
"github.com/thomasdao/goal"
)
// Satisfy Roler interface
func (user *testuser) Roles() []string {
ownRole := fmt.Sprintf("testuser:%v", user.ID)
roles := []string{ownRole}
return roles
}
func (art *article) Get(w http.ResponseWriter, request *http.Request) (int, interface{}, error) {
return goal.Read(reflect.TypeOf(art), request)
}
func (art *article) Post(w http.ResponseWriter, request *http.Request) (int, interface{}, error) {
return goal.Create(reflect.TypeOf(art), request)
}
func (art *article) Query(w http.ResponseWriter, request *http.Request) (int, interface{}, error) {
return goal.HandleQuery(reflect.TypeOf(art), request)
}
func TestCanRead(t *testing.T) {
setup()
defer tearDown()
// Create article with author
author := &testuser{}
author.Username = "secret"
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":"thomasdao", "password": "something-secret"}`)
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")
}
}