From 47a504b7b2a148278d8a095089ea53624bd9befe Mon Sep 17 00:00:00 2001 From: David Young Date: Wed, 25 Nov 2026 09:07:32 -0700 Subject: [PATCH] Phase 10, part 4: inviting users, and what admins can change MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Settings → Users lists everyone with their access and status. Admins invite people by email (a link for 7 days), as admins or as members with modules each to view or edit; the invitation's page sets the password, profile and emails wanted. Admins can resend or withdraw invitations, change access, turn accounts off and on, unlock, reset two-factor, sign someone out, and remove them; never the owner, nor themselves. Your account gets the emails wanted and a photo. Co-Authored-By: Claude Opus 5.5 --- PLAN.md | 24 ++ internal/users/users.go | 52 ++- internal/users/users_test.go | 11 +- internal/web/account.go | 9 +- internal/web/auth.go | 2 +- internal/web/auth_test.go | 6 + internal/web/photo.go | 111 +++++ internal/web/server.go | 17 + internal/web/signin_test.go | 2 +- internal/web/static/app.css | 10 + internal/web/templates/account.html | 19 + internal/web/templates/forbidden.html | 7 + internal/web/templates/invite.html | 28 ++ internal/web/templates/layout.html | 26 +- internal/web/templates/user.html | 54 +++ internal/web/templates/users.html | 31 ++ internal/web/users.go | 567 ++++++++++++++++++++++++++ internal/web/users_test.go | 259 ++++++++++++ 18 files changed, 1220 insertions(+), 15 deletions(-) create mode 100644 internal/web/photo.go create mode 100644 internal/web/templates/forbidden.html create mode 100644 internal/web/templates/invite.html create mode 100644 internal/web/templates/user.html create mode 100644 internal/web/templates/users.html create mode 100644 internal/web/users.go create mode 100644 internal/web/users_test.go diff --git a/PLAN.md b/PLAN.md index 4ed8a24..456cbb0 100644 --- a/PLAN.md +++ b/PLAN.md @@ -2239,6 +2239,30 @@ starts** (multi-tenant still doesn't). - Sign-ins, failures, locks, resets and two-factor changes are logged; they move to the audit log in part 8. +**Part 4 built 2026-11-25** on `phase10`. +- Settings → Users (admins only; a member gets the 403 page): everyone, + with their access (*Admin*, or *SEO, Metrics (view)*), status (active, + invited until when, invitation expired, locked, turned off, two-factor) + and last sign-in. *Invite someone*: email, name, and *Admin* or *Member* + with each module (Content, Prospects, SEO, Sites, Metrics, the Market) + as no access, view or edit. A member needs at least one module. +- The invitation is emailed with a link (7 days, once). `/invite/` + asks for the name, title, time zone, a password twice, and the emails + they want, of those their modules allow (the SEO morning check, the SEO + Monday report; part 5 sends them to the people who chose them). Joining + signs them in. +- One user's page: their access; send the invitation again (a new link + replaces the old) or withdraw it (the account goes); turn the account + off (signed out, links withdrawn) or back on (re-invited if they never + joined); unlock; sign them out everywhere; reset two-factor (off, and + signed out); remove. Losing a module drops its emails. The owner's + account and your own can't be changed there. +- Your account also has the emails wanted, and a photo (2 MB, PNG, JPEG, + WebP or GIF, checked by content), kept in the file storage under + `photos/`, shown at `/users//photo` to people signed in. The photo + is on Your account rather than the invitation page, to keep joining to + one plain form. + 1. **Users and sessions.** - Tables: - `users`: email, name, kind (person or agent), status (invited, diff --git a/internal/users/users.go b/internal/users/users.go index ca1ca8e..938770e 100644 --- a/internal/users/users.go +++ b/internal/users/users.go @@ -236,10 +236,17 @@ func SaveProfile(d *db.DB, u *User) error { return err } -// SetStatus activates, disables or re-invites a user. +// SetStatus activates, disables or re-invites a user. A disabled user's +// sessions end. func SetStatus(d *db.DB, id int64, s Status) error { - _, err := d.Exec(`UPDATE users SET status = ? WHERE id = ?`, string(s), id) - return err + if _, err := d.Exec(`UPDATE users SET status = ? WHERE id = ?`, string(s), id); err != nil { + return err + } + if s == Disabled { + _, err := d.Exec(`DELETE FROM sessions WHERE user_id = ?`, id) + return err + } + return nil } // SignedIn records a sign-in. @@ -257,7 +264,7 @@ func Delete(d *db.DB, id int64) error { defer tx.Rollback() // Not left to ON DELETE CASCADE: SQLite enforces it only with // foreign_keys on, and an imported database may not have had them. - for _, q := range []string{`DELETE FROM sessions WHERE user_id = ?`, `DELETE FROM memberships WHERE user_id = ?`, `DELETE FROM users WHERE id = ?`} { + for _, q := range []string{`DELETE FROM sessions WHERE user_id = ?`, `DELETE FROM links WHERE user_id = ?`, `DELETE FROM memberships WHERE user_id = ?`, `DELETE FROM users WHERE id = ?`} { if _, err := tx.Exec(q, id); err != nil { return err } @@ -409,3 +416,40 @@ func HasOwner(d *db.DB, team int64) (bool, error) { err := d.QueryRow(`SELECT count(*) FROM memberships WHERE team_id = ? AND role = 'owner'`, team).Scan(&n) return n > 0, err } + +// TeamUser is a user with their place in the team. +type TeamUser struct { + *User + Membership +} + +// Members are the team's users, people first, then by name. +func Members(d *db.DB, team int64) ([]TeamUser, error) { + cols := strings.ReplaceAll("u."+userCols, ", ", ", u.") + rows, err := d.Query(`SELECT `+cols+`, m.role, m.modules FROM users u JOIN memberships m ON m.user_id = u.id + WHERE m.team_id = ? ORDER BY u.kind DESC, u.name COLLATE NOCASE, u.email`, team) + if err != nil { + return nil, err + } + defer rows.Close() + var out []TeamUser + for rows.Next() { + var role, modules string + u, err := scanUser(rowWith{rows, []any{&role, &modules}}) + if err != nil { + return nil, err + } + m := Membership{Team: team, User: u.ID, Role: Role(role), Modules: map[string]Access{}} + _ = json.Unmarshal([]byte(modules), &m.Modules) + out = append(out, TeamUser{User: u, Membership: m}) + } + return out, rows.Err() +} + +// rowWith scans a user's columns followed by some more. +type rowWith struct { + row interface{ Scan(...any) error } + more []any +} + +func (r rowWith) Scan(dest ...any) error { return r.row.Scan(append(dest, r.more...)...) } diff --git a/internal/users/users_test.go b/internal/users/users_test.go index af3ae32..6579557 100644 --- a/internal/users/users_test.go +++ b/internal/users/users_test.go @@ -191,16 +191,17 @@ func TestSessions(t *testing.T) { t.Errorf("idle a week: %v", err) } - // A disabled user's sessions stop working. - t3, s3, _ := StartSession(d, u.ID, "", "", now) - t4, _, _ := StartSession(d, u.ID, "", "", now) + // A disabled user's sessions end. + t5, _, _ := StartSession(d, u.ID, "", "", now) if err := SetStatus(d, u.ID, Disabled); err != nil { t.Fatal(err) } - if _, _, err := Lookup(d, t3, now); !errors.Is(err, ErrNoSession) { + SetStatus(d, u.ID, Active) + if _, _, err := Lookup(d, t5, now); !errors.Is(err, ErrNoSession) { t.Errorf("disabled user: %v", err) } - SetStatus(d, u.ID, Active) + t3, s3, _ := StartSession(d, u.ID, "", "", now) + t4, _, _ := StartSession(d, u.ID, "", "", now) if list, _ := Sessions(d, u.ID, now); len(list) != 2 { t.Errorf("sessions: %d", len(list)) } diff --git a/internal/web/account.go b/internal/web/account.go index 3574fe7..80ceb00 100644 --- a/internal/web/account.go +++ b/internal/web/account.go @@ -21,8 +21,10 @@ type accountData struct { Role users.Role Sessions []sessionRow Zones []string - Problem string // under the form it's about - Section string // which form: profile, password, two-factor + Emails []emailKind // the emails they may choose + Photos bool // there's file storage for a photo + Problem string // under the form it's about + Section string // which form: profile, password, two-factor // Setting up two-factor sign-in. Secret string @@ -76,7 +78,7 @@ func (s *Server) renderAccount(w http.ResponseWriter, r *http.Request, v *viewer s.serverError(w, err) return } - d.U, d.Role, d.Zones = u, v.Member.Role, commonZones + d.U, d.Role, d.Zones, d.Emails, d.Photos = u, v.Member.Role, commonZones, emailsFor(v.Member), s.Files != nil for _, ss := range list { d.Sessions = append(d.Sessions, sessionRow{Session: ss, This: ss.ID == v.Session.ID}) } @@ -95,6 +97,7 @@ func (s *Server) accountProfile(w http.ResponseWriter, r *http.Request) { u.Name = strings.TrimSpace(r.PostFormValue("name")) u.Title = strings.TrimSpace(r.PostFormValue("title")) u.TimeZone = strings.TrimSpace(r.PostFormValue("time_zone")) + u.Emails = pickEmails(v.Member, r.PostForm["emails"]) switch { case u.Name == "": s.renderAccount(w, r, v, &accountData{Section: "profile", Problem: "Give your name."}, http.StatusUnprocessableEntity) diff --git a/internal/web/auth.go b/internal/web/auth.go index f73128b..d44d30d 100644 --- a/internal/web/auth.go +++ b/internal/web/auth.go @@ -85,7 +85,7 @@ func publicPath(p string) bool { case p == "/healthz", p == "/favicon.ico", p == "/mcp", strings.HasPrefix(p, "/static/"), p == "/signin", p == "/signin/code", p == "/signout", p == "/forgot", - strings.HasPrefix(p, "/reset/"), strings.HasPrefix(p, "/setup/"): + strings.HasPrefix(p, "/reset/"), strings.HasPrefix(p, "/setup/"), strings.HasPrefix(p, "/invite/"): return true } return false diff --git a/internal/web/auth_test.go b/internal/web/auth_test.go index 68936f7..e0de0a0 100644 --- a/internal/web/auth_test.go +++ b/internal/web/auth_test.go @@ -10,6 +10,7 @@ import ( "supermarket/internal/appmail" "supermarket/internal/config" + "supermarket/internal/storage" "supermarket/internal/users" ) @@ -19,6 +20,11 @@ func newServerEdition(t *testing.T) (*Server, http.Handler) { s, h := newTestServer(t, nil) s.Config = &config.Config{Edition: config.Server} s.Mail = &appmail.Outbox{} + files, err := storage.Open(config.Storage{Dir: t.TempDir()}) + if err != nil { + t.Fatal(err) + } + s.Files = files return s, h } diff --git a/internal/web/photo.go b/internal/web/photo.go new file mode 100644 index 0000000..cd7a4b3 --- /dev/null +++ b/internal/web/photo.go @@ -0,0 +1,111 @@ +package web + +import ( + "bytes" + "errors" + "io" + "net/http" + "strconv" + "strings" + + "supermarket/internal/users" +) + +// Profile photos, kept in the file storage (photos/-.) +// and shown to people signed in. + +const maxPhoto = 2 << 20 + +var photoTypes = map[string]string{"image/png": "png", "image/jpeg": "jpg", "image/webp": "webp", "image/gif": "gif"} + +func (s *Server) accountPhoto(w http.ResponseWriter, r *http.Request) { + v := s.me(w, r) + if v == nil { + return + } + if s.Files == nil { + http.NotFound(w, r) + return + } + u, err := users.ByID(s.DB, v.User.ID) + if err != nil { + s.serverError(w, err) + return + } + fail := func(msg string) { + s.renderAccount(w, r, v, &accountData{Section: "profile", Problem: msg}, http.StatusUnprocessableEntity) + } + key := "" + if r.URL.Query().Get("remove") == "" { + r.Body = http.MaxBytesReader(w, r.Body, maxPhoto+64<<10) + f, _, err := r.FormFile("photo") + if err != nil { + fail("Choose a picture of 2 MB or less (PNG, JPEG, WebP or GIF).") + return + } + defer f.Close() + data, err := io.ReadAll(io.LimitReader(f, maxPhoto+1)) + if err != nil || len(data) > maxPhoto || len(data) == 0 { + fail("Choose a picture of 2 MB or less (PNG, JPEG, WebP or GIF).") + return + } + ext, ok := photoTypes[http.DetectContentType(data)] + if !ok { + fail("That isn't a PNG, JPEG, WebP or GIF picture.") + return + } + token, err := users.NewToken() + if err != nil { + s.serverError(w, err) + return + } + key = "photos/" + strconv.FormatInt(u.ID, 10) + "-" + token[:12] + "." + ext + if err := s.Files.Put(r.Context(), key, bytes.NewReader(data), int64(len(data))); err != nil { + s.serverError(w, err) + return + } + } + old := u.Photo + u.Photo = key + if err := users.SaveProfile(s.DB, u); err != nil { + s.serverError(w, err) + return + } + if old != "" { + if err := s.Files.Delete(r.Context(), old); err != nil { + s.Log.Warn("account: removing the old photo", "file", old, "err", err) + } + } + redirect(w, r, "/settings/account", "saved") +} + +// userPhoto shows someone's photo to people signed in. +func (s *Server) userPhoto(w http.ResponseWriter, r *http.Request) { + if s.me(w, r) == nil { + return + } + id, _ := strconv.ParseInt(r.PathValue("id"), 10, 64) + u, err := users.ByID(s.DB, id) + if errors.Is(err, users.ErrNotFound) || (err == nil && (u.Photo == "" || s.Files == nil)) { + http.NotFound(w, r) + return + } + if err != nil { + s.serverError(w, err) + return + } + rc, err := s.Files.Get(r.Context(), u.Photo) + if err != nil { + http.NotFound(w, r) + return + } + defer rc.Close() + ext := u.Photo[strings.LastIndex(u.Photo, ".")+1:] + for t, e := range photoTypes { + if e == ext { + w.Header().Set("Content-Type", t) + } + } + w.Header().Set("Cache-Control", "private, max-age=3600") + _, _ = io.Copy(w, rc) +} diff --git a/internal/web/server.go b/internal/web/server.go index 95fad77..11d5daf 100644 --- a/internal/web/server.go +++ b/internal/web/server.go @@ -159,6 +159,14 @@ func (s *Server) Handler() (http.Handler, error) { mux.HandleFunc("POST /settings/account/two-factor", s.twoFactorOn) mux.HandleFunc("POST /settings/account/two-factor/off", s.twoFactorOff) mux.HandleFunc("POST /settings/account/recovery-codes", s.recoveryCodes) + mux.HandleFunc("POST /settings/account/photo", s.accountPhoto) + mux.HandleFunc("GET /users/{id}/photo", s.userPhoto) + mux.HandleFunc("GET /settings/users", s.usersPage) + mux.HandleFunc("POST /settings/users", s.userInvite) + mux.HandleFunc("GET /settings/users/{id}", s.userPage) + mux.HandleFunc("POST /settings/users/{id}/{action}", s.userAction) + mux.HandleFunc("GET /invite/{token}", s.invitePage) + mux.HandleFunc("POST /invite/{token}", s.inviteAccept) mux.HandleFunc("GET /search", s.searchPage) @@ -635,6 +643,15 @@ var flashes = map[string]string{ "sessions-ended": "Signed out everywhere else.", "two-factor-off": "Two-factor sign-in is off.", "codes-low": "You're running out of recovery codes: make new ones below.", + "invited": "Invitation sent.", + "withdrawn": "Invitation withdrawn.", + "disabled": "The account is turned off, and signed out.", + "enabled": "The account is back on.", + "unlocked": "Unlocked.", + "two-factor-reset": "Two-factor sign-in is reset: they sign in with their password, then can turn it on again.", + "signed-out-user": "Signed out everywhere.", + "removed": "Removed.", + "joined": "Welcome to Supermarket.", "deleted": "Deleted.", "x-connected": "X is connected.", "li-connected": "LinkedIn is connected.", diff --git a/internal/web/signin_test.go b/internal/web/signin_test.go index 474fa5a..2624b4c 100644 --- a/internal/web/signin_test.go +++ b/internal/web/signin_test.go @@ -273,7 +273,7 @@ func TestTwoFactor(t *testing.T) { if rec := signinPost(h, "203.0.113.9", "/signin/code", url.Values{"token": {token}, "code": {users.TOTPCode(secret, now)}}); rec.Code != http.StatusUnauthorized { t.Errorf("reused code: %d", rec.Code) } - rec = signinPost(h, "203.0.113.9", "/signin/code", url.Values{"token": {token}, "code": {users.TOTPCode(secret, now.Add(30 * time.Second))}, "next": {"/seo"}}) + rec = signinPost(h, "203.0.113.9", "/signin/code", url.Values{"token": {token}, "code": {users.TOTPCode(secret, now.Add(30*time.Second))}, "next": {"/seo"}}) if rec.Code != http.StatusSeeOther || rec.Header().Get("Location") != "/seo" || cookieOf(rec, sessionCookie) == nil { t.Fatalf("code: %d %s", rec.Code, rec.Body.String()) } diff --git a/internal/web/static/app.css b/internal/web/static/app.css index 4a2091b..25a867b 100644 --- a/internal/web/static/app.css +++ b/internal/web/static/app.css @@ -501,3 +501,13 @@ img.qr { image-rendering: pixelated; background: #fff; padding: 0.5rem; border-r .sidebar-foot .who { display: flex; align-items: center; justify-content: space-between; gap: 0.5rem; padding: 0.35rem 0.9rem; font-size: 0.85rem; color: hsl(var(--muted-foreground)); } .sidebar-foot .who form { margin: 0; } .sidebar-foot .who button { padding: 0.15rem 0.5rem; font-size: 0.8rem; } +.pill.warn { background: hsl(var(--warn-bg)); border-color: hsl(var(--warn-border)); color: hsl(var(--warn)); } +fieldset.access .access-grid td { padding: 0.25rem 0.6rem 0.25rem 0; } +fieldset.access .access-grid label { margin: 0; } +.actions { display: flex; flex-wrap: wrap; gap: 0.5rem; } +.actions form.inline { margin: 0; } +.avatar { display: inline-block; width: 1.5rem; height: 1.5rem; border-radius: 999px; object-fit: cover; vertical-align: middle; } +.avatar.large { width: 4rem; height: 4rem; } +.avatar.none { background: hsl(var(--accent)); color: hsl(var(--accent-foreground)); text-align: center; line-height: 4rem; font-weight: 600; text-transform: uppercase; } +.photo-row { display: flex; align-items: center; gap: 1rem; flex-wrap: wrap; } +.photo-row form { margin: 0; } diff --git a/internal/web/templates/account.html b/internal/web/templates/account.html index d15388b..a3d4c37 100644 --- a/internal/web/templates/account.html +++ b/internal/web/templates/account.html @@ -12,9 +12,28 @@ {{range .Zones}} + {{if .Emails}}
+ Emails you'd like + {{$u := .U}}{{range .Emails}}{{end}} +
{{end}} +{{if .Photos}} +
+

Photo

+
+ {{if .U.Photo}}Your photo{{else}}{{end}} +
+ + +
+ {{if .U.Photo}}
{{end}} +
+

Shown beside your name to the team. A square picture of 2 MB or less.

+
+{{end}} +

Password

{{if eq .Section "password"}}{{end}} diff --git a/internal/web/templates/forbidden.html b/internal/web/templates/forbidden.html new file mode 100644 index 0000000..09238cc --- /dev/null +++ b/internal/web/templates/forbidden.html @@ -0,0 +1,7 @@ +{{define "content"}} +

No access

+
+

This isn't in what you have access to. An admin can give it to you, under Settings → Users.

+

Back to the Overview

+
+{{end}} diff --git a/internal/web/templates/invite.html b/internal/web/templates/invite.html new file mode 100644 index 0000000..4061fd1 --- /dev/null +++ b/internal/web/templates/invite.html @@ -0,0 +1,28 @@ +{{define "content"}}{{with .Data}} +{{if .U}} +

Join {{.Company}}

+

You're invited to Supermarket as {{.U.Email}}. Choose a password, and tell the team a little about you.

+{{with .Problem}}{{end}} + + + + + + {{range .Zones}} + + + {{if .Emails}}
+ Emails you'd like + {{$u := .U}}{{range .Emails}}{{end}} +
{{end}} + +
+{{else}} +

This invitation doesn't work

+
+

It has expired (an invitation lasts 7 days), was already used, or was withdrawn or replaced by a newer one.

+

Ask whoever invited you to send it again. If you've joined already, sign in.

+
+{{end}} +{{end}}{{end}} diff --git a/internal/web/templates/layout.html b/internal/web/templates/layout.html index 73cd363..4d3eb4c 100644 --- a/internal/web/templates/layout.html +++ b/internal/web/templates/layout.html @@ -139,7 +139,8 @@