package web
import (
"net/http"
"net/http/httptest"
"net/url"
"path/filepath"
"strings"
"testing"
"time"
"craftdesign.group/quarry/internal/api"
"craftdesign.group/quarry/internal/artifact"
"craftdesign.group/quarry/internal/index"
"craftdesign.group/quarry/internal/ops"
)
// signsInAnyone is a session plane whose login always succeeds, as the
// user it was built for.
type signsInAnyone struct{ fakeSessions }
func (s signsInAnyone) Login(string, string) (string, time.Time, bool) {
return "good", time.Now().Add(time.Hour), true
}
// With no destination, signing in lands on the front page, like
// everyone; an account that holds no repository has nothing to find
// there and lands on its own page, where the welcome is. A destination
// the person asked for is never replaced.
func TestSignInLandsOnTheFrontPageUnlessTheAccountHoldsNothing(t *testing.T) {
ix, err := index.Open(filepath.Join(t.TempDir(), "index.db"))
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { ix.Close() })
if err := ix.FoldNow([]index.Parsed{{Hash: strings.Repeat("55", 32), Art: &artifact.Artifact{
Type: artifact.Manifest, Date: "2026-08-19T09:00:00", User: "dan", Comment: "tip"}}}); err != nil {
t.Fatal(err)
}
r := ops.NewRegistry()
if err := api.RegisterAll(r, api.Deps{Version: "v",
Repos: api.NewRepos(map[string]*api.Repo{"alpha": {Chat: "alpha", Index: ix}}),
Accounts: stubAccts{grants: map[string]map[string]string{"dan": {"alpha": "write"}}},
}); err != nil {
t.Fatal(err)
}
for _, c := range []struct{ user, next, want string }{
{"dan", "", "/"},
{"eve", "", "/home"},
{"eve", "/", "/home"},
{"eve", "/tickets", "/tickets"},
{"dan", "/tickets", "/tickets"},
} {
h := HandlerWith(r, nil, nil, []Option{WithSessions(signsInAnyone{fakeSessions{user: c.user}})})
form := url.Values{"user": {c.user}, "password": {"pw"}, "next": {c.next}}
req := httptest.NewRequest("POST", "/login", strings.NewReader(form.Encode()))
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
w := httptest.NewRecorder()
h.ServeHTTP(w, req)
if w.Code != http.StatusSeeOther || w.Header().Get("Location") != c.want {
t.Errorf("FAIL: %s signing in with next=%q: %d to %q, want %s", c.user, c.next, w.Code, w.Header().Get("Location"), c.want)
}
}
if !t.Failed() {
t.Log("ok")
}
}