package auth import ( "errors" "html/template" "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() authboss.Cfg = authboss.NewConfig() authboss.Cfg.Layout = template.Must(template.New("").Parse(`{{template "authboss" .}}`)) authboss.Cfg.Storer = s authboss.Cfg.XSRFName = "xsrf" authboss.Cfg.XSRFMaker = func(_ http.ResponseWriter, _ *http.Request) string { return "xsrfvalue" } authboss.Cfg.PrimaryID = authboss.StoreUsername a = &Auth{} if err := a.Initialize(); err != nil { panic(err) } return a, s } func testRequest(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(postFormValues...) ctx.SessionStorer = sessionStorer return ctx, httptest.NewRecorder(), r, sessionStorer } func TestAuth(t *testing.T) { a, _ := testSetup() storage := a.Storage() if storage[authboss.Cfg.PrimaryID] != authboss.String { t.Error("Expected storage KV:", authboss.Cfg.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_RedirectsWhenHalfAuthed(t *testing.T) { a, _ := testSetup() ctx, w, r, sessionStore := testRequest("GET") sessionStore.Put(authboss.SessionKey, "a") sessionStore.Put(authboss.SessionHalfAuthKey, "false") authboss.Cfg.AuthLoginSuccessRoute = "/dashboard" if err := a.loginHandlerFunc(ctx, w, r); err != nil { t.Error("Unexpeced error:", err) } if w.Code != http.StatusFound { t.Error("Unexpcted status:", w.Code) } loc := w.Header().Get("Location") if loc != authboss.Cfg.AuthLoginSuccessRoute { t.Error("Unexpected redirect:", loc) } } func TestAuth_loginHandlerFunc_GET(t *testing.T) { a, _ := testSetup() ctx, w, r, _ := testRequest("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, "