From 5f6134b39094f586e5635e45f4f3dd61427a57fe Mon Sep 17 00:00:00 2001 From: Umputun Date: Tue, 15 May 2018 12:14:10 -0500 Subject: [PATCH] add test for admin-only auth --- app/rest/auth/auth_test.go | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/app/rest/auth/auth_test.go b/app/rest/auth/auth_test.go index 839e0bb3..51a6e527 100644 --- a/app/rest/auth/auth_test.go +++ b/app/rest/auth/auth_test.go @@ -70,6 +70,31 @@ func TestAuthNotRequired(t *testing.T) { assert.Equal(t, 201, resp.StatusCode, "wrong auth creds") } +func TestAdminRequired(t *testing.T) { + store := mockStore{} + a := Authenticator{SessionStore: &store, DevPasswd: "123456"} + router := chi.NewRouter() + router.With(a.Auth(true), a.AdminOnly).Get("/auth", func(w http.ResponseWriter, r *http.Request) { + w.WriteHeader(201) + }) + server := httptest.NewServer(router) + defer server.Close() + + client := &http.Client{Timeout: 1 * time.Second} + req, err := http.NewRequest("GET", server.URL+"/auth", nil) + req.Header.Add("Authorization", "Basic "+basicAuth("dev", "123456")) + resp, err := client.Do(req) + require.NoError(t, err) + assert.Equal(t, 201, resp.StatusCode, "valid auth user, admin") + + devUser.Admin = false + req, err = http.NewRequest("GET", server.URL+"/auth", nil) + req.Header.Add("Authorization", "Basic "+basicAuth("dev", "123456")) + resp, err = client.Do(req) + require.NoError(t, err) + assert.Equal(t, 403, resp.StatusCode, "valid auth user, not admin") + +} func basicAuth(username, password string) string { auth := username + ":" + password return base64.StdEncoding.EncodeToString([]byte(auth))