arche / internal/archesrv/admin_test.go

commit 154431fd
  1package archesrv
  2
  3import (
  4	"fmt"
  5	"io"
  6	"net/http"
  7	"strings"
  8	"testing"
  9)
 10
 11func TestForgeServer_Admin_InvitesCRUD(t *testing.T) {
 12	s, ts := newTestServer(t)
 13	_, client := loginAsAdmin(t, s, ts)
 14
 15	resp, err := client.Get(ts.URL + "/admin/invites")
 16	if err != nil {
 17		t.Fatalf("GET /admin/invites: %v", err)
 18	}
 19	resp.Body.Close()
 20	if resp.StatusCode != http.StatusOK {
 21		t.Errorf("admin invites page: want 200, got %d", resp.StatusCode)
 22	}
 23
 24	resp2, err := client.PostForm(ts.URL+"/admin/invites", nil)
 25	if err != nil {
 26		t.Fatalf("POST /admin/invites: %v", err)
 27	}
 28	body2, _ := io.ReadAll(resp2.Body)
 29	resp2.Body.Close()
 30	if resp2.StatusCode != http.StatusOK {
 31		t.Errorf("create invite: want 200, got %d", resp2.StatusCode)
 32	}
 33	if !strings.Contains(string(body2), "/register?invite=") {
 34		t.Errorf("create invite: response should contain /register?invite= link")
 35	}
 36
 37	adminUser, _, _ := s.db.GetUserByName("admin")
 38	invites, err := s.db.ListInvites(adminUser.ID)
 39	if err != nil {
 40		t.Fatalf("ListInvites: %v", err)
 41	}
 42	if len(invites) == 0 {
 43		t.Fatal("expected at least one invite after POST")
 44	}
 45	inviteID := invites[0].ID
 46
 47	req, _ := http.NewRequest(http.MethodDelete,
 48		fmt.Sprintf("%s/admin/invites/%d", ts.URL, inviteID), nil)
 49	resp3, err := client.Do(req)
 50	if err != nil {
 51		t.Fatalf("DELETE invite: %v", err)
 52	}
 53	resp3.Body.Close()
 54	if resp3.StatusCode != http.StatusNoContent {
 55		t.Errorf("delete invite: want 204, got %d", resp3.StatusCode)
 56	}
 57
 58	remaining, _ := s.db.ListInvites(adminUser.ID)
 59	for _, inv := range remaining {
 60		if inv.ID == inviteID {
 61			t.Error("invite should be gone after DELETE")
 62		}
 63	}
 64}
 65
 66func TestForgeServer_Admin_NonAdminCannotAccessAdminRoutes(t *testing.T) {
 67	s, ts := newTestServer(t)
 68	s.db.CreateUser("admin", "adminpass", true) //nolint:errcheck
 69	s.db.CreateUser("alice", "pass", false)     //nolint:errcheck
 70
 71	aliceClient := loginAs(t, ts, "alice", "pass")
 72
 73	for _, path := range []string{
 74		"/admin/invites",
 75		"/admin/users",
 76	} {
 77		resp, err := aliceClient.Get(ts.URL + path)
 78		if err != nil {
 79			t.Fatalf("GET %s: %v", path, err)
 80		}
 81		resp.Body.Close()
 82		if resp.StatusCode < 400 {
 83			t.Errorf("%s: non-admin should get 4xx, got %d", path, resp.StatusCode)
 84		}
 85	}
 86}
 87
 88func TestForgeServer_Admin_UsersPage(t *testing.T) {
 89	s, ts := newTestServer(t)
 90	_, client := loginAsAdmin(t, s, ts)
 91
 92	resp, err := client.Get(ts.URL + "/admin/users")
 93	if err != nil {
 94		t.Fatalf("GET /admin/users: %v", err)
 95	}
 96	defer resp.Body.Close()
 97	if resp.StatusCode != http.StatusOK {
 98		t.Errorf("admin users page: want 200, got %d", resp.StatusCode)
 99	}
100}