package auth import ( "bytes" "errors" "html/template" "io/ioutil" "net/http" "net/http/httptest" "strings" "testing" "gopkg.in/authboss.v0" "gopkg.in/authboss.v0/internal/mocks" ) func testSetup() (a *Auth, s *mocks.MockStorer) { s = mocks.NewMockStorer() ab := authboss.New() ab.LogWriter = ioutil.Discard ab.Layout = template.Must(template.New("").Parse(`{{template "authboss" .}}`)) ab.Storer = s ab.XSRFName = "xsrf" ab.XSRFMaker = func(_ http.ResponseWriter, _ *http.Request) string { return "xsrfvalue" } ab.PrimaryID = authboss.StoreUsername a = &Auth{} if err := a.Initialize(ab); err != nil { panic(err) } return a, s } func testRequest(ab *authboss.Authboss, method string, postFormValues ...string) (*authboss.Context, *httptest.ResponseRecorder, *http.Request, authboss.ClientStorerErr) { r, err := http.NewRequest(method, "", nil) if err != nil { panic(err) } sessionStorer := mocks.NewMockClientStorer() ctx := mocks.MockRequestContext(ab, postFormValues...) ctx.SessionStorer = sessionStorer return ctx, httptest.NewRecorder(), r, sessionStorer } func TestAuth(t *testing.T) { t.Parallel() a, _ := testSetup() storage := a.Storage() if storage[a.PrimaryID] != authboss.String { t.Error("Expected storage KV:", a.PrimaryID, authboss.String) } if storage[authboss.StorePassword] != authboss.String { t.Error("Expected storage KV:", authboss.StorePassword, authboss.String) } routes := a.Routes() if routes["/login"] == nil { t.Error("Expected route '/login' with handleFunc") } if routes["/logout"] == nil { t.Error("Expected route '/logout' with handleFunc") } } func TestAuth_loginHandlerFunc_GET(t *testing.T) { t.Parallel() a, _ := testSetup() ctx, w, r, _ := testRequest(a.Authboss, "GET") if err := a.loginHandlerFunc(ctx, w, r); err != nil { t.Error("Unexpected error:", err) } if w.Code != http.StatusOK { t.Error("Unexpected status:", w.Code) } body := w.Body.String() if !strings.Contains(body, "