Phase 10, part 5: access enforced on every page, form and fragment

One table maps every address to an area (a module, Settings, anything
signed in, or public); each route is checked against it, and the app won't
start with a route missing from it. Changing needs edit on the module. For
members who may only view, forms that would change something are shown
disabled and htmx buttons hidden. The menu, the Overview, Search and the
SEO emails follow each person's modules; Settings is for admins.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-25 09:13:16 -07:00
co-authored by Claude Opus 5.5
parent 47a504b7b2
commit 2b9d04297f
13 changed files with 578 additions and 41 deletions
+30
View File
@@ -2263,6 +2263,36 @@ starts** (multi-tenant still doesn't).
is on Your account rather than the invitation page, to keep joining to
one plain form.
**Part 5 built 2026-11-25** on `phase10`.
- `routeAreas` (internal/web/access.go) is the one table: address
prefixes to areas: a module (content, prospects, seo, sites, metrics,
market), `admin` (Settings, `/auth`), `signed-in` (the Overview, Search,
Your account, photos) or `public`. Every route is registered through a
wrapper that looks its area up and checks it on each request; a route
missing from the table stops `Handler()`, so the app won't start and
every web test fails. `TestEveryRouteHasAnArea` also checks a made-up one.
- A GET reads; anything else changes, which needs *edit* on the module.
Outside someone's access: the 403 page, or a plain 403 for htmx and
forms. Not signed in: to `/signin`.
- For members, pages are rewritten as they're rendered: each form that
posts to an area they can't change is wrapped in a disabled
`<fieldset class="readonly">` (its text stays readable, its buttons are
hidden) and gets no CSRF token; htmx buttons that would change something
are hidden. The same table decides, so the page and the server agree.
- The sidebar, the Overview's cards, the Market link and Search's groups
show only the viewer's areas; the setup steps and import notes only to
admins. Settings and its tabs are for admins; others see Your account
(`/settings` takes them there).
- The SEO morning check and Monday report, on the server edition, go to
each active person with SEO who chose them (Your account), through the
app's mail, with how to stop; the SEO settings' own two boxes are for the
local edition.
- Checked: an owner invites an admin and an SEO-only member; the member
signs in and sees only SEO; 47 pages across every area answer 200 or 403
as they should, for the member, the admin and the owner; changes and
htmx fragments outside SEO answer 403. (The log part of *done when*
comes with part 8.)
1. **Users and sessions.**
- Tables:
- `users`: email, name, kind (person or agent), status (invited,
+226
View File
@@ -0,0 +1,226 @@
package web
import (
"bytes"
"fmt"
"html"
"net/http"
"regexp"
"strings"
)
// Who may reach what. Every route belongs to an area: a module, Settings
// (admins), anything signed in, or public. One table maps addresses to
// areas, by their first segments; the app won't start with a route that
// isn't in it. A GET reads; anything else changes, which a member needs
// edit on the module for.
const (
areaPublic = "public" // no sign-in: the sign-in pages, static files, MCP (its own key)
areaSignedIn = "signed-in" // anyone signed in: the Overview, Search, Your account
areaAdmin = "admin" // admins and the owner: Settings, users, connections
)
// routeAreas maps addresses to areas. An entry matches its path and
// everything under it (/seo matches /seo/check); one starting with = only
// itself. The longest match wins, and an exact one over a prefix.
var routeAreas = map[string]string{
"/static": areaPublic, "=/favicon.ico": areaPublic, "=/healthz": areaPublic, "=/mcp": areaPublic,
"/signin": areaPublic, "=/signout": areaPublic, "=/forgot": areaPublic, "/reset": areaPublic,
"/setup": areaPublic, "/invite": areaPublic,
"=/": areaSignedIn, "=/search": areaSignedIn, "/settings/account": areaSignedIn,
"/users": areaSignedIn, "=/settings": areaSignedIn,
// Old addresses that only redirect.
"=/profile": areaSignedIn, "=/core": areaSignedIn,
"/settings": areaAdmin, "/auth": areaAdmin,
"/content": "content", "/posts": "content", "/inbox": "content", "/drafts": "content", "/reddit": "content",
"/prospects": "prospects", "/signals": "prospects", "/lead-sources": "prospects", "/funnel": "prospects",
"/outreach": "prospects", "/crm": "prospects",
"/seo": "seo",
"/sites": "sites", "/preview": "sites",
"/metrics": "metrics",
"/market": "market", "/inventory": "market",
}
// areaOf is the area of a path (or a route's pattern, without its method).
func areaOf(path string) (string, bool) {
path = strings.TrimSuffix(path, "{$}")
if len(path) > 1 {
path = strings.TrimSuffix(path, "/")
}
best, area := -1, ""
for prefix, a := range routeAreas {
exact := strings.HasPrefix(prefix, "=")
p := strings.TrimPrefix(prefix, "=")
ok := path == p || (!exact && strings.HasPrefix(path, p+"/"))
score := 2 * len(p) // an exact entry beats a prefix of the same path
if exact {
score++
}
if ok && score > best {
best, area = score, a
}
}
return area, best >= 0
}
// publicPath says whether a path is reached without signing in.
func publicPath(p string) bool {
a, ok := areaOf(p)
return ok && a == areaPublic
}
// can says whether the viewer may read (write false) or change things in
// an area.
func (v *viewer) can(area string, write bool) bool {
switch area {
case areaPublic:
return true
case areaSignedIn:
return v.User != nil || v == localOwner
case areaAdmin:
return v.Member.Admin()
}
return v.Member.Can(area, write)
}
// canPost says whether the viewer may send a form to a path.
func (v *viewer) canPost(path string) bool {
if i := strings.IndexAny(path, "?#"); i >= 0 {
path = path[:i]
}
a, ok := areaOf(path)
return ok && v.can(a, true)
}
// routes registers handlers, each behind the check for its area.
type routes struct {
s *Server
mux *http.ServeMux
unmapped []string
}
func (rt *routes) HandleFunc(pattern string, fn http.HandlerFunc) {
rt.Handle(pattern, fn)
}
func (rt *routes) Handle(pattern string, h http.Handler) {
path := pattern
if i := strings.Index(pattern, " "); i >= 0 {
path = pattern[i+1:]
}
area, ok := areaOf(path)
if !ok {
rt.unmapped = append(rt.unmapped, pattern)
return
}
rt.mux.Handle(pattern, rt.s.allow(area, h))
}
func (rt *routes) err() error {
if len(rt.unmapped) == 0 {
return nil
}
return fmt.Errorf("routes without an area (add them to routeAreas, in access.go): %s", strings.Join(rt.unmapped, ", "))
}
// allow lets a request through if the viewer may reach its area: reading,
// or for anything but GET, changing.
func (s *Server) allow(area string, next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
v := viewerOf(r)
if area != areaPublic && v.User == nil && v != localOwner {
s.toSignIn(w, r)
return
}
if !v.can(area, !safeMethod(r.Method)) {
s.forbidden(w, r)
return
}
next.ServeHTTP(w, r)
})
}
// Pages for members who may only view: every form that sends to a module
// they can't change is shown inside a disabled fieldset, so they see what
// it holds but can't submit it (and its buttons are hidden, app.css), and
// htmx buttons that would change something are hidden. The server
// refuses those requests anyway (allow).
var (
formClose = regexp.MustCompile(`(?i)</form\s*>`)
hxChange = regexp.MustCompile(`(?is)<[a-z]+\b[^>]*\bhx-(?:post|put|patch|delete)\s*=\s*"([^"]*)"[^>]*>`)
)
// rewriteForms adds the CSRF token to the forms the viewer may send, and
// disables the others. here is the page's own path, for forms without an
// action.
func rewriteForms(page []byte, token, here string, v *viewer) []byte {
if token == "" && v == nil {
return page
}
var out bytes.Buffer
out.Grow(len(page) + 1024)
rest := page
for {
loc := formTag.FindIndex(rest)
if loc == nil {
out.Write(rest)
break
}
tag := rest[loc[0]:loc[1]]
out.Write(rest[:loc[0]])
rest = rest[loc[1]:]
method, action, _ := formAttrs(tag)
target := action
if target == "" {
target = here
}
if method != "post" || !ownAddress(action) || v == nil || v.canPost(target) {
out.Write(addCSRF(tag, token))
continue
}
// Shown, not sent: the fieldset holds everything up to </form>.
out.Write(tag)
out.WriteString(`<fieldset class="readonly" disabled>`)
end := formClose.FindIndex(rest)
if end == nil {
out.Write(rest)
out.WriteString(`</fieldset>`)
rest = nil
continue
}
out.Write(rest[:end[0]])
out.WriteString(`</fieldset>`)
out.Write(rest[end[0]:end[1]])
rest = rest[end[1]:]
}
if v == nil {
return out.Bytes()
}
return hxChange.ReplaceAllFunc(out.Bytes(), func(tag []byte) []byte {
m := hxChange.FindSubmatch(tag)
if v.canPost(html.UnescapeString(string(m[1]))) {
return tag
}
return append(tag[:len(tag)-1:len(tag)-1], []byte(` hidden disabled>`)...)
})
}
// formAttrs reads a form tag's method (lower case), action and enctype.
func formAttrs(tag []byte) (method, action, enctype string) {
for _, m := range attrRe.FindAllSubmatch(tag, -1) {
switch strings.ToLower(string(m[1])) {
case "method":
method = strings.ToLower(string(m[2]))
case "action":
action = html.UnescapeString(string(m[2]))
case "enctype":
enctype = strings.ToLower(string(m[2]))
}
}
return
}
+206
View File
@@ -0,0 +1,206 @@
package web
import (
"net/http"
"net/url"
"strings"
"testing"
"supermarket/internal/appmail"
"supermarket/internal/profile"
"supermarket/internal/users"
)
func TestEveryRouteHasAnArea(t *testing.T) {
// The app's own routes: Handler fails if one has no area.
s, _ := newTestServer(t, nil)
if _, err := s.Handler(); err != nil {
t.Fatal(err)
}
// A new route that isn't in the table is caught.
rt := &routes{s: s, mux: http.NewServeMux()}
rt.HandleFunc("GET /brand-new/{id}", func(http.ResponseWriter, *http.Request) {})
rt.HandleFunc("GET /seo/new-page", func(http.ResponseWriter, *http.Request) {})
if err := rt.err(); err == nil || !strings.Contains(err.Error(), "/brand-new/{id}") || strings.Contains(err.Error(), "/seo/new-page") {
t.Errorf("unmapped: %v", err)
}
for path, want := range map[string]string{
"/": areaSignedIn, "/seo": "seo", "/seo/check": "seo", "/seosomething": "", "/settings/account": areaSignedIn,
"/settings/account/two-factor": areaSignedIn, "/settings": areaSignedIn, "/settings/ai": areaAdmin,
"/market/1": "market", "/preview/0/x/index.html": "sites", "/static/app.css": areaPublic, "/mcp": areaPublic,
"/mcp/x": "", "/signin/code": areaPublic, "/{$}": areaSignedIn,
} {
got, ok := areaOf(path)
if got != want || ok != (want != "") {
t.Errorf("areaOf(%s) = %q %v, want %q", path, got, ok, want)
}
}
}
// pages are GET addresses across every area, for the access tests.
var accessPages = []string{"/", "/search?q=x", "/settings/account",
"/market", "/market/new", "/settings/profile", "/settings/ai", "/settings/accounts", "/settings/core", "/settings/users",
"/settings/email", "/settings/tracking", "/settings/search", "/settings/sources", "/settings/backups", "/settings/about",
"/content", "/posts", "/content/scheduled", "/content/published",
"/prospects", "/prospects/new", "/prospects/suppressed", "/outreach", "/crm", "/signals", "/signals/new",
"/seo", "/seo/check", "/seo/report", "/seo/next", "/seo/links", "/seo/audit", "/seo/changes", "/seo/keywords", "/seo/briefs", "/seo/engines",
"/metrics", "/metrics/customers", "/metrics/spend", "/metrics/clv", "/metrics/publish",
"/sites", "/sites/previews", "/sites/pages", "/sites/publishing", "/sites/forms", "/sites/new"}
func TestAccessEnforced(t *testing.T) {
s, h := newServerEdition(t)
profile.Save(s.DB, &profile.Profile{Name: "Acme", Description: "Widgets.", Websites: []profile.Website{{URL: "https://acme.example"}}})
owner := addUser(t, s, "owner@example.com", users.Owner, nil)
oc := sessionFor(t, s, owner)
// The owner invites an admin and a member with only SEO.
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"}})
for _, l := range []string{adminLink, memberLink} {
if rec := postForm(h, l, url.Values{"name": {"X"}, "password": {"a long enough one"}, "password2": {"a long enough one"}}); rec.Code != http.StatusSeeOther {
t.Fatalf("join: %d", rec.Code)
}
}
// The member signs in.
rec := signin(h, "203.0.113.20", url.Values{"email": {"sam@example.com"}, "password": {"a long enough one"}})
sc := cookieOf(rec, sessionCookie)
if sc == nil {
t.Fatalf("member sign-in: %d", rec.Code)
}
ada, _ := users.ByEmail(s.DB, "ada@example.com")
ac := sessionFor(t, s, ada)
// The menu shows only SEO.
home := as(h, sc, http.MethodGet, "/", nil).Body.String()
for _, l := range []string{`href="/posts"`, `href="/signals"`, `href="/metrics"`, `href="/sites"`, `href="/market"`, `href="/settings/profile"`} {
if strings.Contains(home, l) {
t.Errorf("member's page links to %s", l)
}
}
if !strings.Contains(home, `href="/seo/check"`) || !strings.Contains(home, `href="/settings/account"`) {
t.Error("member's page lacks SEO or Your account")
}
for _, p := range accessPages {
area, _ := areaOf(strings.SplitN(p, "?", 2)[0])
want := http.StatusForbidden
if area == "seo" || area == areaSignedIn {
want = http.StatusOK
}
if rec := as(h, sc, http.MethodGet, p, nil); rec.Code != want {
t.Errorf("member GET %s: %d, want %d", p, rec.Code, want)
}
// The admin and the owner reach everything.
for who, c := range map[string]*http.Cookie{"admin": ac, "owner": oc} {
if rec := as(h, c, http.MethodGet, p, nil); rec.Code != http.StatusOK {
t.Errorf("%s GET %s: %d", who, p, rec.Code)
}
}
}
// Changes outside SEO, and htmx fragments, are refused too.
for _, p := range []string{"/settings/profile", "/market/save", "/metrics/sync", "/sites/sync", "/signals/new", "/drafts/1/publish", "/settings/users", "/settings/ai/test"} {
if rec := as(h, sc, http.MethodPost, p, url.Values{"name": {"x"}}); rec.Code != http.StatusForbidden {
t.Errorf("member POST %s: %d", p, rec.Code)
}
}
for _, p := range []string{"/settings/core/checks", "/crm/reach", "/settings/ai/models"} {
rec := do(h, http.MethodGet, p, nil, map[string]string{"HX-Request": "true", "Cookie": sessionCookie + "=" + sc.Value})
if rec.Code != http.StatusForbidden {
t.Errorf("member htmx %s: %d", p, rec.Code)
}
}
// Search shows only their modules.
if body := as(h, sc, http.MethodGet, "/search?q=company+profile", nil).Body.String(); strings.Contains(body, `href="/settings/profile"`) {
t.Error("search shows Settings to a member")
}
// What SEO changes, they can.
if rec := as(h, sc, http.MethodPost, "/seo/next/dismiss", url.Values{"page": {"/x"}}); rec.Code == http.StatusForbidden {
t.Errorf("member POST in SEO: %d", rec.Code)
}
}
func TestViewOnlyMember(t *testing.T) {
s, h := newServerEdition(t)
addUser(t, s, "owner@example.com", users.Owner, nil)
profile.Save(s.DB, &profile.Profile{Name: "Acme", Description: "Widgets.", Websites: []profile.Website{{URL: "https://acme.example"}}})
jo := addUser(t, s, "jo@example.com", users.Member, map[string]users.Access{"seo": users.View, "market": users.Edit})
c := sessionFor(t, s, jo)
rec := as(h, c, http.MethodGet, "/seo/audit", nil)
if rec.Code != http.StatusOK {
t.Fatalf("view: %d", rec.Code)
}
body := rec.Body.String()
if !strings.Contains(body, `<fieldset class="readonly" disabled>`) {
t.Error("SEO's forms aren't disabled")
}
if strings.Contains(body, `<input type="hidden" name="csrf" value="`+testCSRF) && strings.Contains(body, `action="/seo/audit?site=0" class="card row wrap" data-busy="Starting…"><input`) {
t.Error("a disabled form carries the token")
}
if rec := as(h, c, http.MethodPost, "/seo/audit?site=0", url.Values{}); rec.Code != http.StatusForbidden {
t.Errorf("view member POST: %d", rec.Code)
}
// The search box (GET) and sign-out still work; the Market, which they
// edit, keeps its forms.
if !strings.Contains(body, `action="/signout"><input type="hidden" name="csrf"`) {
t.Error("sign-out form disabled")
}
rec = as(h, c, http.MethodGet, "/market/new", nil)
if strings.Contains(rec.Body.String(), `class="readonly"`) {
t.Error("the Market's forms are disabled for an editor")
}
}
func TestRewriteForms(t *testing.T) {
v := &viewer{Member: users.Membership{Role: users.Member, Modules: map[string]users.Access{"seo": users.View, "market": users.Edit}}, User: &users.User{ID: 2}}
in := `<form method="post" action="/seo/keywords"><textarea>keep me</textarea><button>Find</button></form>` +
`<form method="post" action="/market/save"><button>Save</button></form>` +
`<form method="get" action="/seo"><input name="q"></form>` +
`<form method="post"><button>Here</button></form>` +
`<button hx-post="/seo/changes/suggest">Suggest</button><button hx-get="/seo/audit/status">Status</button>`
out := string(rewriteForms([]byte(in), "T", "/seo/check", v))
want := `<form method="post" action="/seo/keywords"><fieldset class="readonly" disabled><textarea>keep me</textarea><button>Find</button></fieldset></form>` +
`<form method="post" action="/market/save"><input type="hidden" name="csrf" value="T"><button>Save</button></form>` +
`<form method="get" action="/seo"><input name="q"></form>` +
`<form method="post"><fieldset class="readonly" disabled><button>Here</button></fieldset></form>` +
`<button hx-post="/seo/changes/suggest" hidden disabled>Suggest</button><button hx-get="/seo/audit/status">Status</button>`
if out != want {
t.Errorf("got\n%s\nwant\n%s", out, want)
}
}
func TestLocalOwnerReachesEverything(t *testing.T) {
_, h := newTestServer(t, nil)
for _, p := range accessPages {
if p == "/settings/account" || p == "/settings/users" {
continue // there are no accounts on the local edition
}
if rec := do(h, http.MethodGet, p, nil, nil); rec.Code != http.StatusOK {
t.Errorf("local GET %s: %d", p, rec.Code)
}
}
if body := do(h, http.MethodGet, "/seo/keywords", nil, nil).Body.String(); strings.Contains(body, "readonly") {
t.Error("local forms disabled")
}
}
func TestMailTeam(t *testing.T) {
s, _ := newServerEdition(t)
a := addUser(t, s, "a@example.com", users.Member, map[string]users.Access{"seo": users.View})
b := addUser(t, s, "b@example.com", users.Member, map[string]users.Access{"metrics": users.Edit})
c := addUser(t, s, "c@example.com", users.Admin, nil)
d := addUser(t, s, "d@example.com", users.Admin, nil)
for _, u := range []*users.User{a, b, c} {
u.Emails = []string{"seo-check"}
users.SaveProfile(s.DB, u)
}
users.SetStatus(s.DB, c.ID, users.Disabled)
_ = d // didn't ask
if n := s.mailTeam(t.Context(), "seo-check", "Moved", "Text"); n != 1 {
t.Errorf("sent %d", n)
}
m := s.Mail.(interface{ Last(string) *appmail.Message }).Last("a@example.com")
if m == nil || !strings.Contains(m.Body, "/settings/account") {
t.Errorf("mail %+v", m)
}
}
+6 -24
View File
@@ -79,18 +79,6 @@ const (
csrfHeader = "X-CSRF-Token" // htmx sends it (app.js)
)
// publicPaths are reached without signing in.
func publicPath(p string) bool {
switch {
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, "/invite/"):
return true
}
return false
}
// sessions finds who each request comes from. On the server edition,
// anyone not signed in is sent to sign in.
func (s *Server) sessions(next http.Handler) http.Handler {
@@ -293,17 +281,7 @@ func addCSRF(page []byte, token string) []byte {
}
field := []byte(`<input type="hidden" name="` + csrfField + `" value="` + html.EscapeString(token) + `">`)
return formTag.ReplaceAllFunc(page, func(tag []byte) []byte {
var method, action, enctype string
for _, m := range attrRe.FindAllSubmatch(tag, -1) {
switch strings.ToLower(string(m[1])) {
case "method":
method = strings.ToLower(string(m[2]))
case "action":
action = html.UnescapeString(string(m[2]))
case "enctype":
enctype = strings.ToLower(string(m[2]))
}
}
method, action, enctype := formAttrs(tag)
if method != "post" || !ownAddress(action) {
return tag
}
@@ -335,5 +313,9 @@ func withCSRF(r *http.Request, exec func(*bytes.Buffer) error) ([]byte, error) {
if err := exec(&buf); err != nil {
return nil, err
}
return addCSRF(buf.Bytes(), csrfToken(r)), nil
var v *viewer
if vv := viewerOf(r); !vv.Member.Admin() {
v = vv // forms they can't send are disabled
}
return rewriteForms(buf.Bytes(), csrfToken(r), r.URL.Path, v), nil
}
+2 -1
View File
@@ -163,7 +163,8 @@ func (s *Server) dashboard(w http.ResponseWriter, r *http.Request) {
s.render(w, r, "dashboard", page{Title: "Overview", Nav: "home", Data: map[string]any{
"Steps": steps,
"Modules": modules,
"Modules": visibleModules(viewerOf(r)),
"Admin": viewerOf(r).Member.Admin(),
"ImportStatus": s.ImportStatus,
"ImportErr": errString(s.ImportErr),
"QueuedPosts": queued,
+4 -3
View File
@@ -58,7 +58,7 @@ func (s *Server) searchPage(w http.ResponseWriter, r *http.Request) {
total := 0
if q != "" {
var err error
groups, err = s.search(q)
groups, err = s.search(q, viewerOf(r))
if err != nil {
s.serverError(w, err)
return
@@ -77,7 +77,7 @@ func (s *Server) searchPage(w http.ResponseWriter, r *http.Request) {
// search looks for q in the inventory, fetched items, posts and settings.
// Every word must appear (case-insensitively), in any order.
func (s *Server) search(q string) ([]hitGroup, error) {
func (s *Server) search(q string, v *viewer) ([]hitGroup, error) {
words := strings.Fields(strings.ToLower(q))
matches := func(texts ...string) bool {
all := strings.ToLower(strings.Join(texts, "\n"))
@@ -202,8 +202,9 @@ func (s *Server) search(q string) ([]hitGroup, error) {
}
var groups []hitGroup
area := map[string]string{"Posts": "content", "Fetched items": "content", "Market": "market", "Prospects": "prospects", "Settings": areaAdmin}
for _, g := range []hitGroup{{"Posts", posts}, {"Fetched items", found}, {"Market", inv}, {"Prospects", prospectHits}, {"Settings", settings}} {
if len(g.Hits) > 0 {
if len(g.Hits) > 0 && v.can(area[g.Name], false) {
groups = append(groups, g)
}
}
+7 -3
View File
@@ -462,7 +462,9 @@ func (s *Server) writeReport(ctx context.Context, site seoSite, email bool) (*se
if err := seo.Save(s.DB, rep); err != nil {
return nil, err
}
if email && seo.LoadSettings(s.DB).EmailReport {
if email && s.signsIn() {
s.mailTeam(ctx, "seo-report", "SEO report: "+site.URL+", week to "+rep.WeekTo, rep.Text())
} else if email && seo.LoadSettings(s.DB).EmailReport {
if set, mb, err := s.mailbox(); err == nil {
ectx, cancel := context.WithTimeout(ctx, 2*time.Minute)
err = outreach.SendToSelf(ectx, set, mb, "SEO report: "+site.URL+", week to "+rep.WeekTo, rep.Text(), time.Now())
@@ -504,7 +506,7 @@ func checkEmailedKey(property string) string { return "seo:check-emailed:" + pro
// final data, when something really moved and the settings ask for it.
func (s *Server) dailyChecks(ctx context.Context) {
set := seo.LoadSettings(s.DB)
if !set.EmailCheck {
if !set.EmailCheck && !s.signsIn() {
return
}
for _, site := range s.seoSites() {
@@ -524,7 +526,9 @@ func (s *Server) dailyChecks(ctx context.Context) {
if sent == c.To {
continue
}
if !c.Quiet() {
if !c.Quiet() && s.signsIn() {
s.mailTeam(ctx, "seo-check", fmt.Sprintf("SEO morning check: %s, %d moved", site.URL, len(c.Moves)), c.Text(site.URL))
} else if !c.Quiet() {
mailSet, mb, err := s.mailbox()
if err != nil {
return // email isn't set up: nothing to send with
+28 -4
View File
@@ -125,7 +125,7 @@ func (s *Server) Handler() (http.Handler, error) {
return nil, err
}
mux := http.NewServeMux()
mux := &routes{s: s, mux: http.NewServeMux()}
static, _ := fs.Sub(staticFS, "static")
mux.Handle("GET /static/", http.StripPrefix("/static/", http.FileServerFS(static)))
// Browsers ask for /favicon.ico whatever the page says.
@@ -186,6 +186,10 @@ func (s *Server) Handler() (http.Handler, error) {
// Settings: the profile, social accounts, AI, and the Core & Hermes.
mux.HandleFunc("GET /settings", func(w http.ResponseWriter, r *http.Request) {
if !viewerOf(r).Member.Admin() {
http.Redirect(w, r, "/settings/account", http.StatusSeeOther)
return
}
http.Redirect(w, r, "/settings/profile", http.StatusSeeOther)
})
mux.HandleFunc("GET /settings/profile", s.profilePage)
@@ -345,7 +349,10 @@ func (s *Server) Handler() (http.Handler, error) {
})
}
return s.guard(s.csrf(s.sessions(mux))), nil
if err := mux.err(); err != nil {
return nil, err
}
return s.guard(s.csrf(s.sessions(mux.mux))), nil
}
// guard protects the app, which has no login because only this machine can
@@ -582,8 +589,25 @@ var modules = []module{
{"metrics", "Metrics", "Phase 4", "MRR, NRR, CAC and CLV from Stripe, with pipeline influence from EspoCRM.", "/metrics"},
}
// Modules is for the menu.
func (p page) Modules() []module { return modules }
// Modules is for the menu: the viewer's.
func (p page) Modules() []module { return visibleModules(p.Viewer) }
// visibleModules are the modules a viewer may see.
func visibleModules(v *viewer) []module {
if v == nil {
return modules
}
out := make([]module, 0, len(modules))
for _, m := range modules {
if v.can(m.ID, false) {
out = append(out, m)
}
}
return out
}
// Can is for templates: whether the viewer may see an area.
func (p page) Can(area string) bool { return p.Viewer == nil || p.Viewer.can(area, false) }
// render writes a full page, or only its "content" block for htmx requests
// that ask for a fragment.
+6
View File
@@ -511,3 +511,9 @@ fieldset.access .access-grid label { margin: 0; }
.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; }
/* A form a member may only view (access.go): what it holds stays
readable; its buttons go. */
fieldset.readonly { border: 0; padding: 0; margin: 0; min-width: 0; }
fieldset.readonly button, fieldset.readonly input[type="submit"], fieldset.readonly input[type="file"] { display: none; }
fieldset.readonly input, fieldset.readonly textarea, fieldset.readonly select { background: hsl(var(--muted)); color: hsl(var(--foreground)); }
+8 -2
View File
@@ -22,7 +22,12 @@
{{end}}
</div>
{{if .Pending}}
{{if not .Modules}}
<section class="card empty"><p>You don't have any modules yet. An admin can give you some, under Settings → Users.</p></section>
{{end}}
{{if not .Admin}}
{{else if .Pending}}
<section class="card">
<h2>Setup</h2>
<ul class="steps">
@@ -45,7 +50,8 @@
</details>
{{end}}
{{if .ImportErr}}
{{if not .Admin}}
{{else if .ImportErr}}
<section class="card warn">
<h2>Import from the old app failed</h2>
<p>{{.ImportErr}}</p>
+6 -4
View File
@@ -35,9 +35,9 @@
</form>
<nav class="nav" aria-label="Main">
<a href="/" {{if eq .Nav "home"}}aria-current="page"{{end}}>{{template "icon" "overview"}}<span>Overview</span></a>
<a href="/market" {{if eq .Nav "inventory"}}aria-current="page"{{end}}>{{template "icon" "inventory"}}<span>Market</span></a>
{{if .Can "market"}}<a href="/market" {{if eq .Nav "inventory"}}aria-current="page"{{end}}>{{template "icon" "inventory"}}<span>Market</span></a>{{end}}
<div class="nav-label">Modules</div>
{{if .Modules}}<div class="nav-label">Modules</div>{{end}}
{{$nav := .Nav}}{{$inbox := .Inbox}}
{{range .Modules}}
{{if .Link}}
@@ -101,7 +101,7 @@
{{end}}
</nav>
<div class="sidebar-foot">
<a href="/settings/profile" {{if hasPrefix .Nav "settings"}}aria-current="page"{{end}}>{{template "icon" "settings"}}<span>Settings</span></a>
{{if .Can "admin"}}<a href="/settings/profile" {{if hasPrefix .Nav "settings"}}aria-current="page"{{end}}>{{template "icon" "settings"}}<span>Settings</span></a>{{end}}
{{with .Viewer}}{{with .User}}<div class="who"><a href="/settings/account" title="Your account">{{if .Name}}{{.Name}}{{else}}{{.Email}}{{end}}</a>
<form method="post" action="/signout"><button type="submit" class="secondary small">Sign out</button></form></div>{{end}}{{end}}
<p class="version">Supermarket {{.Version}}</p>
@@ -134,13 +134,14 @@
{{define "settings-start"}}
<div class="page-head">
<h1>Settings</h1>
<p class="lede">Your company, the accounts Supermarket posts with, the prospecting tools it reads, the AI it writes with, and your Federated Core.</p>
<p class="lede">{{if .Can "admin"}}Your company, the accounts Supermarket posts with, the prospecting tools it reads, the AI it writes with, and your Federated Core.{{else}}Your account.{{end}}</p>
</div>
<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>
{{if .Member.Admin}}<a href="/settings/users" {{if eq $.Nav "settings/users"}}aria-current="page"{{end}}>{{template "icon" "prospects"}}Users</a>{{end}}{{end}}{{end}}
{{if $.Can "admin"}}
<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>
@@ -155,6 +156,7 @@
<div class="nav-label">Data</div>
<a href="/settings/backups" {{if eq .Nav "settings/backups"}}aria-current="page"{{end}}>{{template "icon" "backups"}}Backups</a>
<a href="/settings/about" {{if eq .Nav "settings/about"}}aria-current="page"{{end}}>{{template "icon" "info"}}About</a>
{{end}}
</nav>
<div class="settings-body">
{{end}}
@@ -61,8 +61,12 @@
<label>Positions, more than <input name="min_positions" inputmode="decimal" value="{{$s.MinPositions}}" size="4"></label>
<label>On at least <input name="min_impressions" inputmode="numeric" value="{{$s.MinImpressions}}" size="6"> impressions</label>
</div>
{{if $.Viewer.User}}
<p class="help">The Monday report and the morning check (sent when something really moved, at most once a day) go to each person with SEO who asks for them, under Settings → Your account.</p>
{{else}}
<label class="check"><input type="checkbox" name="email_report" {{if $s.EmailReport}}checked{{end}}> Email me the Monday report (through the mailbox under <a href="/settings/email">Settings → Email</a>)</label>
<label class="check"><input type="checkbox" name="email_check" {{if $s.EmailCheck}}checked{{end}}> Email me the morning check when something really moved (at most once a day, when Search Console's data moves on)</label>
{{end}}
</section>
{{end}}
+45
View File
@@ -1,6 +1,7 @@
package web
import (
"context"
"errors"
"net/http"
"strconv"
@@ -565,3 +566,47 @@ func (s *Server) inviteAccept(w http.ResponseWriter, r *http.Request) {
}
redirect(w, r, "/", "joined")
}
// mailTeam sends one of the emails people choose (emailKinds) to each
// active person who chose it and may still see its module.
func (s *Server) mailTeam(ctx context.Context, kind, subject, body string) int {
var ek emailKind
for _, k := range emailKinds {
if k.ID == kind {
ek = k
}
}
list, err := users.Members(s.DB, users.Team)
if err != nil {
s.Log.Warn("mail: listing who gets "+kind, "err", err)
return 0
}
if s.Mail == nil {
return 0
}
sent := 0
for _, m := range list {
if m.Status != users.Active || m.Kind != users.Person || !m.Can(ek.Module, false) || !has(m.Emails, kind) {
continue
}
mctx, cancel := context.WithTimeout(ctx, 2*time.Minute)
err := s.Mail.Send(mctx, appmail.Message{To: m.Email, ToName: m.Name, Subject: subject,
Body: body + "\n\n-- \nYou get this because you asked for " + strings.ToLower(ek.Name[:1]) + ek.Name[1:] + ". To stop, untick it under Settings → Your account: " + s.PublicURL + "/settings/account\n"})
cancel()
if err != nil {
s.Log.Warn("mail: not sent", "kind", kind, "to", m.Email, "err", err)
continue
}
sent++
}
return sent
}
func has(list []string, v string) bool {
for _, x := range list {
if x == v {
return true
}
}
return false
}