Phase 10, part 8: the audit log, and who made what

Sign-ins and failed ones, everything admins do to users, connections,
posting accounts, each post published and email sent, pull requests and
deletions go in an audit log (schema 36), kept two years; admins read it
under Settings → Activity. Drafts, published posts and outreach emails
show who made them.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-25 09:31:33 -07:00
co-authored by Claude Opus 5.5
parent bb4772637c
commit c8964cec12
23 changed files with 601 additions and 11 deletions
+1 -1
View File
@@ -120,7 +120,7 @@ func (rt *routes) Handle(pattern string, h http.Handler) {
rt.unmapped = append(rt.unmapped, pattern)
return
}
rt.mux.Handle(pattern, rt.s.allow(area, h))
rt.mux.Handle(pattern, rt.s.allow(area, rt.s.audited(pattern, h)))
}
func (rt *routes) err() error {
+21
View File
@@ -7,6 +7,7 @@ import (
"testing"
"supermarket/internal/appmail"
"supermarket/internal/audit"
"supermarket/internal/profile"
"supermarket/internal/users"
)
@@ -117,6 +118,26 @@ func TestAccessEnforced(t *testing.T) {
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)
}
// The log shows each step, to admins only.
entries, _ := audit.List(s.DB, audit.Filter{}, 100)
var steps []string
for i := len(entries) - 1; i >= 0; i-- {
e := entries[i]
steps = append(steps, e.UserName+" "+e.Action+" "+e.Target)
}
got := strings.Join(steps, "\n")
for _, want := range []string{"owner invited ada@example.com", "owner invited sam@example.com", "X joined ada@example.com", "X joined sam@example.com", "X signin"} {
if !strings.Contains(got, want) {
t.Errorf("the log lacks %q:\n%s", want, got)
}
}
if rec := as(h, sc, http.MethodGet, "/settings/activity", nil); rec.Code != http.StatusForbidden {
t.Errorf("member reads the log: %d", rec.Code)
}
if body := as(h, oc, http.MethodGet, "/settings/activity", nil).Body.String(); !strings.Contains(body, "invited <strong>sam@example.com</strong>") {
t.Errorf("activity page: %s", body)
}
}
func TestViewOnlyMember(t *testing.T) {
+4
View File
@@ -176,6 +176,7 @@ func (s *Server) accountPassword(w http.ResponseWriter, r *http.Request) {
return
}
s.Log.Info("account: password changed", "user", u.Email, "sessions ended", n)
s.audit(r, "password-changed", u.Email, "")
redirect(w, r, "/settings/account", "password-changed")
}
@@ -310,6 +311,7 @@ func (s *Server) twoFactorOn(w http.ResponseWriter, r *http.Request) {
}
_ = users.UseTOTPStep(s.DB, u, step)
s.Log.Info("account: two-factor sign-in on", "user", u.Email)
s.audit(r, "two-factor-on", u.Email, "")
s.render(w, r, "two-factor", page{Title: "Two-factor sign-in", Nav: "settings/account", Flash: "Two-factor sign-in is on.", Data: &accountData{U: u, Codes: codes}})
}
@@ -333,6 +335,7 @@ func (s *Server) twoFactorOff(w http.ResponseWriter, r *http.Request) {
return
}
s.Log.Info("account: two-factor sign-in off", "user", u.Email)
s.audit(r, "two-factor-off", u.Email, "")
redirect(w, r, "/settings/account#two-factor", "two-factor-off")
}
@@ -375,5 +378,6 @@ func (s *Server) recoveryCodes(w http.ResponseWriter, r *http.Request) {
}
_ = users.UseTOTPStep(s.DB, u, step)
s.Log.Info("account: new recovery codes", "user", u.Email)
s.audit(r, "recovery-codes", u.Email, "")
s.render(w, r, "two-factor", page{Title: "Two-factor sign-in", Nav: "settings/account", Flash: "New recovery codes: the old ones no longer work.", Data: &accountData{U: u, Codes: codes}})
}
+193
View File
@@ -0,0 +1,193 @@
package web
import (
"net/http"
"strconv"
"strings"
"time"
"supermarket/internal/audit"
"supermarket/internal/users"
)
// The audit log: who did what. Sign-ins, accounts and connections are
// recorded where they happen; what's sent, published or deleted, by the
// table below, after the request succeeds.
// audit records something the viewer did.
func (s *Server) audit(r *http.Request, action, target, detail string) {
v := viewerOf(r)
e := audit.Entry{Action: action, Target: target, Detail: detail, IP: clientIP(r)}
if v.User != nil {
e.UserID, e.UserName = v.User.ID, displayName(v.User)
}
s.record(e)
}
// auditFor records something done for a user, without a request: a
// scheduled post going out, an email sent from the queue.
func (s *Server) auditFor(user int64, action, target, detail string) {
e := audit.Entry{Kind: audit.System, Action: action, Target: target, Detail: detail, UserID: user}
if user != 0 {
if u, err := users.ByID(s.DB, user); err == nil {
e.UserName = displayName(u)
}
}
s.record(e)
}
func (s *Server) record(e audit.Entry) {
if err := audit.Record(s.DB, e); err != nil {
s.Log.Error("audit: not recorded", "action", e.Action, "err", err)
}
}
func displayName(u *users.User) string {
if u.Name != "" {
return u.Name
}
return u.Email
}
// auditedRoutes are the changes recorded by their route, when they work:
// the route's pattern, then its {action} ("" for routes without one).
var auditedRoutes = map[string]map[string]string{
"POST /drafts/{id}/{action}": {"schedule": "scheduled", "posted": "marked-posted", "discard": "deleted"},
"POST /outreach/{id}/{action}": {"queue": "queued-email", "send-now": "sent-email", "mark-sent": "marked-sent", "discard": "deleted"},
"POST /prospects/{kind}/{id}/{action}": {"accept": "queued-for-crm", "accept-all": "queued-for-crm", "list": "added-to-list", "delete": "deleted", "suppress": "suppressed"},
"POST /seo/changes/{id}/{action}": {"yes": "opened-pull-request"},
"POST /seo/briefs/{id}/{action}": {"pr": "opened-pull-request", "drop": "deleted"},
"POST /sites/pages/{id}/{action}": {"remove": "deleted", "close": "closed-pull-request"},
"POST /sites/new": {"": "created-site"},
"POST /sites/pages/add": {"": "opened-pull-request"},
"POST /sites/theme/update": {"": "opened-pull-request"},
"POST /sites/previews/delete": {"": "deleted"},
"POST /seo/engines/setup": {"": "opened-pull-request"},
"POST /seo/engines/ping": {"": "sent-to-indexnow"},
"POST /metrics/publish": {"": "published"},
"POST /market/{id}/delete": {"": "deleted"},
"POST /signals/{id}/delete": {"": "deleted"},
"POST /funnel/{id}/delete": {"": "deleted"},
"POST /metrics/spend/{id}/delete": {"": "deleted"},
"POST /settings/backups/{action}": {"restore": "restored-backup", "delete": "deleted"},
"POST /crm/{id}/{action}": {"cancel": "deleted"},
"POST /prospects/suppressed": {"": "changed-suppression"},
"POST /settings/email/send-test": {"": "sent-email"},
"POST /settings/email/listmonk/sync": {"": "synced-mailing-lists"},
"POST /settings/profile": {"": "changed-profile"},
}
// statusWriter notes the response's status.
type statusWriter struct {
http.ResponseWriter
code int
}
func (w *statusWriter) WriteHeader(code int) {
if w.code == 0 {
w.code = code
}
w.ResponseWriter.WriteHeader(code)
}
func (w *statusWriter) Write(b []byte) (int, error) {
if w.code == 0 {
w.code = http.StatusOK
}
return w.ResponseWriter.Write(b)
}
// audited wraps a route in the table: a request that worked (a redirect
// or a page, not an error) is recorded.
func (s *Server) audited(pattern string, next http.Handler) http.Handler {
actions, ok := auditedRoutes[pattern]
if !ok {
return next
}
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
action, ok := actions[r.PathValue("action")]
if !ok {
next.ServeHTTP(w, r)
return
}
sw := &statusWriter{ResponseWriter: w}
next.ServeHTTP(sw, r)
// A failed form re-renders its page with 200 and an error: only
// redirects count as done.
if sw.code == http.StatusSeeOther || sw.code == http.StatusFound {
target := r.URL.Path
if k := r.PathValue("kind"); k != "" {
target = k + " " + r.PathValue("id")
}
s.audit(r, action, target, "")
}
})
}
// Settings → Activity.
type activityData struct {
Entries []audit.Entry
People []users.TeamUser
Filter audit.Filter
More int64 // the ID to page from; 0: no more
}
const activityPage = 100
func (s *Server) activityPage(w http.ResponseWriter, r *http.Request) {
if s.admin(w, r) == nil {
return
}
q := r.URL.Query()
f := audit.Filter{Action: strings.TrimSpace(q.Get("action")), Text: q.Get("q")}
f.UserID, _ = strconv.ParseInt(q.Get("user"), 10, 64)
f.Before, _ = strconv.ParseInt(q.Get("before"), 10, 64)
entries, err := audit.List(s.DB, f, activityPage+1)
if err != nil {
s.serverError(w, err)
return
}
d := activityData{Filter: f}
if len(entries) > activityPage {
entries = entries[:activityPage]
d.More = entries[len(entries)-1].ID
}
d.Entries = entries
d.People, _ = users.Members(s.DB, users.Team)
s.render(w, r, "activity", page{Title: "Activity", Nav: "settings/activity", Data: d})
}
// actionLabels say what an action was, in the Activity list.
var actionLabels = map[string]string{
"setup": "set up Supermarket as its owner", "signin": "signed in", "signin-failed": "failed to sign in",
"locked": "was locked out", "signout": "signed out", "reset-asked": "asked to reset the password",
"password-reset": "reset the password", "password-changed": "changed the password",
"two-factor-on": "turned two-factor sign-in on", "two-factor-off": "turned two-factor sign-in off",
"recovery-codes": "made new recovery codes", "joined": "joined",
"invited": "invited", "invitation-resent": "sent an invitation again", "invitation-withdrawn": "withdrew an invitation",
"access-changed": "changed the access of", "disabled": "turned off the account of", "enabled": "turned on the account of",
"unlocked": "unlocked", "two-factor-reset": "reset two-factor sign-in for", "signed-out-user": "signed out everywhere",
"removed-user": "removed", "connected": "connected", "disconnected": "removed the connection to",
"account-signed-out": "signed out the posting account", "posting-grants": "changed who may post to which account",
"published": "published", "scheduled": "scheduled", "marked-posted": "marked as posted", "deleted": "deleted",
"queued-email": "queued an email", "sent-email": "sent an email", "marked-sent": "marked an email as sent",
"queued-for-crm": "queued for the CRM", "added-to-list": "added to a mailing list", "suppressed": "added to the suppression list",
"opened-pull-request": "opened a pull request", "closed-pull-request": "closed a pull request", "created-site": "started a site",
"sent-to-indexnow": "sent pages to IndexNow", "restored-backup": "restored a backup", "changed-suppression": "changed the suppression list",
"synced-mailing-lists": "synced the mailing lists", "changed-profile": "changed the company profile",
}
func actionLabel(a string) string {
if l, ok := actionLabels[a]; ok {
return l
}
return strings.ReplaceAll(a, "-", " ")
}
// pruneAudit keeps two years of the log.
func (s *Server) pruneAudit(now time.Time) {
if _, err := audit.Prune(s.DB, 2*365*24*time.Hour, now); err != nil {
s.Log.Warn("audit: pruning", "err", err)
}
}
+53
View File
@@ -0,0 +1,53 @@
package web
import (
"net/http"
"net/url"
"strconv"
"strings"
"testing"
"supermarket/internal/audit"
"supermarket/internal/inventory"
"supermarket/internal/secrets"
"supermarket/internal/users"
)
func TestActivityRecords(t *testing.T) {
s, h := newServerEdition(t)
owner := addUser(t, s, "owner@example.com", users.Owner, nil)
owner.Name = "Olu"
users.SaveProfile(s.DB, owner)
oc := sessionFor(t, s, owner)
// A failed sign-in, a connection, a deletion.
signin(h, "203.0.113.4", url.Values{"email": {"owner@example.com"}, "password": {"nope nope nope"}})
as(h, oc, http.MethodPost, "/settings/sources", url.Values{secrets.HunterAPIKey: {"hk"}})
e := &inventory.Entry{Name: "Rival", Relationship: "competitor"}
inventory.Save(s.DB, e)
if rec := as(h, oc, http.MethodPost, "/market/"+itoa64(e.ID)+"/delete", url.Values{}); rec.Code != http.StatusSeeOther {
t.Fatalf("delete: %d", rec.Code)
}
entries, _ := audit.List(s.DB, audit.Filter{}, 50)
byAction := map[string][]audit.Entry{}
for _, e := range entries {
byAction[e.Action] = append(byAction[e.Action], e)
}
if f := byAction["signin-failed"]; len(f) != 1 || f[0].IP != "203.0.113.4" || f[0].UserID != owner.ID {
t.Errorf("failed sign-in: %+v", f)
}
if c := byAction["connected"]; len(c) != 1 || c[0].Target != "Hunter.io" || c[0].UserName != "Olu" {
t.Errorf("connection: %+v", c)
}
if d := byAction["deleted"]; len(d) != 1 || !strings.Contains(d[0].Target, "/market/") {
t.Errorf("deletions: %+v", d)
}
// Filters.
body := as(h, oc, http.MethodGet, "/settings/activity?action=signin-failed", nil).Body.String()
if !strings.Contains(body, "failed to sign in") || strings.Contains(body, "Hunter.io") {
t.Errorf("filtered: %s", body)
}
}
func itoa64(n int64) string { return strconv.FormatInt(n, 10) }
+12
View File
@@ -40,6 +40,16 @@ var services = []service{
{"listmonk", "Listmonk", "Mailing lists", "/settings/email", []string{secrets.ListmonkToken}},
}
// serviceName is a service as people say it.
func serviceName(id string) string {
for _, sv := range services {
if sv.ID == id {
return sv.Name
}
}
return id
}
// serviceOf is the service a secret belongs to, by its name's prefix.
func serviceOf(secret string) string {
prefix, _, _ := strings.Cut(secret, ".")
@@ -107,6 +117,7 @@ func (s *Server) setSecrets(r *http.Request, updates map[string]string) error {
removed := !set && !s.serviceSet(sv)
changes[sv] = connChange{By: who, UserID: id, At: now, Removed: removed}
s.Log.Info("connections: changed", "service", sv, "removed", removed, "by", who)
s.audit(r, ifElse(removed, "disconnected", "connected"), serviceName(sv), "")
}
return s.DB.PutJSON(connChangesKey, changes)
}
@@ -125,6 +136,7 @@ func (s *Server) recordConnection(r *http.Request, service string, set bool) {
}
}
changes[service] = connChange{By: who, UserID: id, At: time.Now().UTC(), Removed: !set}
s.audit(r, ifElse(set, "connected", "disconnected"), serviceName(service), "")
if err := s.DB.PutJSON(connChangesKey, changes); err != nil {
s.Log.Warn("connections: recording a change", "err", err)
}
+4
View File
@@ -322,6 +322,7 @@ func (s *Server) draftAction(w http.ResponseWriter, r *http.Request) {
}
reddit = reddit || d.Channel == content.ChannelReddit
s.Log.Info("content: published", "draft", did, "as", d.PostedAs, "by", by)
s.audit(r, "published", d.PostedAs, "post "+strconv.FormatInt(did, 10)+": "+d.PostURL)
}
if reddit {
s.forgetRedditHistory()
@@ -473,6 +474,9 @@ func (s *Server) publishDue(ctx context.Context, now time.Time) {
continue
}
s.Log.Info("scheduler: published", "draft", d.ID, "channel", d.Channel)
if pd, err := content.GetDraft(s.DB, d.ID); err == nil {
s.auditFor(d.PostedBy, "published", pd.PostedAs, "scheduled post "+strconv.FormatInt(d.ID, 10)+": "+pd.PostURL)
}
}
}
+14 -1
View File
@@ -276,6 +276,7 @@ func (s *Server) outreachDraft(w http.ResponseWriter, r *http.Request) {
set, _ := s.outreachSettings()
var m *outreach.Message
if m, err = outreach.Draft(ctx, s.DB, c, p, set, id, channel, time.Now()); err == nil {
s.setCreatedBy(r, m.ID)
redirect(w, r, "/outreach#m-"+strconv.FormatInt(m.ID, 10), "drafted-outreach")
return
}
@@ -320,11 +321,13 @@ func (s *Server) outreachDraftMany(w http.ResponseWriter, r *http.Request) {
set, _ := s.outreachSettings()
var failed []string
for _, id := range ids {
if _, err := outreach.Draft(ctx, s.DB, c, p, set, id, channel, time.Now()); err != nil {
if m, err := outreach.Draft(ctx, s.DB, c, p, set, id, channel, time.Now()); err != nil {
failed = append(failed, err.Error())
if ctx.Err() != nil {
break
}
} else {
s.setCreatedBy(r, m.ID)
}
}
if len(failed) > 0 {
@@ -433,6 +436,7 @@ func (s *Server) RunOutreach(ctx context.Context) {
s.Log.Warn("outreach: sending", "message", idOf(m), "err", err)
} else if m != nil {
s.Log.Info("outreach: sent", "message", m.ID, "to", m.To)
s.auditFor(m.CreatedBy, "sent-email", m.To, m.Subject+" (from the queue)")
}
}
cancel()
@@ -465,3 +469,12 @@ func idOf(m *outreach.Message) int64 {
}
return m.ID
}
// setCreatedBy records who drafted an outreach email.
func (s *Server) setCreatedBy(r *http.Request, id int64) {
if v := viewerOf(r); v.User != nil {
if err := outreach.SetCreatedBy(s.DB, id, v.User.ID); err != nil {
s.Log.Warn("outreach: recording who drafted it", "err", err)
}
}
}
+3 -1
View File
@@ -376,7 +376,8 @@ func (s *Server) postingSave(w http.ResponseWriter, r *http.Request) {
s.serverError(w, err)
return
}
s.Log.Info("posting accounts: who may post changed", "by", viewerOf(r).User.Email)
s.Log.Info("posting accounts: who may post changed")
s.audit(r, "posting-grants", "", "")
redirect(w, r, "/settings/posting", "saved")
}
@@ -406,6 +407,7 @@ func (s *Server) postingRemove(w http.ResponseWriter, r *http.Request) {
s.serverError(w, err)
return
}
s.audit(r, "account-signed-out", a.Label(), "")
back := "/settings/accounts"
if strings.HasPrefix(r.URL.Path, "/settings/account/") {
back = "/settings/account#posting"
+13
View File
@@ -40,6 +40,7 @@ import (
"supermarket/internal/signals"
"supermarket/internal/sites"
"supermarket/internal/tracking"
"supermarket/internal/users"
)
//go:embed templates/*.html
@@ -342,6 +343,7 @@ func (s *Server) Handler() (http.Handler, error) {
mux.HandleFunc("POST /settings/backups/upload", s.backupUpload)
mux.HandleFunc("GET /settings/about", s.aboutPage)
mux.HandleFunc("GET /settings/connections", s.connectionsPage)
mux.HandleFunc("GET /settings/activity", s.activityPage)
mux.HandleFunc("GET /settings/posting", s.postingPage)
mux.HandleFunc("POST /settings/posting", s.postingSave)
mux.HandleFunc("POST /settings/posting/{id}/remove", s.postingRemove)
@@ -489,6 +491,17 @@ func (s *Server) loadTemplates() error {
},
"spendChannel": metrics.ChannelName,
"dec1f": func(f float64) string { return strconv.FormatFloat(f, 'f', 1, 64) },
"actionLabel": actionLabel,
// by is "by Jane" for something a person made; "" if unknown.
"by": func(id int64) string {
if id == 0 {
return ""
}
if u, err := users.ByID(s.DB, id); err == nil {
return "by " + displayName(u)
}
return "by someone since removed"
},
"cents": func(f float64) string {
if f < 0 {
return "·"
+2
View File
@@ -6,6 +6,7 @@ import (
"strings"
"time"
"supermarket/internal/audit"
"supermarket/internal/users"
)
@@ -116,6 +117,7 @@ func (s *Server) setupSave(w http.ResponseWriter, r *http.Request) {
}
s.setupDone.Store(true)
s.Log.Info("setup: the owner is created", "email", u.Email)
s.record(audit.Entry{UserID: u.ID, UserName: displayName(u), Action: "setup", Target: u.Email, IP: clientIP(r)})
if err := s.startSession(w, r, u); err != nil {
s.serverError(w, err)
return
+14 -2
View File
@@ -10,6 +10,7 @@ import (
"time"
"supermarket/internal/appmail"
"supermarket/internal/audit"
"supermarket/internal/users"
)
@@ -199,6 +200,7 @@ func (s *Server) finishSignIn(w http.ResponseWriter, r *http.Request, u *users.U
return
}
s.Log.Info("signin", "user", u.Email, "ip", clientIP(r))
s.record(audit.Entry{UserID: u.ID, UserName: displayName(u), Action: "signin", IP: clientIP(r)})
if u.TwoFactor && u.RecoveryLeft < 3 {
redirect(w, r, "/settings/account#two-factor", "codes-low")
return
@@ -220,11 +222,14 @@ func (s *Server) countFailure(ipKey, emailKey string, u *users.User, now time.Ti
s.Log.Warn("signin: counting a failure", "err", err)
}
}
ip := strings.TrimPrefix(ipKey, "signin:ip:")
if u == nil {
s.Log.Info("signin: failed, no such account", "key", emailKey, "ip", strings.TrimPrefix(ipKey, "signin:ip:"))
s.Log.Info("signin: failed, no such account", "key", emailKey, "ip", ip)
s.record(audit.Entry{Action: "signin-failed", Target: strings.TrimPrefix(emailKey, "signin:email:"), Detail: "no such account", IP: ip})
return
}
s.Log.Info("signin: failed", "user", u.Email, "ip", strings.TrimPrefix(ipKey, "signin:ip:"))
s.Log.Info("signin: failed", "user", u.Email, "ip", ip)
s.record(audit.Entry{UserID: u.ID, UserName: displayName(u), Action: "signin-failed", Target: u.Email, IP: ip})
locked, err := users.FailedSignIn(s.DB, u, now)
if err != nil {
s.Log.Warn("signin: counting a failure", "err", err)
@@ -232,6 +237,7 @@ func (s *Server) countFailure(ipKey, emailKey string, u *users.User, now time.Ti
}
if locked {
s.Log.Warn("signin: account locked", "user", u.Email)
s.record(audit.Entry{UserID: u.ID, UserName: displayName(u), Action: "locked", Target: u.Email, Detail: strconv.Itoa(users.LockAfter) + " failed sign-ins in a row", IP: ip})
s.sendMail(appmail.Message{To: u.Email, ToName: u.Name, Subject: "Your Supermarket account is locked",
Body: "Hello" + nameSuffix(u.Name) + ",\n\n" +
"Your account at " + s.PublicURL + " was locked after " + strconv.Itoa(users.LockAfter) + " failed sign-ins in a row.\n\n" +
@@ -242,6 +248,9 @@ func (s *Server) countFailure(ipKey, emailKey string, u *users.User, now time.Ti
}
func (s *Server) signout(w http.ResponseWriter, r *http.Request) {
if viewerOf(r).User != nil {
s.audit(r, "signout", "", "")
}
if err := s.endSession(w, r); err != nil {
s.serverError(w, err)
return
@@ -286,6 +295,7 @@ func (s *Server) forgot(w http.ResponseWriter, r *http.Request) {
return
}
s.Log.Info("signin: password reset asked for", "user", u.Email, "ip", clientIP(r))
s.record(audit.Entry{UserID: u.ID, UserName: displayName(u), Action: "reset-asked", Target: u.Email, IP: clientIP(r)})
s.sendMail(appmail.Message{To: u.Email, ToName: u.Name, Subject: "Reset your Supermarket password",
Body: "Hello" + nameSuffix(u.Name) + ",\n\n" +
"Someone, probably you, asked to reset your password at " + s.PublicURL + ".\n\n" +
@@ -361,6 +371,7 @@ func (s *Server) reset(w http.ResponseWriter, r *http.Request) {
}
_ = users.ClearFails(s.DB, "signin:email:"+u.Email)
s.Log.Info("signin: password reset", "user", u.Email, "ip", clientIP(r))
s.record(audit.Entry{UserID: u.ID, UserName: displayName(u), Action: "password-reset", Target: u.Email, IP: clientIP(r)})
redirect(w, r, "/signin?email="+url.QueryEscape(u.Email), "password-reset")
}
@@ -407,6 +418,7 @@ func (s *Server) RunAccounts(ctx context.Context) {
if err := users.PruneThrottle(s.DB, now); err != nil {
s.Log.Warn("accounts: pruning counts", "err", err)
}
s.pruneAudit(now)
})
select {
case <-ctx.Done():
+29
View File
@@ -0,0 +1,29 @@
{{define "content"}}{{template "settings-start" .}}{{with .Data}}{{$d := .}}
<h2>Activity</h2>
<p class="lede">Who did what: sign-ins (and failed ones), invitations and access, connections, everything sent or published, and deletions. Kept for two years.</p>
<form class="card filters row wrap" method="get" action="/settings/activity">
<label>Person <select name="user"><option value="">Everyone</option>{{range .People}}<option value="{{.ID}}" {{if eq .ID $d.Filter.UserID}}selected{{end}}>{{if .Name}}{{.Name}}{{else}}{{.Email}}{{end}}</option>{{end}}</select></label>
<label>What <select name="action">
<option value="">Everything</option>
{{range $v, $l := dict "signin" "Sign-ins" "signin-failed" "Failed sign-ins" "invited" "Invitations" "access-changed" "Access changes" "connected" "Connections" "published" "Published" "sent-email" "Emails sent" "deleted" "Deletions"}}<option value="{{$v}}" {{if eq $v $d.Filter.Action}}selected{{end}}>{{$l}}</option>{{end}}
</select></label>
<label>Containing <input name="q" value="{{.Filter.Text}}" placeholder="an address, an account…"></label>
<button type="submit" class="secondary">Show</button>
</form>
<section class="card">
{{if .Entries}}
<table class="list activity">
<thead><tr><th>When</th><th>Who</th><th>What</th><th>From</th></tr></thead>
<tbody>
{{range .Entries}}<tr>
<td title="{{.At.Local.Format "2 Jan 2006 15:04:05"}}">{{ago .At}}</td>
<td>{{if .UserName}}{{.UserName}}{{else if eq .Kind "system"}}Supermarket{{else}}<span class="muted">someone</span>{{end}}{{if eq .Kind "system"}} <span class="muted small">(on its own)</span>{{else if eq .Kind "agent"}} <span class="pill">agent</span>{{end}}</td>
<td>{{actionLabel .Action}}{{with .Target}} <strong>{{.}}</strong>{{end}}{{with .Detail}}<br><span class="muted small">{{truncate 200 .}}</span>{{end}}</td>
<td class="muted small">{{.IP}}</td>
</tr>{{end}}
</tbody>
</table>
{{with .More}}<p><a href="/settings/activity?before={{.}}{{with $d.Filter.UserID}}&amp;user={{.}}{{end}}{{with $d.Filter.Action}}&amp;action={{.}}{{end}}{{with $d.Filter.Text}}&amp;q={{.}}{{end}}">Older →</a></p>{{end}}
{{else}}<p class="muted">Nothing recorded{{if or .Filter.UserID .Filter.Action .Filter.Text}} that matches{{end}}.</p>{{end}}
</section>
{{end}}{{template "settings-end"}}{{end}}
@@ -9,7 +9,7 @@
{{range .Drafts}}
<tr>
<td>{{.PublishedAt.Local.Format "2 Jan 2006 15:04"}}</td>
<td>{{.Where}}{{with .PostedAs}}<br><span class="muted small">as {{.}}</span>{{end}}</td>
<td>{{.Where}}{{with .PostedAs}}<br><span class="muted small">as {{.}}</span>{{end}}{{with by .PostedBy}}<br><span class="muted small">{{.}}</span>{{end}}</td>
<td>{{.InventoryName}}</td>
<td class="post-text">{{if .PostURL}}<a href="{{.PostURL}}" target="_blank" rel="noopener noreferrer">{{if .Title}}<strong>{{.Title}}</strong> {{end}}{{truncate 200 .Content}}</a>{{else}}{{if .Title}}<strong>{{.Title}}</strong> {{end}}{{truncate 200 .Content}}{{end}}</td>
</tr>
+1 -1
View File
@@ -18,7 +18,7 @@
<div class="drafts">
{{range .Drafts}}
<div class="draft{{if eq .Status "failed"}} failed{{end}}">
<h3>{{.Where}}</h3>
<h3>{{.Where}}{{with by .WrittenBy}} <span class="muted small">{{.}}</span>{{end}}</h3>
{{if .Error}}<p class="error">{{.Error}}</p>{{end}}
{{$rv := index $reddit .ID}}
{{if $rv}}
+1
View File
@@ -157,6 +157,7 @@
<a href="/settings/ai" {{if eq .Nav "settings/ai"}}aria-current="page"{{end}}>{{template "icon" "ai"}}AI</a>
<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/activity" {{if eq .Nav "settings/activity"}}aria-current="page"{{end}}>{{template "icon" "backups"}}Activity</a>
<a href="/settings/about" {{if eq .Nav "settings/about"}}aria-current="page"{{end}}>{{template "icon" "info"}}About</a>
{{end}}
</nav>
+1 -1
View File
@@ -39,7 +39,7 @@
{{if eq .Channel "email"}}{{.To}}{{if eq .Contact.EmailStatus "valid"}} <span class="badge published">verified</span>{{else if eq .Contact.EmailStatus "risky"}} <span class="badge">risky</span>{{else if eq .Contact.EmailStatus "invalid"}} <span class="badge failed">bounces</span>{{else}} <span class="muted">not verified</span>{{end}}
{{else}}<a href="{{.Contact.LinkedIn}}" target="_blank" rel="noopener noreferrer">LinkedIn profile ↗</a>{{end}}
{{with index $d.SignalNames .SignalID}} · signal <strong>{{.}}</strong>{{end}}
· written {{ago .CreatedAt}}{{if not .SentAt.IsZero}} · sent {{ago .SentAt}}{{end}}
· written {{ago .CreatedAt}}{{with by .CreatedBy}} {{.}}{{end}}{{if not .SentAt.IsZero}} · sent {{ago .SentAt}}{{end}}
</p>
</div>
</div>
+14 -1
View File
@@ -9,6 +9,7 @@ import (
"time"
"supermarket/internal/appmail"
"supermarket/internal/audit"
"supermarket/internal/posting"
"supermarket/internal/profile"
"supermarket/internal/users"
@@ -246,6 +247,7 @@ func (s *Server) userInvite(w http.ResponseWriter, r *http.Request) {
return
}
s.Log.Info("users: invited", "user", u.Email, "role", role, "by", v.User.Email)
s.audit(r, "invited", u.Email, accessText(users.Membership{Role: role, Modules: mods}))
redirect(w, r, "/settings/users", "invited")
}
@@ -357,7 +359,17 @@ func (s *Server) userAction(w http.ResponseWriter, r *http.Request) {
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) }
auditAs := map[string]string{"access": "access-changed", "resend": "invitation-resent", "withdraw": "invitation-withdrawn",
"disable": "disabled", "enable": "enabled", "unlock": "unlocked", "reset-two-factor": "two-factor-reset",
"sign-out": "signed-out-user", "remove": "removed-user"}
log := func(what string) {
s.Log.Info("users: "+what, "user", u.Email, "by", v.User.Email)
detail := ""
if action == "access" {
detail = strings.TrimPrefix(what, "access changed to ")
}
s.audit(r, auditAs[action], u.Email, detail)
}
var err error
switch action {
case "access":
@@ -572,6 +584,7 @@ func (s *Server) inviteAccept(w http.ResponseWriter, r *http.Request) {
return
}
s.Log.Info("users: joined", "user", u.Email)
s.record(audit.Entry{UserID: u.ID, UserName: displayName(u), Action: "joined", Target: u.Email, IP: clientIP(r)})
if err := s.startSession(w, r, u); err != nil {
s.serverError(w, err)
return