Phase 10, part 2: the first owner, from a one-time setup link

A new server prints a link to create its owner (supermarket setup-link
makes another); until it's used, every page says the setup isn't
finished. One-time links (schema 33) are kept as hashes and used up in
one statement; resets and invitations will use them too. The server
edition opens Postgres.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-25 08:53:14 -07:00
co-authored by Claude Opus 5.5
parent 96404a3580
commit 72455438c9
16 changed files with 553 additions and 10 deletions
+10 -1
View File
@@ -24,7 +24,7 @@ import (
// viewer is who a request comes from.
type viewer struct {
User *users.User // nil on the local edition
User *users.User // nil on the local edition
Member users.Membership
Session *users.Session // nil on the local edition
}
@@ -99,6 +99,15 @@ func (s *Server) sessions(next http.Handler) http.Handler {
next.ServeHTTP(w, r.WithContext(context.WithValue(r.Context(), viewerKey, localOwner)))
return
}
if !publicPath(r.URL.Path) || r.URL.Path == "/signin" {
if done, err := s.hasOwner(); err != nil {
s.serverError(w, err)
return
} else if !done {
s.setupUnfinished(w, r)
return
}
}
v, err := s.lookupSession(r)
if err != nil && !errors.Is(err, users.ErrNoSession) {
s.serverError(w, err)
+1 -1
View File
@@ -154,6 +154,7 @@ func TestAddCSRF(t *testing.T) {
func TestServerEditionNeedsSignIn(t *testing.T) {
s, h := newServerEdition(t)
owner := addUser(t, s, "owner@example.com", users.Owner, nil)
// Not signed in: pages lead to the sign-in page; what's public stays so.
rec := do(h, http.MethodGet, "/seo/check?site=0", nil, nil)
if rec.Code != http.StatusSeeOther || rec.Header().Get("Location") != "/signin?next=%2Fseo%2Fcheck%3Fsite%3D0" {
@@ -175,7 +176,6 @@ func TestServerEditionNeedsSignIn(t *testing.T) {
}
// Signed in.
owner := addUser(t, s, "owner@example.com", users.Owner, nil)
c := sessionFor(t, s, owner)
if rec := as(h, c, http.MethodGet, "/settings/profile", nil); rec.Code != http.StatusOK {
t.Errorf("signed in: %d", rec.Code)
+15 -5
View File
@@ -20,6 +20,7 @@ import (
"supermarket/internal/jobs"
"supermarket/internal/storage"
"sync"
"sync/atomic"
"time"
"unicode"
"unicode/utf8"
@@ -67,8 +68,9 @@ type Server struct {
pages map[string]*template.Template
mu sync.Mutex
jobsOnce sync.Once
mu sync.Mutex
jobsOnce sync.Once
setupDone atomic.Bool // the team has its owner (server edition)
// Reddit: an app-only token for reading rules before sign-in, and the
// account's recent posts for the warnings.
@@ -135,6 +137,10 @@ func (s *Server) Handler() (http.Handler, error) {
mux.HandleFunc("GET /{$}", s.dashboard)
// Signing in (the server edition).
mux.HandleFunc("GET /setup/{token}", s.setupPage)
mux.HandleFunc("POST /setup/{token}", s.setupSave)
mux.HandleFunc("GET /search", s.searchPage)
mux.HandleFunc("GET /market", s.inventoryList)
@@ -511,6 +517,7 @@ type page struct {
NewProspects int // companies and people waiting for review, shown in the menu
Drafts int // outreach drafts waiting, shown in the menu
Bare bool // no sidebar: pages before signing in
CSRF string // the form token, for htmx (app.js)
Viewer *viewer // who's looking
}
@@ -560,9 +567,11 @@ func (s *Server) render(w http.ResponseWriter, r *http.Request, name string, p p
return
}
p.Version = s.Version
p.Inbox = s.inboxCount()
p.NewProspects = s.newProspects()
p.Drafts = s.outreachDrafts()
if !p.Bare {
p.Inbox = s.inboxCount()
p.NewProspects = s.newProspects()
p.Drafts = s.outreachDrafts()
}
if p.Flash == "" {
p.Flash = flashText(r.URL.Query())
}
@@ -599,6 +608,7 @@ func (s *Server) fragment(w http.ResponseWriter, r *http.Request, page, name str
// Messages shown after a redirect, by code, so no user text is reflected.
var flashes = map[string]string{
"saved": "Saved.",
"welcome": "Welcome: you're the owner. Start with the company's profile.",
"deleted": "Deleted.",
"x-connected": "X is connected.",
"li-connected": "LinkedIn is connected.",
+134
View File
@@ -0,0 +1,134 @@
package web
import (
"errors"
"net/http"
"strings"
"time"
"supermarket/internal/users"
)
// The first owner. A new server has no users: its start-up log prints a
// one-time link (also `supermarket setup-link`), and whoever opens it
// creates the owner. Until then, every page says the setup isn't finished.
// hasOwner says whether the setup is finished.
func (s *Server) hasOwner() (bool, error) {
if s.setupDone.Load() {
return true, nil
}
ok, err := users.HasOwner(s.DB, users.Team)
if ok {
s.setupDone.Store(true)
}
return ok, err
}
// setupForm is the setup page's form.
type setupForm struct {
Token, Email, Name string
Problems []string
}
func (s *Server) setupPage(w http.ResponseWriter, r *http.Request) {
if !s.signsIn() {
http.NotFound(w, r)
return
}
if done, err := s.hasOwner(); err != nil {
s.serverError(w, err)
return
} else if done {
http.Redirect(w, r, "/signin", http.StatusSeeOther)
return
}
token := r.PathValue("token")
if _, err := users.PeekLink(s.DB, token, users.SetupLink, time.Now()); err != nil {
s.setupExpired(w, r, err)
return
}
s.render(w, r, "setup", page{Title: "Set up Supermarket", Bare: true, Data: setupForm{Token: token}})
}
func (s *Server) setupExpired(w http.ResponseWriter, r *http.Request, err error) {
if !errors.Is(err, users.ErrBadLink) {
s.serverError(w, err)
return
}
w.WriteHeader(http.StatusNotFound)
s.render(w, r, "setup", page{Title: "Set up Supermarket", Bare: true, Data: setupForm{}})
}
func (s *Server) setupSave(w http.ResponseWriter, r *http.Request) {
if !s.signsIn() {
http.NotFound(w, r)
return
}
if done, err := s.hasOwner(); err != nil {
s.serverError(w, err)
return
} else if done {
http.Redirect(w, r, "/signin", http.StatusSeeOther)
return
}
token := r.PathValue("token")
f := setupForm{Token: token, Email: strings.TrimSpace(r.PostFormValue("email")), Name: strings.TrimSpace(r.PostFormValue("name"))}
pw := r.PostFormValue("password")
email, err := users.NormalEmail(f.Email)
if err != nil {
f.Problems = append(f.Problems, "Give your email address: you sign in with it.")
}
if f.Name == "" {
f.Problems = append(f.Problems, "Give your name.")
}
if err := users.CheckNewPassword(pw, f.Email); err != nil {
f.Problems = append(f.Problems, sentence(err.Error())+".")
} else if pw != r.PostFormValue("password2") {
f.Problems = append(f.Problems, "The two passwords aren't the same.")
}
if len(f.Problems) > 0 {
if _, err := users.PeekLink(s.DB, token, users.SetupLink, time.Now()); err != nil {
s.setupExpired(w, r, err)
return
}
w.WriteHeader(http.StatusUnprocessableEntity)
s.render(w, r, "setup", page{Title: "Set up Supermarket", Bare: true, Data: f})
return
}
now := time.Now()
if _, err := users.UseLink(s.DB, token, users.SetupLink, now); err != nil {
s.setupExpired(w, r, err)
return
}
u := &users.User{Email: email, Name: f.Name, Status: users.Active}
if err := users.Create(s.DB, u, now); err != nil {
s.serverError(w, err)
return
}
if err := users.SetPassword(s.DB, u, pw); err != nil {
s.serverError(w, err)
return
}
if err := users.Join(s.DB, users.Team, u.ID, users.Owner, nil, now); err != nil {
s.serverError(w, err)
return
}
s.setupDone.Store(true)
s.Log.Info("setup: the owner is created", "email", u.Email)
if err := s.startSession(w, r, u); err != nil {
s.serverError(w, err)
return
}
redirect(w, r, "/settings/profile", "welcome")
}
// setupUnfinished is every page's answer until the owner is created.
func (s *Server) setupUnfinished(w http.ResponseWriter, r *http.Request) {
if r.Header.Get("HX-Request") != "" || !safeMethod(r.Method) {
http.Error(w, "Supermarket isn't set up yet.", http.StatusServiceUnavailable)
return
}
w.WriteHeader(http.StatusServiceUnavailable)
s.render(w, r, "setup-unfinished", page{Title: "Not set up yet", Bare: true})
}
+100
View File
@@ -0,0 +1,100 @@
package web
import (
"net/http"
"net/url"
"strings"
"testing"
"time"
"supermarket/internal/users"
)
func TestSetup(t *testing.T) {
s, h := newServerEdition(t)
// Before the owner, every page says so; what's public still works.
for _, p := range []string{"/", "/seo/check", "/signin"} {
rec := do(h, http.MethodGet, p, nil, nil)
if rec.Code != http.StatusServiceUnavailable || !strings.Contains(rec.Body.String(), "isn't set up yet") {
t.Errorf("%s: %d", p, rec.Code)
}
}
if rec := do(h, http.MethodGet, "/healthz", nil, nil); rec.Code != http.StatusOK {
t.Errorf("healthz: %d", rec.Code)
}
// A made-up link doesn't work.
if rec := do(h, http.MethodGet, "/setup/made-up", nil, nil); rec.Code != http.StatusNotFound || !strings.Contains(rec.Body.String(), "doesn't work") {
t.Errorf("made-up link: %d", rec.Code)
}
old, err := users.NewLink(s.DB, users.SetupLink, 0, time.Now())
if err != nil {
t.Fatal(err)
}
token, _ := users.NewLink(s.DB, users.SetupLink, 0, time.Now()) // replaces it
if rec := do(h, http.MethodGet, "/setup/"+old, nil, nil); rec.Code != http.StatusNotFound {
t.Errorf("replaced link: %d", rec.Code)
}
rec := do(h, http.MethodGet, "/setup/"+token, nil, nil)
if rec.Code != http.StatusOK || !strings.Contains(rec.Body.String(), "Create the owner") || strings.Contains(rec.Body.String(), `class="sidebar"`) {
t.Fatalf("setup page: %d", rec.Code)
}
// Mistakes are shown, and the link still works.
form := url.Values{"email": {"Owner@Example.com"}, "name": {"Olu"}, "password": {"short"}, "password2": {"short"}}
rec = postForm(h, "/setup/"+token, form)
if rec.Code != http.StatusUnprocessableEntity || !strings.Contains(rec.Body.String(), "at least 10 characters") || !strings.Contains(rec.Body.String(), `value="Owner@Example.com"`) {
t.Errorf("short password: %d %s", rec.Code, rec.Body.String())
}
form.Set("password", "a long enough one")
form.Set("password2", "a long enough one!")
if rec = postForm(h, "/setup/"+token, form); rec.Code != http.StatusUnprocessableEntity || !strings.Contains(rec.Body.String(), "passwords aren") {
t.Errorf("mismatch: %d", rec.Code)
}
form.Set("password2", "a long enough one")
rec = postForm(h, "/setup/"+token, form)
if rec.Code != http.StatusSeeOther || rec.Header().Get("Location") != "/settings/profile?msg=welcome" {
t.Fatalf("setup: %d %s %s", rec.Code, rec.Header().Get("Location"), rec.Body.String())
}
var session *http.Cookie
for _, c := range rec.Result().Cookies() {
if c.Name == sessionCookie {
session = c
}
}
if session == nil {
t.Fatal("not signed in")
}
u, err := users.ByEmail(s.DB, "owner@example.com")
if err != nil || u.Status != users.Active || !users.CheckPassword(u, "a long enough one") || u.SignedIn.IsZero() {
t.Fatalf("owner: %+v %v", u, err)
}
if m, _ := users.MembershipOf(s.DB, users.Team, u.ID); m.Role != users.Owner {
t.Errorf("role %s", m.Role)
}
if rec := as(h, session, http.MethodGet, "/settings/profile?msg=welcome", nil); rec.Code != http.StatusOK || !strings.Contains(rec.Body.String(), "Start with the company") {
t.Errorf("profile after setup: %d", rec.Code)
}
// The link is used up, and setting up again leads to signing in.
if rec := postForm(h, "/setup/"+token, form); rec.Code != http.StatusSeeOther || rec.Header().Get("Location") != "/signin" {
t.Errorf("second use: %d %s", rec.Code, rec.Header().Get("Location"))
}
if n, _ := users.Count(s.DB); n != 1 {
t.Errorf("%d users", n)
}
// Not signed in: to the sign-in page, no longer the setup notice.
if rec := do(h, http.MethodGet, "/seo/check", nil, nil); rec.Code != http.StatusSeeOther {
t.Errorf("after setup, not signed in: %d", rec.Code)
}
}
func TestSetupIsServerOnly(t *testing.T) {
s, h := newTestServer(t, nil)
token, _ := users.NewLink(s.DB, users.SetupLink, 0, time.Now())
if rec := do(h, http.MethodGet, "/setup/"+token, nil, nil); rec.Code != http.StatusNotFound {
t.Errorf("local: %d", rec.Code)
}
}
+10
View File
@@ -486,3 +486,13 @@ svg.line-chart line.axis { stroke: hsl(var(--border)); }
dl.facts { display: grid; grid-template-columns: max-content 1fr; gap: 0.6rem 1.2rem; margin: 0.5rem 0 0.8rem; }
dl.facts dt { font-weight: 600; color: hsl(var(--muted-foreground)); }
dl.facts dd { margin: 0; overflow-wrap: anywhere; }
/* Pages before signing in (setup, sign-in, invitations): no sidebar, one
narrow column. */
.bare-shell { min-height: 100vh; display: flex; flex-direction: column; align-items: center; padding: 3rem 1rem 1.5rem; background: hsl(var(--sidebar)); }
.bare-shell .brand { padding: 0 0 1.25rem; font-size: 1.15rem; }
.bare-main { width: 100%; max-width: 26rem; }
.bare-main h1 { font-size: 1.35rem; margin: 0 0 0.35rem; }
.bare-main .card { padding: 1.5rem; }
.bare-main button[type="submit"] { width: 100%; }
.bare-shell .version { margin-top: auto; padding-top: 2rem; font-size: 0.8rem; color: hsl(var(--muted-foreground)); }
+12
View File
@@ -14,6 +14,17 @@
<script src="/static/app.js" defer></script>
</head>
<body>
{{if .Bare}}
<div class="bare-shell">
<p class="brand"><img class="logo" src="/static/logo.png" alt="" width="28" height="28">Supermarket</p>
<main class="bare-main">
{{if .Flash}}<p class="flash" role="status">{{.Flash}}</p>{{end}}
{{if .Error}}<p class="error" role="alert">{{.Error}}</p>{{end}}
{{template "content" .}}
</main>
<p class="version">Supermarket {{.Version}}</p>
</div>
{{else}}
<div class="shell">
<aside class="sidebar" id="sidebar">
<a class="brand" href="/"><img class="logo" src="/static/logo.png" alt="" width="28" height="28">Supermarket</a>
@@ -111,6 +122,7 @@
</main>
</div>
</div>
{{end}}
</body>
</html>
@@ -0,0 +1,8 @@
{{define "content"}}
<h1>Supermarket isn't set up yet</h1>
<section class="card">
<p>Its owner hasn't been created. Whoever installed it opens the setup link from the start-up log, which begins <code>/setup/</code>.</p>
<p class="help">To make a new link, run this on the server:</p>
<pre>docker compose exec supermarket supermarket setup-link</pre>
</section>
{{end}}
+23
View File
@@ -0,0 +1,23 @@
{{define "content"}}{{with .Data}}
{{if .Token}}
<h1>Set up Supermarket</h1>
<p class="lede">You're its owner: you can do everything, and invite the rest of the team. Then fill in the company's profile.</p>
{{if .Problems}}<div class="error" role="alert">{{range .Problems}}<p>{{.}}</p>{{end}}</div>{{end}}
<form class="card" method="post" action="/setup/{{.Token}}">
<label>Your email address <input type="email" name="email" value="{{.Email}}" autocomplete="username" required autofocus></label>
<label>Your name <input name="name" value="{{.Name}}" autocomplete="name" required></label>
<label>Choose a password <input type="password" name="password" autocomplete="new-password" minlength="10" required>
<span class="help">At least 10 characters. A few unrelated words make a good one.</span></label>
<label>The same password again <input type="password" name="password2" autocomplete="new-password" minlength="10" required></label>
<button type="submit">Create the owner</button>
</form>
{{else}}
<h1>This setup link doesn't work</h1>
<section class="card">
<p>It has expired (a setup link lasts a day), was already used, or was replaced by a newer one.</p>
<p class="help">For a new link, run this on the server, and open the address it prints:</p>
<pre>docker compose exec supermarket supermarket setup-link</pre>
<p class="help">If Supermarket is already set up, <a href="/signin">sign in</a>.</p>
</section>
{{end}}
{{end}}{{end}}