Phase 10, part 4: inviting users, and what admins can change

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 <noreply@anthropic.com>
This commit is contained in:
2026-11-25 09:07:32 -07:00
co-authored by Claude Opus 5.5
parent 8040512a18
commit 47a504b7b2
18 changed files with 1220 additions and 15 deletions
+24
View File
@@ -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/<token>`
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/<id>/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,
+47 -3
View File
@@ -236,11 +236,18 @@ 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)
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.
func SignedIn(d *db.DB, id int64, now time.Time) error {
@@ -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...)...) }
+6 -5
View File
@@ -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))
}
+4 -1
View File
@@ -21,6 +21,8 @@ type accountData struct {
Role users.Role
Sessions []sessionRow
Zones []string
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
@@ -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)
+1 -1
View File
@@ -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
+6
View File
@@ -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
}
+111
View File
@@ -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/<user>-<random>.<ext>)
// 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)
}
+17
View File
@@ -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.",
+10
View File
@@ -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; }
+19
View File
@@ -12,9 +12,28 @@
<label>Time zone <input name="time_zone" value="{{.U.TimeZone}}" list="zones" placeholder="e.g. Europe/Paris">
<span class="help">Times are shown in it. Empty: the server's.</span></label>
<datalist id="zones">{{range .Zones}}<option value="{{.}}">{{end}}</datalist>
{{if .Emails}}<fieldset>
<legend>Emails you'd like</legend>
{{$u := .U}}{{range .Emails}}<label class="check"><input type="checkbox" name="emails" value="{{.ID}}" {{if has $u.Emails .ID}}checked{{end}}> <span>{{.Name}} <span class="help">{{.Help}}</span></span></label>{{end}}
</fieldset>{{end}}
<button type="submit">Save</button>
</form>
{{if .Photos}}
<section class="card" id="photo">
<h2>Photo</h2>
<div class="photo-row">
{{if .U.Photo}}<img class="avatar large" src="/users/{{.U.ID}}/photo" alt="Your photo" width="64" height="64">{{else}}<span class="avatar large none" aria-hidden="true">{{slice .U.Email 0 1}}</span>{{end}}
<form method="post" action="/settings/account/photo" enctype="multipart/form-data" class="inline-form">
<input type="file" name="photo" accept="image/png,image/jpeg,image/webp,image/gif" required>
<button type="submit" class="secondary">Upload</button>
</form>
{{if .U.Photo}}<form method="post" action="/settings/account/photo?remove=1"><button type="submit" class="secondary small">Remove</button></form>{{end}}
</div>
<p class="help">Shown beside your name to the team. A square picture of 2 MB or less.</p>
</section>
{{end}}
<form class="card" method="post" action="/settings/account/password" id="password">
<h2>Password</h2>
{{if eq .Section "password"}}<p class="error" role="alert">{{.Problem}}</p>{{end}}
+7
View File
@@ -0,0 +1,7 @@
{{define "content"}}
<div class="page-head"><h1>No access</h1></div>
<section class="card empty">
<p>This isn't in what you have access to. An admin can give it to you, under Settings → Users.</p>
<p><a href="/">Back to the Overview</a></p>
</section>
{{end}}
+28
View File
@@ -0,0 +1,28 @@
{{define "content"}}{{with .Data}}
{{if .U}}
<h1>Join {{.Company}}</h1>
<p class="lede">You're invited to Supermarket as <strong>{{.U.Email}}</strong>. Choose a password, and tell the team a little about you.</p>
{{with .Problem}}<p class="error" role="alert">{{.}}</p>{{end}}
<form class="card" method="post" action="/invite/{{.Token}}">
<input type="text" name="username" value="{{.U.Email}}" autocomplete="username" hidden>
<label>Your name <input name="name" value="{{.U.Name}}" autocomplete="name" required></label>
<label>Title <input name="title" value="{{.U.Title}}" placeholder="e.g. Content writer" autocomplete="organization-title"></label>
<label>Time zone <input name="time_zone" value="{{.U.TimeZone}}" list="zones" placeholder="e.g. Europe/Paris"></label>
<datalist id="zones">{{range .Zones}}<option value="{{.}}">{{end}}</datalist>
<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>
{{if .Emails}}<fieldset>
<legend>Emails you'd like</legend>
{{$u := .U}}{{range .Emails}}<label class="check"><input type="checkbox" name="emails" value="{{.ID}}" {{if has $u.Emails .ID}}checked{{end}}> <span>{{.Name}} <span class="help">{{.Help}}</span></span></label>{{end}}
</fieldset>{{end}}
<button type="submit">Join</button>
</form>
{{else}}
<h1>This invitation doesn't work</h1>
<section class="card">
<p>It has expired (an invitation lasts 7 days), was already used, or was withdrawn or replaced by a newer one.</p>
<p class="help">Ask whoever invited you to send it again. If you've joined already, <a href="/signin">sign in</a>.</p>
</section>
{{end}}
{{end}}{{end}}
+25 -1
View File
@@ -139,7 +139,8 @@
<div class="settings">
<nav class="settings-nav" aria-label="Settings sections">
{{with .Viewer}}{{if .User}}<div class="nav-label">You</div>
<a href="/settings/account" {{if eq $.Nav "settings/account"}}aria-current="page"{{end}}>{{template "icon" "profile"}}Your account</a>{{end}}{{end}}
<a href="/settings/account" {{if eq $.Nav "settings/account"}}aria-current="page"{{end}}>{{template "icon" "profile"}}Your account</a>
{{if .Member.Admin}}<a href="/settings/users" {{if eq $.Nav "settings/users"}}aria-current="page"{{end}}>{{template "icon" "prospects"}}Users</a>{{end}}{{end}}{{end}}
<div class="nav-label">Company</div>
<a href="/settings/profile" {{if eq .Nav "settings/profile"}}aria-current="page"{{end}}>{{template "icon" "profile"}}Profile</a>
<div class="nav-label">Connections</div>
@@ -271,3 +272,26 @@
{{else}}<p class="help">None this week.</p>{{end}}
</section>
{{end}}
{{/* Users (Settings → Users, and one user's page). */}}
{{define "user-status"}}{{if eq .Status "invited"}}{{if .InviteEnd.IsZero}}<span class="pill warn">Invitation expired</span>{{else}}<span class="pill">Invited</span> <span class="muted small">until {{.InviteEnd.Local.Format "2 Jan"}}</span>{{end}}{{else if eq .Status "disabled"}}<span class="pill">Turned off</span>{{else if .Locked}}<span class="pill warn">Locked</span>{{else}}<span class="pill ok">Active</span>{{if .TwoFactor}} <span class="muted small">two-factor</span>{{end}}{{end}}{{end}}
{{/* Role and modules: {{template "access-fields" (dict "Role" … "Modules" … "Grants" …)}} */}}
{{define "access-fields"}}{{$mods := .Modules}}
<fieldset class="access">
<legend>Access</legend>
<label class="check"><input type="radio" name="role" value="admin" {{if eq (print .Role) "admin"}}checked{{end}}> <span><strong>Admin</strong>: every module, Settings, users and connections</span></label>
<label class="check"><input type="radio" name="role" value="member" {{if ne (print .Role) "admin"}}checked{{end}}> <span><strong>Member</strong>: these modules</span></label>
<table class="list access-grid">
<tbody>
{{range .Grants}}{{$a := print (index $mods .ID)}}<tr>
<td>{{.Name}}</td>
<td><label class="check"><input type="radio" name="module:{{.ID}}" value="" {{if eq $a ""}}checked{{end}}> No access</label></td>
<td><label class="check"><input type="radio" name="module:{{.ID}}" value="view" {{if eq $a "view"}}checked{{end}}> View</label></td>
<td><label class="check"><input type="radio" name="module:{{.ID}}" value="edit" {{if eq $a "edit"}}checked{{end}}> Edit</label></td>
</tr>{{end}}
</tbody>
</table>
<p class="help">An admin has them all, whatever is chosen here. <em>View</em> shows a module's pages without the buttons and forms that change things.</p>
</fieldset>
{{end}}
+54
View File
@@ -0,0 +1,54 @@
{{define "content"}}{{template "settings-start" .}}{{with .Data}}{{$u := .M}}
<p><a href="/settings/users">← Users</a></p>
<h2>{{if $u.Name}}{{$u.Name}}{{else}}{{$u.Email}}{{end}}</h2>
<p class="lede">{{$u.Email}}{{with $u.Title}} · {{.}}{{end}} · {{template "user-status" $u}}</p>
{{with .Problem}}<p class="error" role="alert">{{.}}</p>{{end}}
<section class="card">
<dl class="facts">
<dt>Access</dt><dd>{{$u.Access}}</dd>
<dt>Joined</dt><dd>{{if eq $u.Status "invited"}}Not yet{{else}}{{$u.Created.Local.Format "2 Jan 2006"}}{{end}}</dd>
<dt>Last signed in</dt><dd>{{ago $u.SignedIn}}{{if .SessionsN}} · signed in on {{.SessionsN}} {{if eq .SessionsN 1}}browser{{else}}browsers{{end}}{{end}}</dd>
<dt>Two-factor sign-in</dt><dd>{{if $u.TwoFactor}}On, {{$u.RecoveryLeft}} recovery codes left{{else}}Off{{end}}</dd>
{{if $u.FailedSignIns}}<dt>Failed sign-ins</dt><dd>{{$u.FailedSignIns}} in a row{{if $u.Locked}}, locked {{ago $u.LockedAt}}{{end}}</dd>{{end}}
</dl>
</section>
{{if eq (print $u.Role) "owner"}}
<section class="card"><p class="help">The owner can do everything; their account can only be changed by them, under Settings → Your account.</p></section>
{{else if .Me}}
<section class="card"><p class="help">This is you: another admin changes your access. Your own settings are under <a href="/settings/account">Your account</a>.</p></section>
{{else}}
<form class="card" method="post" action="/settings/users/{{$u.ID}}/access">
{{template "access-fields" (dict "Role" $u.Role "Modules" $u.Modules "Grants" .Grants)}}
<button type="submit">Save</button>
</form>
<section class="card">
<h2>Account</h2>
<div class="actions">
{{if eq $u.Status "invited"}}
<form class="inline" method="post" action="/settings/users/{{$u.ID}}/resend"><button type="submit" class="secondary">Send the invitation again</button></form>
<form class="inline" method="post" action="/settings/users/{{$u.ID}}/withdraw"><button type="submit" class="secondary danger">Withdraw the invitation</button></form>
{{else if eq $u.Status "disabled"}}
<form class="inline" method="post" action="/settings/users/{{$u.ID}}/enable"><button type="submit" class="secondary">Turn the account back on</button></form>
{{else}}
{{if $u.Locked}}<form class="inline" method="post" action="/settings/users/{{$u.ID}}/unlock"><button type="submit">Unlock</button></form>{{end}}
{{if .SessionsN}}<form class="inline" method="post" action="/settings/users/{{$u.ID}}/sign-out"><button type="submit" class="secondary">Sign them out everywhere</button></form>{{end}}
{{if $u.TwoFactor}}<form class="inline" method="post" action="/settings/users/{{$u.ID}}/reset-two-factor"><button type="submit" class="secondary">Reset two-factor sign-in</button></form>{{end}}
<form class="inline" method="post" action="/settings/users/{{$u.ID}}/disable"><button type="submit" class="secondary danger">Turn the account off</button></form>
{{end}}
</div>
{{if $u.TwoFactor}}<p class="help">Reset two-factor sign-in for someone who lost their phone and their recovery codes: they sign in with their password alone, then turn it on again. Make sure it's really them asking.</p>{{end}}
<p class="help">Turning an account off signs them out and keeps their name on what they did; they can be turned back on.</p>
</section>
{{if ne $u.Status "invited"}}
<form class="card danger-zone" method="post" action="/settings/users/{{$u.ID}}/remove">
<h2>Remove</h2>
<p class="help">Removes the account for good. What they wrote stays.</p>
<button type="submit" class="danger">Remove {{if $u.Name}}{{$u.Name}}{{else}}{{$u.Email}}{{end}}</button>
</form>
{{end}}
{{end}}
{{end}}{{template "settings-end"}}{{end}}
+31
View File
@@ -0,0 +1,31 @@
{{define "content"}}{{template "settings-start" .}}{{with .Data}}{{$d := .}}
<h2>Users</h2>
<p class="lede">Who can sign in, and to what. Admins can do everything, including this page; members get the modules you give them, each to view or to edit.</p>
<section class="card">
<table class="list">
<thead><tr><th>Name</th><th>Access</th><th>Status</th><th>Last signed in</th></tr></thead>
<tbody>
{{range .Rows}}<tr>
<td><a href="/settings/users/{{.ID}}">{{if .Name}}{{.Name}}{{else}}{{.Email}}{{end}}</a>{{if eq .ID $d.Me}} <span class="muted">(you)</span>{{end}}<br><span class="muted small">{{.Email}}</span></td>
<td>{{.Access}}</td>
<td>{{template "user-status" .}}</td>
<td>{{ago .SignedIn}}</td>
</tr>{{end}}
</tbody>
</table>
</section>
<form class="card" method="post" action="/settings/users" id="invite">
<h2>Invite someone</h2>
{{with .Form.Problem}}<p class="error" role="alert">{{.}}</p>{{end}}
<div class="cols">
<label>Email address <input type="email" name="email" value="{{.Form.Email}}" required></label>
<label>Name <input name="name" value="{{.Form.Name}}" required></label>
</div>
{{template "access-fields" (dict "Role" .Form.Role "Modules" .Form.Modules "Grants" .Grants)}}
<p class="help">They get an email with a link that works once, for 7 days, to choose a password and fill in their profile.</p>
<button type="submit">Send the invitation</button>
</form>
{{end}}{{template "settings-end"}}{{end}}
+567
View File
@@ -0,0 +1,567 @@
package web
import (
"errors"
"net/http"
"strconv"
"strings"
"time"
"supermarket/internal/appmail"
"supermarket/internal/profile"
"supermarket/internal/users"
)
// Settings → Users, for admins on the server edition: inviting people,
// their roles and modules, turning accounts off, and the rest. And the
// invitation's page, where a new user chooses a password.
// grant is a module that can be given to a member.
type grant struct {
ID, Name string
}
// grants are the modules members can be given, as the menu shows them,
// with the Market.
func grants() []grant {
out := make([]grant, 0, len(modules)+1)
for _, m := range modules {
out = append(out, grant{m.ID, m.Name})
}
return append(out, grant{"market", "Market"})
}
func grantName(id string) string {
for _, g := range grants() {
if g.ID == id {
return g.Name
}
}
return id
}
// emailKind is an email a user can choose to get.
type emailKind struct {
ID, Name, Module, Help string
}
var emailKinds = []emailKind{
{"seo-check", "The SEO morning check", "seo", "On days a page's rankings really moved."},
{"seo-report", "The SEO Monday report", "seo", "Each week's report, on Monday morning."},
}
// emailsFor are the emails someone with this membership can get.
func emailsFor(m users.Membership) []emailKind {
var out []emailKind
for _, k := range emailKinds {
if m.Can(k.Module, false) {
out = append(out, k)
}
}
return out
}
// pickEmails keeps the emails chosen on a form that the membership allows.
func pickEmails(m users.Membership, chosen []string) []string {
out := []string{}
for _, k := range emailsFor(m) {
for _, c := range chosen {
if c == k.ID {
out = append(out, k.ID)
break
}
}
}
return out
}
// admin is the signed-in admin, or a 404 (local edition) or 403 page.
func (s *Server) admin(w http.ResponseWriter, r *http.Request) *viewer {
v := s.me(w, r)
if v == nil {
return nil
}
if !v.Member.Admin() {
s.forbidden(w, r)
return nil
}
return v
}
// forbidden is the answer to a request outside someone's access.
func (s *Server) forbidden(w http.ResponseWriter, r *http.Request) {
if r.Header.Get("HX-Request") != "" || !safeMethod(r.Method) {
http.Error(w, "You don't have access to this. An admin can give it to you.", http.StatusForbidden)
return
}
w.WriteHeader(http.StatusForbidden)
s.render(w, r, "forbidden", page{Title: "No access"})
}
// memberRow is a line of the users list.
type memberRow struct {
users.TeamUser
Access string // "Admin", or the modules
InviteEnd time.Time // when an invitation runs out; zero if it has
}
func (s *Server) memberRows() ([]memberRow, error) {
list, err := users.Members(s.DB, users.Team)
if err != nil {
return nil, err
}
now := time.Now()
out := make([]memberRow, 0, len(list))
for _, m := range list {
row := memberRow{TeamUser: m, Access: accessText(m.Membership)}
if m.Status == users.Invited {
if row.InviteEnd, err = users.LinkExpiry(s.DB, users.InviteLink, m.ID, now); err != nil {
return nil, err
}
}
out = append(out, row)
}
return out, nil
}
// accessText says what a membership gives: "Owner", "Admin", or the
// modules ("SEO, Metrics (view)").
func accessText(m users.Membership) string {
switch m.Role {
case users.Owner:
return "Owner"
case users.Admin:
return "Admin"
}
var parts []string
for _, g := range grants() {
switch m.Modules[g.ID] {
case users.Edit:
parts = append(parts, g.Name)
case users.View:
parts = append(parts, g.Name+" (view)")
}
}
if len(parts) == 0 {
return "No modules"
}
return strings.Join(parts, ", ")
}
type usersData struct {
Rows []memberRow
Grants []grant
Form inviteForm
Me int64
}
type inviteForm struct {
Email, Name string
Role users.Role
Modules map[string]users.Access
Problem string
}
func (s *Server) usersPage(w http.ResponseWriter, r *http.Request) {
v := s.admin(w, r)
if v == nil {
return
}
s.renderUsers(w, r, v, inviteForm{Role: users.Member}, http.StatusOK)
}
func (s *Server) renderUsers(w http.ResponseWriter, r *http.Request, v *viewer, f inviteForm, code int) {
rows, err := s.memberRows()
if err != nil {
s.serverError(w, err)
return
}
if code != http.StatusOK {
w.WriteHeader(code)
}
s.render(w, r, "users", page{Title: "Users", Nav: "settings/users", Data: usersData{Rows: rows, Grants: grants(), Form: f, Me: v.User.ID}})
}
// accessFromForm reads a role and modules: role=admin|member, and
// module:<id>=view|edit|"".
func accessFromForm(r *http.Request) (users.Role, map[string]users.Access) {
role := users.Member
if r.PostFormValue("role") == "admin" {
role = users.Admin
}
mods := map[string]users.Access{}
for _, g := range grants() {
switch users.Access(r.PostFormValue("module:" + g.ID)) {
case users.View:
mods[g.ID] = users.View
case users.Edit:
mods[g.ID] = users.Edit
}
}
return role, mods
}
func (s *Server) userInvite(w http.ResponseWriter, r *http.Request) {
v := s.admin(w, r)
if v == nil {
return
}
role, mods := accessFromForm(r)
f := inviteForm{Email: strings.TrimSpace(r.PostFormValue("email")), Name: strings.TrimSpace(r.PostFormValue("name")), Role: role, Modules: mods}
email, err := users.NormalEmail(f.Email)
switch {
case err != nil:
f.Problem = "Give the email address they'll sign in with."
case f.Name == "":
f.Problem = "Give their name, for the invitation."
case role == users.Member && len(mods) == 0:
f.Problem = "Give them at least one module, or make them an admin."
}
if f.Problem == "" {
if _, err := users.ByEmail(s.DB, email); err == nil {
f.Problem = "Someone has that email address already: they're in the list below."
} else if !errors.Is(err, users.ErrNotFound) {
s.serverError(w, err)
return
}
}
if f.Problem != "" {
s.renderUsers(w, r, v, f, http.StatusUnprocessableEntity)
return
}
now := time.Now()
u := &users.User{Email: email, Name: f.Name, Status: users.Invited}
if err := users.Create(s.DB, u, now); err != nil {
s.serverError(w, err)
return
}
if err := users.Join(s.DB, users.Team, u.ID, role, mods, now); err != nil {
s.serverError(w, err)
return
}
if err := s.sendInvitation(v, u); err != nil {
s.serverError(w, err)
return
}
s.Log.Info("users: invited", "user", u.Email, "role", role, "by", v.User.Email)
redirect(w, r, "/settings/users", "invited")
}
// sendInvitation makes a new invitation link (replacing any earlier one)
// and emails it.
func (s *Server) sendInvitation(by *viewer, u *users.User) error {
token, err := users.NewLink(s.DB, users.InviteLink, u.ID, time.Now())
if err != nil {
return err
}
company := "your team"
if p, err := profile.Load(s.DB); err == nil && p.Name != "" {
company = p.Name
}
from := by.User.Name
if from == "" {
from = by.User.Email
}
s.sendMail(appmail.Message{To: u.Email, ToName: u.Name, Subject: from + " invited you to " + company + "'s Supermarket",
Body: "Hello" + nameSuffix(u.Name) + ",\n\n" +
from + " invited you to Supermarket, " + company + "'s marketing suite, at " + s.PublicURL + ".\n\n" +
"To join, choose a password here. The link works once, for 7 days:\n" + s.PublicURL + "/invite/" + token + "\n\n" +
"If you weren't expecting this, ignore it: nothing happens unless you open the link.\n"})
return nil
}
// The page for one user.
type userData struct {
M memberRow
Grants []grant
Me bool
Problem string
SessionsN int
}
// target is the user an admin acts on, by the {id} in the address.
func (s *Server) target(w http.ResponseWriter, r *http.Request) (*users.User, users.Membership, bool) {
id, _ := strconv.ParseInt(r.PathValue("id"), 10, 64)
u, err := users.ByID(s.DB, id)
if errors.Is(err, users.ErrNotFound) {
http.NotFound(w, r)
return nil, users.Membership{}, false
}
if err != nil {
s.serverError(w, err)
return nil, users.Membership{}, false
}
m, err := users.MembershipOf(s.DB, users.Team, u.ID)
if errors.Is(err, users.ErrNotFound) {
http.NotFound(w, r)
return nil, users.Membership{}, false
}
if err != nil {
s.serverError(w, err)
return nil, users.Membership{}, false
}
return u, m, true
}
func (s *Server) userPage(w http.ResponseWriter, r *http.Request) {
v := s.admin(w, r)
if v == nil {
return
}
u, m, ok := s.target(w, r)
if !ok {
return
}
s.renderUser(w, r, v, u, m, "", http.StatusOK)
}
func (s *Server) renderUser(w http.ResponseWriter, r *http.Request, v *viewer, u *users.User, m users.Membership, problem string, code int) {
row := memberRow{TeamUser: users.TeamUser{User: u, Membership: m}, Access: accessText(m)}
if u.Status == users.Invited {
row.InviteEnd, _ = users.LinkExpiry(s.DB, users.InviteLink, u.ID, time.Now())
}
list, _ := users.Sessions(s.DB, u.ID, time.Now())
if code != http.StatusOK {
w.WriteHeader(code)
}
name := u.Name
if name == "" {
name = u.Email
}
s.render(w, r, "user", page{Title: name, Nav: "settings/users", Data: userData{M: row, Grants: grants(), Me: u.ID == v.User.ID, Problem: problem, SessionsN: len(list)}})
}
// userAction is what an admin does to someone: access, resend, withdraw,
// disable, enable, unlock, reset-two-factor, sign-out, remove.
func (s *Server) userAction(w http.ResponseWriter, r *http.Request) {
v := s.admin(w, r)
if v == nil {
return
}
u, m, ok := s.target(w, r)
if !ok {
return
}
action := r.PathValue("action")
back := "/settings/users/" + strconv.FormatInt(u.ID, 10)
// The owner's account is theirs alone, and no one changes their own
// role or turns themselves off.
if m.Role == users.Owner && action != "resend" {
s.renderUser(w, r, v, u, m, "The owner's account can't be changed here.", http.StatusForbidden)
return
}
if u.ID == v.User.ID {
s.renderUser(w, r, v, u, m, "You can't change your own access: ask another admin.", http.StatusForbidden)
return
}
log := func(what string) { s.Log.Info("users: "+what, "user", u.Email, "by", v.User.Email) }
var err error
switch action {
case "access":
role, mods := accessFromForm(r)
if role == users.Member && len(mods) == 0 {
s.renderUser(w, r, v, u, m, "Give them at least one module, or make them an admin.", http.StatusUnprocessableEntity)
return
}
if err = users.Join(s.DB, users.Team, u.ID, role, mods, time.Now()); err == nil {
nm, _ := users.MembershipOf(s.DB, users.Team, u.ID)
u.Emails = pickEmails(nm, u.Emails) // none for modules they've lost
err = users.SaveProfile(s.DB, u)
}
log("access changed to " + accessText(users.Membership{Role: role, Modules: mods}))
if err == nil {
redirect(w, r, back, "saved")
return
}
case "resend":
if u.Status != users.Invited {
http.Redirect(w, r, back, http.StatusSeeOther)
return
}
if err = s.sendInvitation(v, u); err == nil {
log("invitation sent again")
redirect(w, r, back, "invited")
return
}
case "withdraw":
if u.Status != users.Invited {
http.Redirect(w, r, back, http.StatusSeeOther)
return
}
if err = users.Delete(s.DB, u.ID); err == nil {
log("invitation withdrawn")
redirect(w, r, "/settings/users", "withdrawn")
return
}
case "disable":
if err = users.SetStatus(s.DB, u.ID, users.Disabled); err == nil {
_ = users.DropLinks(s.DB, users.InviteLink, u.ID)
_ = users.DropLinks(s.DB, users.ResetLink, u.ID)
log("turned off")
redirect(w, r, back, "disabled")
return
}
case "enable":
status := users.Active
if !u.HasPassword {
status = users.Invited // never joined: invite them again
}
if err = users.SetStatus(s.DB, u.ID, status); err == nil {
if status == users.Invited {
err = s.sendInvitation(v, u)
}
log("turned on")
if err == nil {
redirect(w, r, back, "enabled")
return
}
}
case "unlock":
if err = users.Unlock(s.DB, u.ID); err == nil {
log("unlocked")
redirect(w, r, back, "unlocked")
return
}
case "reset-two-factor":
if err = turnOffTwoFactor(s, u); err == nil {
_, err = users.EndOtherSessions(s.DB, u.ID, "")
log("two-factor sign-in reset")
if err == nil {
redirect(w, r, back, "two-factor-reset")
return
}
}
case "sign-out":
if _, err = users.EndOtherSessions(s.DB, u.ID, ""); err == nil {
log("signed out everywhere")
redirect(w, r, back, "signed-out-user")
return
}
case "remove":
if err = turnOffTwoFactor(s, u); err == nil {
err = users.Delete(s.DB, u.ID)
}
if err == nil {
log("removed")
redirect(w, r, "/settings/users", "removed")
return
}
default:
http.NotFound(w, r)
return
}
s.serverError(w, err)
}
// The invitation's page.
type inviteData struct {
Token, Company string
U *users.User
Emails []emailKind
Zones []string
Problem string
}
func (s *Server) invitePage(w http.ResponseWriter, r *http.Request) {
if !s.signsIn() {
http.NotFound(w, r)
return
}
d, ok := s.inviteData(w, r)
if !ok {
return
}
s.render(w, r, "invite", page{Title: "Join Supermarket", Bare: true, Data: d})
}
// inviteData finds the invitation; when it doesn't work, it says so.
func (s *Server) inviteData(w http.ResponseWriter, r *http.Request) (*inviteData, bool) {
token := r.PathValue("token")
d := &inviteData{Token: token, Zones: commonZones, Company: "the team"}
if p, err := profile.Load(s.DB); err == nil && p.Name != "" {
d.Company = p.Name
}
id, err := users.PeekLink(s.DB, token, users.InviteLink, time.Now())
if err == nil {
d.U, err = users.ByID(s.DB, id)
}
if err == nil && d.U.Status != users.Invited {
err = users.ErrBadLink
}
if errors.Is(err, users.ErrBadLink) || errors.Is(err, users.ErrNotFound) {
w.WriteHeader(http.StatusNotFound)
s.render(w, r, "invite", page{Title: "Join Supermarket", Bare: true, Data: &inviteData{Company: d.Company}})
return nil, false
}
if err != nil {
s.serverError(w, err)
return nil, false
}
m, err := users.MembershipOf(s.DB, users.Team, d.U.ID)
if err != nil {
s.serverError(w, err)
return nil, false
}
d.Emails = emailsFor(m)
return d, true
}
func (s *Server) inviteAccept(w http.ResponseWriter, r *http.Request) {
if !s.signsIn() {
http.NotFound(w, r)
return
}
d, ok := s.inviteData(w, r)
if !ok {
return
}
u := d.U
u.Name = strings.TrimSpace(r.PostFormValue("name"))
u.Title = strings.TrimSpace(r.PostFormValue("title"))
u.TimeZone = strings.TrimSpace(r.PostFormValue("time_zone"))
m, _ := users.MembershipOf(s.DB, users.Team, u.ID)
u.Emails = pickEmails(m, r.PostForm["emails"])
pw := r.PostFormValue("password")
switch {
case u.Name == "":
d.Problem = "Give your name."
case u.TimeZone != "" && !validZone(u.TimeZone):
d.Problem = "That isn't a time zone: choose one from the list, such as Europe/Paris."
default:
if err := users.CheckNewPassword(pw, u.Email); err != nil {
d.Problem = sentence(err.Error()) + "."
} else if pw != r.PostFormValue("password2") {
d.Problem = "The two passwords aren't the same."
}
}
if d.Problem != "" {
w.WriteHeader(http.StatusUnprocessableEntity)
s.render(w, r, "invite", page{Title: "Join Supermarket", Bare: true, Data: d})
return
}
now := time.Now()
if _, err := users.UseLink(s.DB, d.Token, users.InviteLink, now); err != nil {
s.invitePage(w, r)
return
}
if err := users.SaveProfile(s.DB, u); 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.SetStatus(s.DB, u.ID, users.Active); err != nil {
s.serverError(w, err)
return
}
s.Log.Info("users: joined", "user", u.Email)
if err := s.startSession(w, r, u); err != nil {
s.serverError(w, err)
return
}
redirect(w, r, "/", "joined")
}
+259
View File
@@ -0,0 +1,259 @@
package web
import (
"bytes"
"context"
"mime/multipart"
"net/http"
"net/http/httptest"
"net/url"
"regexp"
"strconv"
"strings"
"testing"
"time"
"supermarket/internal/users"
)
var inviteRe = regexp.MustCompile(`http://localhost:8470(/invite/[A-Za-z0-9_-]+)`)
// invite has an admin invite someone, and returns the link's path.
func invite(t *testing.T, s *Server, h http.Handler, admin *http.Cookie, form url.Values) string {
t.Helper()
n := 0
if s.Mail != nil {
n = s.Mail.(interface{ Count() int }).Count()
}
rec := as(h, admin, http.MethodPost, "/settings/users", form)
if rec.Code != http.StatusSeeOther {
t.Fatalf("invite %v: %d %s", form, rec.Code, rec.Body.String())
}
m := waitMail(t, s, form.Get("email"), n+1)
p := inviteRe.FindStringSubmatch(m.Body)
if p == nil {
t.Fatalf("no link in %s", m.Body)
}
return p[1]
}
func TestInviteAndJoin(t *testing.T) {
s, h := newServerEdition(t)
owner := addUser(t, s, "owner@example.com", users.Owner, nil)
oc := sessionFor(t, s, owner)
// Mistakes.
for _, f := range []url.Values{
{"email": {"not an address"}, "name": {"X"}, "role": {"admin"}},
{"email": {"x@example.com"}, "name": {""}, "role": {"admin"}},
{"email": {"x@example.com"}, "name": {"X"}, "role": {"member"}},
{"email": {"OWNER@example.com"}, "name": {"X"}, "role": {"admin"}},
} {
if rec := as(h, oc, http.MethodPost, "/settings/users", f); rec.Code != http.StatusUnprocessableEntity {
t.Errorf("%v: %d", f, rec.Code)
}
}
adminLink := invite(t, s, h, oc, url.Values{"email": {"ada@example.com"}, "name": {"Ada"}, "role": {"admin"}})
memberLink := invite(t, s, h, oc, url.Values{"email": {"sam@example.com"}, "name": {"Sam"}, "role": {"member"}, "module:seo": {"edit"}, "module:metrics": {"bogus"}})
m, _ := users.ByEmail(s.DB, "sam@example.com")
mm, _ := users.MembershipOf(s.DB, users.Team, m.ID)
if m.Status != users.Invited || mm.Role != users.Member || len(mm.Modules) != 1 || mm.Modules["seo"] != users.Edit {
t.Errorf("member %+v %+v", m, mm)
}
rec := as(h, oc, http.MethodGet, "/settings/users", nil)
if !strings.Contains(rec.Body.String(), "Invited") || !strings.Contains(rec.Body.String(), ">SEO<") {
t.Errorf("list: %s", rec.Body.String())
}
// Not signed in: the invitation page is open; signed-in pages aren't.
rec = do(h, http.MethodGet, memberLink, nil, nil)
if rec.Code != http.StatusOK || !strings.Contains(rec.Body.String(), "sam@example.com") || !strings.Contains(rec.Body.String(), "SEO morning check") {
t.Fatalf("invite page: %d %s", rec.Code, rec.Body.String())
}
if rec := postForm(h, memberLink, url.Values{"name": {"Sam"}, "password": {"short"}, "password2": {"short"}}); rec.Code != http.StatusUnprocessableEntity {
t.Errorf("short: %d", rec.Code)
}
rec = postForm(h, memberLink, url.Values{"name": {"Sam Lee"}, "title": {"Writer"}, "time_zone": {"Europe/Paris"},
"password": {"a long enough one"}, "password2": {"a long enough one"}, "emails": {"seo-check", "made-up"}})
if rec.Code != http.StatusSeeOther || rec.Header().Get("Location") != "/?msg=joined" || cookieOf(rec, sessionCookie) == nil {
t.Fatalf("join: %d %s", rec.Code, rec.Body.String())
}
m, _ = users.ByEmail(s.DB, "sam@example.com")
if m.Status != users.Active || m.Name != "Sam Lee" || m.Title != "Writer" || len(m.Emails) != 1 || m.Emails[0] != "seo-check" {
t.Errorf("joined %+v", m)
}
if rec := do(h, http.MethodGet, memberLink, nil, nil); rec.Code != http.StatusNotFound {
t.Errorf("used twice: %d", rec.Code)
}
// A member can't manage users.
mc := sessionFor(t, s, m)
for _, p := range []string{"/settings/users", "/settings/users/" + strconv.FormatInt(owner.ID, 10)} {
if rec := as(h, mc, http.MethodGet, p, nil); rec.Code != http.StatusForbidden {
t.Errorf("member %s: %d", p, rec.Code)
}
}
if rec := as(h, mc, http.MethodPost, "/settings/users", url.Values{"email": {"x@example.com"}, "name": {"X"}, "role": {"admin"}}); rec.Code != http.StatusForbidden {
t.Errorf("member invites: %d", rec.Code)
}
// The invited admin, once joined, can.
postForm(h, adminLink, url.Values{"name": {"Ada"}, "password": {"a long enough one"}, "password2": {"a long enough one"}})
ada, _ := users.ByEmail(s.DB, "ada@example.com")
ac := sessionFor(t, s, ada)
if rec := as(h, ac, http.MethodGet, "/settings/users", nil); rec.Code != http.StatusOK {
t.Errorf("admin: %d", rec.Code)
}
}
func TestUserActions(t *testing.T) {
s, h := newServerEdition(t)
owner := addUser(t, s, "owner@example.com", users.Owner, nil)
admin := addUser(t, s, "ada@example.com", users.Admin, nil)
sam := addUser(t, s, "sam@example.com", users.Member, map[string]users.Access{"seo": users.Edit})
ac := sessionFor(t, s, admin)
sc := sessionFor(t, s, sam)
path := func(u *users.User, action string) string {
return "/settings/users/" + strconv.FormatInt(u.ID, 10) + "/" + action
}
// Nobody changes the owner, nor themselves.
if rec := as(h, ac, http.MethodPost, path(owner, "disable"), url.Values{}); rec.Code != http.StatusForbidden {
t.Errorf("disable the owner: %d", rec.Code)
}
if rec := as(h, ac, http.MethodPost, path(admin, "access"), url.Values{"role": {"member"}, "module:seo": {"view"}}); rec.Code != http.StatusForbidden {
t.Errorf("change yourself: %d", rec.Code)
}
// Access: down to SEO view and Metrics; their SEO emails stay, as SEO
// is still theirs.
sam.Emails = []string{"seo-check"}
users.SaveProfile(s.DB, sam)
if rec := as(h, ac, http.MethodPost, path(sam, "access"), url.Values{"role": {"member"}, "module:seo": {"view"}, "module:metrics": {"edit"}}); rec.Code != http.StatusSeeOther {
t.Errorf("access: %d", rec.Code)
}
m, _ := users.MembershipOf(s.DB, users.Team, sam.ID)
if m.Modules["seo"] != users.View || m.Modules["metrics"] != users.Edit {
t.Errorf("modules %v", m.Modules)
}
if got, _ := users.ByID(s.DB, sam.ID); len(got.Emails) != 1 {
t.Errorf("emails %v", got.Emails)
}
// Losing SEO loses its emails.
as(h, ac, http.MethodPost, path(sam, "access"), url.Values{"role": {"member"}, "module:metrics": {"edit"}})
if got, _ := users.ByID(s.DB, sam.ID); len(got.Emails) != 0 {
t.Errorf("emails kept: %v", got.Emails)
}
// Lock, unlock.
for i := 0; i < users.LockAfter; i++ {
users.FailedSignIn(s.DB, sam, time.Now())
}
if rec := as(h, ac, http.MethodGet, "/settings/users/"+strconv.FormatInt(sam.ID, 10), nil); !strings.Contains(rec.Body.String(), "/unlock") {
t.Errorf("no unlock button: %s", rec.Body.String())
}
as(h, ac, http.MethodPost, path(sam, "unlock"), url.Values{})
if got, _ := users.ByID(s.DB, sam.ID); got.Locked() {
t.Error("still locked")
}
// Reset two-factor: off, and signed out.
users.SetTwoFactor(s.DB, sam, true, []string{"x"})
s.Secrets.Set(map[string]string{users.TOTPSecretName(sam.ID): "ABCD"})
as(h, ac, http.MethodPost, path(sam, "reset-two-factor"), url.Values{})
if got, _ := users.ByID(s.DB, sam.ID); got.TwoFactor || s.Secrets.Get(users.TOTPSecretName(sam.ID)) != "" {
t.Error("two-factor not reset")
}
if rec := as(h, sc, http.MethodGet, "/seo", nil); rec.Code != http.StatusSeeOther {
t.Error("not signed out after the reset")
}
// Disable, enable.
sc = sessionFor(t, s, sam)
as(h, ac, http.MethodPost, path(sam, "disable"), url.Values{})
if rec := as(h, sc, http.MethodGet, "/seo", nil); rec.Code != http.StatusSeeOther {
t.Error("disabled, still signed in")
}
as(h, ac, http.MethodPost, path(sam, "enable"), url.Values{})
if got, _ := users.ByID(s.DB, sam.ID); got.Status != users.Active {
t.Errorf("enabled: %s", got.Status)
}
// Withdrawing an invitation removes it; removing someone, them.
link := invite(t, s, h, ac, url.Values{"email": {"kim@example.com"}, "name": {"Kim"}, "role": {"admin"}})
kim, _ := users.ByEmail(s.DB, "kim@example.com")
if rec := as(h, ac, http.MethodPost, path(kim, "withdraw"), url.Values{}); rec.Code != http.StatusSeeOther {
t.Errorf("withdraw: %d", rec.Code)
}
if rec := do(h, http.MethodGet, link, nil, nil); rec.Code != http.StatusNotFound {
t.Errorf("withdrawn link: %d", rec.Code)
}
as(h, ac, http.MethodPost, path(sam, "remove"), url.Values{})
if _, err := users.ByID(s.DB, sam.ID); err == nil {
t.Error("not removed")
}
if n, _ := users.Count(s.DB); n != 2 {
t.Errorf("%d users", n)
}
}
func TestPhoto(t *testing.T) {
s, h := newServerEdition(t)
u := addUser(t, s, "owner@example.com", users.Owner, nil)
c := sessionFor(t, s, u)
upload := func(name string, data []byte, withToken bool) int {
var body bytes.Buffer
mw := multipart.NewWriter(&body)
fw, _ := mw.CreateFormFile("photo", name)
fw.Write(data)
mw.Close()
target := "/settings/account/photo"
if withToken {
target += "?csrf=" + testCSRF
}
req := httptest.NewRequest(http.MethodPost, target, &body)
req.Host = "localhost:8470"
req.Header.Set("Content-Type", mw.FormDataContentType())
req.Header.Set("Origin", "http://localhost:8470")
req.AddCookie(c)
req.AddCookie(&http.Cookie{Name: csrfCookie, Value: testCSRF})
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
return rec.Code
}
// The page's upload form carries the token in its address.
if rec := as(h, c, http.MethodGet, "/settings/account", nil); !strings.Contains(rec.Body.String(), `action="/settings/account/photo?csrf=`) {
t.Error("upload form without its token")
}
png := []byte("\x89PNG\r\n\x1a\n" + strings.Repeat("\x00", 100))
if code := upload("me.png", png, false); code != http.StatusForbidden {
t.Errorf("no token: %d", code)
}
if code := upload("me.txt", []byte("hello"), true); code != http.StatusUnprocessableEntity {
t.Errorf("not a picture: %d", code)
}
if code := upload("big.png", append(png, make([]byte, maxPhoto)...), true); code != http.StatusUnprocessableEntity {
t.Errorf("too big: %d", code)
}
if code := upload("me.png", png, true); code != http.StatusSeeOther {
t.Fatalf("upload: %d", code)
}
got, _ := users.ByID(s.DB, u.ID)
if !strings.HasPrefix(got.Photo, "photos/") || !strings.HasSuffix(got.Photo, ".png") {
t.Fatalf("photo %q", got.Photo)
}
rec := as(h, c, http.MethodGet, "/users/"+strconv.FormatInt(u.ID, 10)+"/photo", nil)
if rec.Code != http.StatusOK || rec.Header().Get("Content-Type") != "image/png" || !bytes.Equal(rec.Body.Bytes(), png) {
t.Errorf("photo: %d %s", rec.Code, rec.Header().Get("Content-Type"))
}
if rec := do(h, http.MethodGet, "/users/"+strconv.FormatInt(u.ID, 10)+"/photo", nil, nil); rec.Code != http.StatusSeeOther {
t.Errorf("not signed in: %d", rec.Code)
}
as(h, c, http.MethodPost, "/settings/account/photo?remove=1", url.Values{})
if got, _ := users.ByID(s.DB, u.ID); got.Photo != "" {
t.Error("not removed")
}
if _, err := s.Files.Stat(context.Background(), got.Photo); err == nil {
t.Error("old file kept")
}
}