diff --git a/PLAN.md b/PLAN.md index 456cbb0..c4dce7e 100644 --- a/PLAN.md +++ b/PLAN.md @@ -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 + `
` (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, diff --git a/internal/web/access.go b/internal/web/access.go new file mode 100644 index 0000000..d02adf5 --- /dev/null +++ b/internal/web/access.go @@ -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)`) + 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 . + out.Write(tag) + out.WriteString(`
`) + end := formClose.FindIndex(rest) + if end == nil { + out.Write(rest) + out.WriteString(`
`) + rest = nil + continue + } + out.Write(rest[:end[0]]) + out.WriteString(`
`) + 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 +} diff --git a/internal/web/access_test.go b/internal/web/access_test.go new file mode 100644 index 0000000..6ba4f8a --- /dev/null +++ b/internal/web/access_test.go @@ -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, `
`) { + t.Error("SEO's forms aren't disabled") + } + if strings.Contains(body, `` + + `
` + + `
` + + `
` + + `` + out := string(rewriteForms([]byte(in), "T", "/seo/check", v)) + want := `
` + + `
` + + `
` + + `
` + + `` + 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) + } +} diff --git a/internal/web/auth.go b/internal/web/auth.go index d44d30d..e7674bc 100644 --- a/internal/web/auth.go +++ b/internal/web/auth.go @@ -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(``) 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 } diff --git a/internal/web/pages.go b/internal/web/pages.go index 7db8f9d..ca88de5 100644 --- a/internal/web/pages.go +++ b/internal/web/pages.go @@ -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, diff --git a/internal/web/search.go b/internal/web/search.go index 038225b..30fc43d 100644 --- a/internal/web/search.go +++ b/internal/web/search.go @@ -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) } } diff --git a/internal/web/seo.go b/internal/web/seo.go index ab1b83a..396584d 100644 --- a/internal/web/seo.go +++ b/internal/web/seo.go @@ -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 diff --git a/internal/web/server.go b/internal/web/server.go index 11d5daf..dd9cecd 100644 --- a/internal/web/server.go +++ b/internal/web/server.go @@ -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. diff --git a/internal/web/static/app.css b/internal/web/static/app.css index 25a867b..18a110f 100644 --- a/internal/web/static/app.css +++ b/internal/web/static/app.css @@ -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)); } diff --git a/internal/web/templates/dashboard.html b/internal/web/templates/dashboard.html index 01e40bc..6dc5175 100644 --- a/internal/web/templates/dashboard.html +++ b/internal/web/templates/dashboard.html @@ -22,7 +22,12 @@ {{end}} -{{if .Pending}} +{{if not .Modules}} +

You don't have any modules yet. An admin can give you some, under Settings → Users.

+{{end}} + +{{if not .Admin}} +{{else if .Pending}}

Setup

    @@ -45,7 +50,8 @@ {{end}} -{{if .ImportErr}} +{{if not .Admin}} +{{else if .ImportErr}}

    Import from the old app failed

    {{.ImportErr}}

    diff --git a/internal/web/templates/layout.html b/internal/web/templates/layout.html index 4d3eb4c..ddee122 100644 --- a/internal/web/templates/layout.html +++ b/internal/web/templates/layout.html @@ -35,9 +35,9 @@
    {{end}} diff --git a/internal/web/users.go b/internal/web/users.go index f263fe0..c63b455 100644 --- a/internal/web/users.go +++ b/internal/web/users.go @@ -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 +}