Files

83 lines
2.3 KiB
Go

package server
import (
"bytes"
"net/http"
"net/http/httptest"
"strings"
"testing"
"agent-system-backend/internal/store"
)
// bootAdmin creates an administrator and completes the initial forced change.
func bootAdmin(t *testing.T, h http.Handler, st *store.Store) string {
t.Helper()
bootHash, err := store.HashPassword("boot-pass-00")
if err != nil {
t.Fatal(err)
}
if err := st.CreateAccount("admin", "", bootHash, true); err != nil {
t.Fatal(err)
}
req := httptest.NewRequest("POST", "/api/auth/login", strings.NewReader(`{"owner":"admin","password":"boot-pass-00"}`))
req.Header.Set("Content-Type", "application/json")
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != http.StatusOK {
t.Fatalf("boot login: %d %s", rec.Code, rec.Body.String())
}
tok := cookieOf(rec)
if tok == "" {
t.Fatal("missing session cookie")
}
req = httptest.NewRequest("POST", "/api/auth/password", strings.NewReader(`{"current":"boot-pass-00","next":"admin-final-9"}`))
req.AddCookie(&http.Cookie{Name: SessionCookie, Value: tok})
req.Header.Set("Content-Type", "application/json")
rec = httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != http.StatusOK {
t.Fatalf("boot set password: %d %s", rec.Code, rec.Body.String())
}
req = httptest.NewRequest("POST", "/api/auth/login", strings.NewReader(`{"owner":"admin","password":"admin-final-9"}`))
req.Header.Set("Content-Type", "application/json")
rec = httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != http.StatusOK {
t.Fatalf("relogin: %d %s", rec.Code, rec.Body.String())
}
return cookieOf(rec)
}
func cookieOf(rec *httptest.ResponseRecorder) string {
for _, ck := range rec.Result().Cookies() {
if ck.Name == SessionCookie {
return ck.Value
}
}
return ""
}
func reqWithCookie(method, path, body, cookie string) *http.Request {
var rdr *bytes.Reader
if body != "" {
rdr = bytes.NewReader([]byte(body))
} else {
rdr = bytes.NewReader(nil)
}
req := httptest.NewRequest(method, path, rdr)
if cookie != "" {
req.AddCookie(&http.Cookie{Name: SessionCookie, Value: cookie})
}
if body != "" {
req.Header.Set("Content-Type", "application/json")
}
return req
}
func do(h http.Handler, method, path, body, cookie string) *httptest.ResponseRecorder {
rec := httptest.NewRecorder()
h.ServeHTTP(rec, reqWithCookie(method, path, body, cookie))
return rec
}