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:
@@ -2185,6 +2185,24 @@ This makes the server edition usable by a team. A commit after each part.
|
||||
- Sessions aren't exported (`supermarket export`); users and memberships
|
||||
are.
|
||||
|
||||
**Part 2 built 2026-11-25** on `phase10`.
|
||||
- Schema 33: `links`, one-time links (setup, password reset, invitation),
|
||||
kept as the hash of their token, each lasting its own time (a day, an
|
||||
hour, 7 days). A new link replaces the user's earlier one for the same
|
||||
purpose; using one is a single `DELETE … RETURNING`, so of two people
|
||||
using it together, one gets *expired*. Not exported.
|
||||
- The server edition opens Postgres (`SUPERMARKET_DATABASE_URL`). With no
|
||||
owner yet, the start-up log prints `https://<domain>/setup/<token>`;
|
||||
`supermarket setup-link` prints a new one, replacing it.
|
||||
- The setup page (no sidebar, like the sign-in pages to come) asks for the
|
||||
owner's email, name and password twice. Mistakes are shown and the link
|
||||
stays usable; on success the owner is signed in and taken to the company
|
||||
profile. Afterwards `/setup/…` leads to `/signin`.
|
||||
- Until the owner exists, every page but the public ones answers 503,
|
||||
*Supermarket isn't set up yet*, with the command for a new link.
|
||||
- The server edition still won't start (`config.Ready`): signing in comes
|
||||
in part 3.
|
||||
|
||||
1. **Users and sessions.**
|
||||
- Tables:
|
||||
- `users`: email, name, kind (person or agent), status (invited,
|
||||
|
||||
@@ -210,7 +210,7 @@ The old terminal app used `http://localhost:8080/callback`; you can remove that
|
||||
## Security
|
||||
|
||||
- The port is published on `127.0.0.1` only, so other machines can't reach it, whatever the firewall says.
|
||||
- The app has no login, so it protects itself from web pages open in the same browser: it only answers requests addressed to `localhost` (against DNS rebinding), and refuses form posts that don't come from its own pages.
|
||||
- The app has no login, so it protects itself from web pages open in the same browser: it only answers requests addressed to `localhost` (against DNS rebinding), and refuses form posts that don't come from its own pages: each form carries a random token that another site can't know, and the browser's `Origin` must be the app's own.
|
||||
- The container runs as you, with a read-only filesystem, no Linux capabilities and `no-new-privileges`. It can write only its data folder.
|
||||
- `/mcp` requires the bearer token in `mcp-token`.
|
||||
|
||||
|
||||
+64
-1
@@ -49,6 +49,7 @@ import (
|
||||
"supermarket/internal/secrets"
|
||||
"supermarket/internal/storage"
|
||||
"supermarket/internal/transfer"
|
||||
"supermarket/internal/users"
|
||||
"supermarket/internal/web"
|
||||
)
|
||||
|
||||
@@ -72,6 +73,13 @@ func main() {
|
||||
if len(os.Args) > 1 && os.Args[1] == "config" {
|
||||
os.Exit(configCommand())
|
||||
}
|
||||
if len(os.Args) > 1 && os.Args[1] == "setup-link" {
|
||||
if err := setupLinkCommand(); err != nil {
|
||||
fmt.Fprintln(os.Stderr, err)
|
||||
os.Exit(1)
|
||||
}
|
||||
return
|
||||
}
|
||||
if len(os.Args) > 1 && (os.Args[1] == "export" || os.Args[1] == "import") {
|
||||
if err := transferCommand(os.Args[1], os.Args[2:]); err != nil {
|
||||
fmt.Fprintln(os.Stderr, err)
|
||||
@@ -208,7 +216,12 @@ func run(log *slog.Logger) error {
|
||||
return err
|
||||
}
|
||||
db.AppVersion = version
|
||||
database, err := db.Open(filepath.Join(dataDir, "app.db"))
|
||||
var database *db.DB
|
||||
if cfg.DatabaseURL != "" {
|
||||
database, err = db.OpenPostgres(cfg.DatabaseURL)
|
||||
} else {
|
||||
database, err = db.Open(filepath.Join(dataDir, "app.db"))
|
||||
}
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -316,6 +329,15 @@ func run(log *slog.Logger) error {
|
||||
return err
|
||||
}
|
||||
|
||||
// A new server has no owner yet: a link to create one.
|
||||
if cfg.Edition != config.Local {
|
||||
if link, err := setupLink(database, publicURL); err != nil {
|
||||
return err
|
||||
} else if link != "" {
|
||||
log.Warn("Supermarket isn't set up yet. To create its owner, open this link (it works once, for a day): " + link)
|
||||
}
|
||||
}
|
||||
|
||||
httpServer := &http.Server{
|
||||
Addr: addr,
|
||||
Handler: handler,
|
||||
@@ -379,6 +401,47 @@ func run(log *slog.Logger) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// setupLink makes a new one-time link to create the owner, or returns ""
|
||||
// if there's an owner already.
|
||||
func setupLink(d *db.DB, publicURL string) (string, error) {
|
||||
done, err := users.HasOwner(d, users.Team)
|
||||
if err != nil || done {
|
||||
return "", err
|
||||
}
|
||||
token, err := users.NewLink(d, users.SetupLink, 0, time.Now())
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return publicURL + "/setup/" + token, nil
|
||||
}
|
||||
|
||||
// setupLinkCommand runs `supermarket setup-link`: a new link to create the
|
||||
// owner, replacing the one in the start-up log.
|
||||
func setupLinkCommand() error {
|
||||
cfg, err := config.Load(os.Getenv)
|
||||
if err != nil {
|
||||
return fmt.Errorf("the settings need fixing (supermarket config shows them):\n%w", err)
|
||||
}
|
||||
if cfg.Edition == config.Local {
|
||||
return errors.New("the local edition has no sign-in, so nothing to set up: open " + cfg.PublicURL)
|
||||
}
|
||||
d, _, err := openForCommand(cfg)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer d.Close()
|
||||
link, err := setupLink(d, cfg.PublicURL)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if link == "" {
|
||||
return errors.New("Supermarket is set up already: its owner signs in, and invites the others (Settings → Users)")
|
||||
}
|
||||
fmt.Println("Open this link to create Supermarket's owner. It works once, for a day, and replaces any earlier link:")
|
||||
fmt.Println(link)
|
||||
return nil
|
||||
}
|
||||
|
||||
// mcpToken reads the bearer token agents use for /mcp, creating it if there
|
||||
// is none. install.sh may create it first, to give it to Hermes.
|
||||
func mcpToken(path string) (string, error) {
|
||||
|
||||
@@ -90,6 +90,20 @@ CREATE TABLE sessions (
|
||||
user_agent TEXT NOT NULL DEFAULT ''
|
||||
);
|
||||
CREATE INDEX sessions_user ON sessions(user_id);
|
||||
`,
|
||||
},
|
||||
// 33
|
||||
{
|
||||
Note: "one-time links: setting up the first owner, password resets, invitations",
|
||||
SQLite: `
|
||||
CREATE TABLE links (
|
||||
id TEXT PRIMARY KEY, -- the SHA-256 of the link's random token
|
||||
purpose TEXT NOT NULL, -- setup, reset or invite
|
||||
user_id INTEGER NOT NULL DEFAULT 0, -- whose it is; 0 for setup
|
||||
created_at TEXT NOT NULL,
|
||||
expires_at TEXT NOT NULL
|
||||
);
|
||||
CREATE INDEX links_user ON links(user_id, purpose);
|
||||
`,
|
||||
},
|
||||
}
|
||||
|
||||
@@ -42,7 +42,7 @@ type Manifest struct {
|
||||
// company's data. Secrets go in secrets.json, opened, if asked for.
|
||||
var skipped = map[string]bool{
|
||||
"instances": true, "locks": true, "schema_version": true, "schema_migrations": true, "secrets": true,
|
||||
"sessions": true,
|
||||
"sessions": true, "links": true,
|
||||
}
|
||||
|
||||
// startupSettings are settings a new install writes when it first starts:
|
||||
|
||||
@@ -0,0 +1,100 @@
|
||||
package users
|
||||
|
||||
import (
|
||||
"database/sql"
|
||||
"errors"
|
||||
"time"
|
||||
|
||||
"supermarket/internal/db"
|
||||
)
|
||||
|
||||
// Purpose is what a one-time link is for.
|
||||
type Purpose string
|
||||
|
||||
const (
|
||||
SetupLink Purpose = "setup" // creates the first owner
|
||||
ResetLink Purpose = "reset" // chooses a new password
|
||||
InviteLink Purpose = "invite" // joins the team
|
||||
)
|
||||
|
||||
// How long each kind of link lasts.
|
||||
var linkTTL = map[Purpose]time.Duration{
|
||||
SetupLink: 24 * time.Hour,
|
||||
ResetLink: time.Hour,
|
||||
InviteLink: 7 * 24 * time.Hour,
|
||||
}
|
||||
|
||||
// ErrBadLink is a link that's unknown, used, replaced or out of date.
|
||||
var ErrBadLink = errors.New("this link has expired or was already used")
|
||||
|
||||
// NewLink makes a one-time link's token. It replaces the user's earlier
|
||||
// link for the same purpose (the setup link has no user: one at a time).
|
||||
// Only the token's hash is kept.
|
||||
func NewLink(d *db.DB, p Purpose, user int64, now time.Time) (string, error) {
|
||||
ttl, ok := linkTTL[p]
|
||||
if !ok {
|
||||
return "", errors.New("no such link")
|
||||
}
|
||||
token, err := NewToken()
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
tx, err := d.Begin()
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
defer tx.Rollback()
|
||||
if _, err := tx.Exec(`DELETE FROM links WHERE purpose = ? AND user_id = ?`, string(p), user); err != nil {
|
||||
return "", err
|
||||
}
|
||||
if _, err := tx.Exec(`INSERT INTO links (id, purpose, user_id, created_at, expires_at) VALUES (?, ?, ?, ?, ?)`,
|
||||
hashToken(token), string(p), user, ts(now), ts(now.Add(ttl))); err != nil {
|
||||
return "", err
|
||||
}
|
||||
return token, tx.Commit()
|
||||
}
|
||||
|
||||
// PeekLink says whose a link is, without using it: to show its page.
|
||||
func PeekLink(d *db.DB, token string, p Purpose, now time.Time) (int64, error) {
|
||||
var user int64
|
||||
err := d.QueryRow(`SELECT user_id FROM links WHERE id = ? AND purpose = ? AND expires_at > ?`, hashToken(token), string(p), ts(now)).Scan(&user)
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
return 0, ErrBadLink
|
||||
}
|
||||
return user, err
|
||||
}
|
||||
|
||||
// UseLink uses a link up, once: of two people using it together, one
|
||||
// gets ErrBadLink.
|
||||
func UseLink(d *db.DB, token string, p Purpose, now time.Time) (int64, error) {
|
||||
var user int64
|
||||
err := d.QueryRow(`DELETE FROM links WHERE id = ? AND purpose = ? AND expires_at > ? RETURNING user_id`, hashToken(token), string(p), ts(now)).Scan(&user)
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
return 0, ErrBadLink
|
||||
}
|
||||
return user, err
|
||||
}
|
||||
|
||||
// DropLinks withdraws a user's links for a purpose (a withdrawn
|
||||
// invitation; a reset no longer needed).
|
||||
func DropLinks(d *db.DB, p Purpose, user int64) error {
|
||||
_, err := d.Exec(`DELETE FROM links WHERE purpose = ? AND user_id = ?`, string(p), user)
|
||||
return err
|
||||
}
|
||||
|
||||
// LinkExpiry is when a user's link for a purpose runs out; zero if they
|
||||
// have none that works.
|
||||
func LinkExpiry(d *db.DB, p Purpose, user int64, now time.Time) (time.Time, error) {
|
||||
var exp string
|
||||
err := d.QueryRow(`SELECT expires_at FROM links WHERE purpose = ? AND user_id = ? AND expires_at > ?`, string(p), user, ts(now)).Scan(&exp)
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
return time.Time{}, nil
|
||||
}
|
||||
return parseTS(exp), err
|
||||
}
|
||||
|
||||
// PruneLinks deletes links that have run out.
|
||||
func PruneLinks(d *db.DB, now time.Time) error {
|
||||
_, err := d.Exec(`DELETE FROM links WHERE expires_at <= ?`, ts(now))
|
||||
return err
|
||||
}
|
||||
@@ -221,3 +221,45 @@ func TestSessions(t *testing.T) {
|
||||
t.Errorf("pruned %d", n)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLinks(t *testing.T) {
|
||||
d := openDB(t)
|
||||
now := time.Date(2026, 11, 25, 10, 0, 0, 0, time.UTC)
|
||||
a, err := NewLink(d, ResetLink, 7, now)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if u, err := PeekLink(d, a, ResetLink, now); err != nil || u != 7 {
|
||||
t.Errorf("peek: %d %v", u, err)
|
||||
}
|
||||
if _, err := PeekLink(d, a, InviteLink, now); !errors.Is(err, ErrBadLink) {
|
||||
t.Error("used for another purpose")
|
||||
}
|
||||
if exp, _ := LinkExpiry(d, ResetLink, 7, now); !exp.Equal(now.Add(time.Hour)) {
|
||||
t.Errorf("expiry %v", exp)
|
||||
}
|
||||
if _, err := UseLink(d, a, ResetLink, now.Add(time.Hour)); !errors.Is(err, ErrBadLink) {
|
||||
t.Error("used after an hour")
|
||||
}
|
||||
b, _ := NewLink(d, ResetLink, 7, now)
|
||||
c, _ := NewLink(d, ResetLink, 7, now) // replaces b
|
||||
if _, err := UseLink(d, b, ResetLink, now); !errors.Is(err, ErrBadLink) {
|
||||
t.Error("replaced link worked")
|
||||
}
|
||||
if u, err := UseLink(d, c, ResetLink, now); err != nil || u != 7 {
|
||||
t.Errorf("use: %d %v", u, err)
|
||||
}
|
||||
if _, err := UseLink(d, c, ResetLink, now); !errors.Is(err, ErrBadLink) {
|
||||
t.Error("used twice")
|
||||
}
|
||||
i, _ := NewLink(d, InviteLink, 8, now)
|
||||
if err := DropLinks(d, InviteLink, 8); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := PeekLink(d, i, InviteLink, now); !errors.Is(err, ErrBadLink) {
|
||||
t.Error("withdrawn link worked")
|
||||
}
|
||||
if _, err := NewLink(d, "other", 1, now); err == nil {
|
||||
t.Error("unknown purpose")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -20,6 +20,7 @@ import (
|
||||
"supermarket/internal/jobs"
|
||||
"supermarket/internal/storage"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
"unicode"
|
||||
"unicode/utf8"
|
||||
@@ -69,6 +70,7 @@ type Server struct {
|
||||
|
||||
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
|
||||
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.",
|
||||
|
||||
@@ -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})
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -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)); }
|
||||
|
||||
@@ -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}}
|
||||
@@ -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}}
|
||||
Reference in New Issue
Block a user