func TestJWTParser(t *testing.T) { testApp := NewApp() testApp.UseFunc(Recoverer) testApp.UseFunc(URLParser) testApp.UseFunc(JWTParser) testApp.Get("/jwt", func(ctx context.Context, w ResponseWriter) context.Context { r := ctx.Value(key("id")).(string) for _, s := range ctx.Value(key("groups")).([]string) { r += s } w.Write([]byte(r)) return ctx }, GatePublic) server := httptest.NewServer(testApp) tests := []struct { id string groups []string expectation string }{ { // 0 id: "abc123", groups: []string{"admin", "developer", "founder"}, expectation: "abc123admindeveloperfounder", }, { // 1 id: "abc123", groups: []string{}, expectation: "abc123", }, { // 2 id: "", groups: []string{"public"}, expectation: "public", }, { // 3 id: "", groups: []string{}, expectation: "", }, } for i, test := range tests { token, err := cybele.GenerateJWT(map[string]interface{}{ "id": test.id, "groups": test.groups, }) tchek.UnintendedError(err) res := tchek.MakeRequest(server, "GET", "/jwt", token) fmt.Printf("\n") var body []byte body, err = ioutil.ReadAll(res.Body) tchek.UnintendedError(err) tchek.AreEqual(t, i, test.expectation, string(body)) } }
func TestAuthorizer(t *testing.T) { testApp := NewApp() testApp.UseFunc(Recoverer) testApp.UseFunc(URLParser) testApp.UseFunc(JWTParser) testApp.UseFunc(Authorizer) testApp.Get("/users", func(ctx context.Context, w ResponseWriter) context.Context { return ctx }, GateAdmin) testApp.Get("/comments", func(ctx context.Context, w ResponseWriter) context.Context { return ctx }, GatePublic) testApp.Post("/comments", func(ctx context.Context, w ResponseWriter) context.Context { return ctx }, GateNotBannedUser) server := httptest.NewServer(testApp) tests := []struct { method string url string id string groups []string expectedStatusCode int }{ { // 0 method: "GET", url: "/comments", id: "", groups: []string{}, expectedStatusCode: http.StatusOK, }, { // 1 method: "GET", url: "/comments", id: "abc123", groups: []string{"banned"}, expectedStatusCode: http.StatusOK, }, { // 2 method: "POST", url: "/comments", id: "abc123", groups: []string{"banned"}, expectedStatusCode: http.StatusForbidden, }, { // 4 method: "GET", url: "/users", id: "abc123", groups: []string{"admin"}, expectedStatusCode: http.StatusOK, }, } for i, test := range tests { var err error token := "" if test.id != "" { token, err = cybele.GenerateJWT(map[string]interface{}{ "id": test.id, "groups": test.groups, }) tchek.UnintendedError(err) } res := tchek.MakeRequest(server, test.method, test.url, token) fmt.Printf("\n") tchek.AreEqual(t, i, test.expectedStatusCode, res.StatusCode) } }