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:
@@ -2344,6 +2344,31 @@ starts** (multi-tenant still doesn't).
|
|||||||
reminders of running-out sign-ins cover every account.
|
reminders of running-out sign-ins cover every account.
|
||||||
- Agents get the same grid in Phase 11.
|
- Agents get the same grid in Phase 11.
|
||||||
|
|
||||||
|
**Part 8 built 2026-11-25** on `phase10`.
|
||||||
|
- Schema 36: `audit_log` (when, who, their name then, person, agent or
|
||||||
|
system, the action, its target, detail, IP), kept two years (pruned by
|
||||||
|
the hourly `job:accounts`), and `outreach.created_by`. `internal/audit`
|
||||||
|
records and lists it.
|
||||||
|
- Recorded where they happen: the setup, sign-ins, failed sign-ins (with
|
||||||
|
the address tried, known or not), locks, sign-outs, resets asked and
|
||||||
|
done, password and two-factor changes, joining; every admin action on
|
||||||
|
Users (invited, access changed with the new access, resent, withdrawn,
|
||||||
|
turned off and on, unlocked, two-factor reset, signed out, removed);
|
||||||
|
connections made and removed; posting accounts signed out and who-may-
|
||||||
|
post changes; each post published (the account and the post's link,
|
||||||
|
each copy), and scheduled posts and queued emails sent on their own
|
||||||
|
(as Supermarket, for the person who scheduled or wrote them).
|
||||||
|
- Recorded by their route (`auditedRoutes`, in activity.go), when the
|
||||||
|
request worked (it redirected): scheduling and discarding posts,
|
||||||
|
queueing and sending emails, CRM queueing, mailing-list adds,
|
||||||
|
suppression, pull requests (SEO changes, briefs, pages, the theme,
|
||||||
|
search-engine setup), a new site, IndexNow, the metrics page, restoring
|
||||||
|
backups, the company profile, and the deletions.
|
||||||
|
- Settings → Activity (admins): newest first, a hundred at a time,
|
||||||
|
filtered by person, kind and text.
|
||||||
|
- *By Jane*: on drafts in Posts (who wrote it), published posts (who
|
||||||
|
posted it, and as which account) and outreach emails (who drafted it).
|
||||||
|
|
||||||
1. **Users and sessions.**
|
1. **Users and sessions.**
|
||||||
- Tables:
|
- Tables:
|
||||||
- `users`: email, name, kind (person or agent), status (invited,
|
- `users`: email, name, kind (person or agent), status (invited,
|
||||||
|
|||||||
@@ -0,0 +1,117 @@
|
|||||||
|
// Package audit is the record of who did what: sign-ins, invitations and
|
||||||
|
// roles, connections, everything sent or published, and deletions. Admins
|
||||||
|
// read it under Settings → Activity.
|
||||||
|
package audit
|
||||||
|
|
||||||
|
import (
|
||||||
|
"strings"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"supermarket/internal/db"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Entry is one thing someone did.
|
||||||
|
type Entry struct {
|
||||||
|
ID int64
|
||||||
|
At time.Time
|
||||||
|
UserID int64 // 0: Supermarket itself, or the local edition's owner
|
||||||
|
UserName string // as they were called then
|
||||||
|
Kind string // person, agent or system
|
||||||
|
Action string
|
||||||
|
Target string
|
||||||
|
Detail string
|
||||||
|
IP string
|
||||||
|
}
|
||||||
|
|
||||||
|
// Kinds of actor.
|
||||||
|
const (
|
||||||
|
Person = "person"
|
||||||
|
Agent = "agent"
|
||||||
|
System = "system"
|
||||||
|
)
|
||||||
|
|
||||||
|
const timeFormat = "2006-01-02T15:04:05.000Z"
|
||||||
|
|
||||||
|
// Record adds an entry. Long fields are cut short.
|
||||||
|
func Record(d *db.DB, e Entry) error {
|
||||||
|
if e.At.IsZero() {
|
||||||
|
e.At = time.Now()
|
||||||
|
}
|
||||||
|
if e.Kind == "" {
|
||||||
|
e.Kind = Person
|
||||||
|
}
|
||||||
|
_, err := d.Exec(`INSERT INTO audit_log (at, user_id, user_name, kind, action, target, detail, ip) VALUES (?, ?, ?, ?, ?, ?, ?, ?)`,
|
||||||
|
e.At.UTC().Format(timeFormat), e.UserID, cut(e.UserName, 200), e.Kind, cut(e.Action, 100), cut(e.Target, 500), cut(e.Detail, 2000), cut(e.IP, 64))
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
func cut(s string, n int) string {
|
||||||
|
if r := []rune(s); len(r) > n {
|
||||||
|
return string(r[:n-1]) + "…"
|
||||||
|
}
|
||||||
|
return s
|
||||||
|
}
|
||||||
|
|
||||||
|
// Filter narrows the list.
|
||||||
|
type Filter struct {
|
||||||
|
UserID int64 // 0: everyone
|
||||||
|
Action string // a prefix: "signin" matches signin and signin-failed
|
||||||
|
Text string // in the target or detail
|
||||||
|
Before int64 // entries older than this ID (paging); 0: the newest
|
||||||
|
}
|
||||||
|
|
||||||
|
// List is the newest entries first.
|
||||||
|
func List(d *db.DB, f Filter, limit int) ([]Entry, error) {
|
||||||
|
q := `SELECT id, at, user_id, user_name, kind, action, target, detail, ip FROM audit_log WHERE 1 = 1`
|
||||||
|
var args []any
|
||||||
|
if f.UserID != 0 {
|
||||||
|
q += ` AND user_id = ?`
|
||||||
|
args = append(args, f.UserID)
|
||||||
|
}
|
||||||
|
if f.Action != "" {
|
||||||
|
q += ` AND action LIKE ?`
|
||||||
|
args = append(args, escapeLike(f.Action)+"%")
|
||||||
|
}
|
||||||
|
if t := strings.TrimSpace(f.Text); t != "" {
|
||||||
|
q += ` AND (target LIKE ? OR detail LIKE ? OR user_name LIKE ?)`
|
||||||
|
like := "%" + escapeLike(t) + "%"
|
||||||
|
args = append(args, like, like, like)
|
||||||
|
}
|
||||||
|
if f.Before != 0 {
|
||||||
|
q += ` AND id < ?`
|
||||||
|
args = append(args, f.Before)
|
||||||
|
}
|
||||||
|
q += ` ORDER BY id DESC LIMIT ?`
|
||||||
|
args = append(args, limit)
|
||||||
|
rows, err := d.Query(q, args...)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
defer rows.Close()
|
||||||
|
var out []Entry
|
||||||
|
for rows.Next() {
|
||||||
|
var e Entry
|
||||||
|
var at string
|
||||||
|
if err := rows.Scan(&e.ID, &at, &e.UserID, &e.UserName, &e.Kind, &e.Action, &e.Target, &e.Detail, &e.IP); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
e.At, _ = time.Parse(timeFormat, at)
|
||||||
|
out = append(out, e)
|
||||||
|
}
|
||||||
|
return out, rows.Err()
|
||||||
|
}
|
||||||
|
|
||||||
|
// escapeLike makes % and _ match themselves (with ESCAPE-less LIKE, by
|
||||||
|
// dropping them: a search for them finds nothing special).
|
||||||
|
func escapeLike(s string) string {
|
||||||
|
return strings.NewReplacer("%", "", "_", "").Replace(s)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Prune deletes entries older than keep.
|
||||||
|
func Prune(d *db.DB, keep time.Duration, now time.Time) (int64, error) {
|
||||||
|
res, err := d.Exec(`DELETE FROM audit_log WHERE at < ?`, now.Add(-keep).UTC().Format(timeFormat))
|
||||||
|
if err != nil {
|
||||||
|
return 0, err
|
||||||
|
}
|
||||||
|
return res.RowsAffected()
|
||||||
|
}
|
||||||
@@ -0,0 +1,49 @@
|
|||||||
|
package audit
|
||||||
|
|
||||||
|
import (
|
||||||
|
"path/filepath"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"supermarket/internal/db"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestRecordAndList(t *testing.T) {
|
||||||
|
d, err := db.Open(filepath.Join(t.TempDir(), "app.db"))
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
defer d.Close()
|
||||||
|
now := time.Now()
|
||||||
|
for _, e := range []Entry{
|
||||||
|
{At: now.Add(-400 * 24 * time.Hour), UserID: 1, UserName: "Olu", Action: "signin"},
|
||||||
|
{At: now.Add(-time.Hour), UserID: 1, UserName: "Olu", Action: "signin", IP: "203.0.113.1"},
|
||||||
|
{At: now.Add(-30 * time.Minute), UserID: 2, UserName: "Sam", Action: "signin-failed", Target: "sam@example.com"},
|
||||||
|
{At: now, UserID: 1, UserName: "Olu", Action: "invited", Target: "sam@example.com", Detail: "Member: SEO"},
|
||||||
|
{At: now, Kind: System, Action: "published", Target: "X @acme"},
|
||||||
|
} {
|
||||||
|
if err := Record(d, e); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
all, _ := List(d, Filter{}, 10)
|
||||||
|
if len(all) != 5 || all[0].Action != "published" || all[0].Kind != System || all[4].Kind != Person {
|
||||||
|
t.Fatalf("all: %+v", all)
|
||||||
|
}
|
||||||
|
if l, _ := List(d, Filter{Action: "signin"}, 10); len(l) != 3 {
|
||||||
|
t.Errorf("signin*: %d", len(l))
|
||||||
|
}
|
||||||
|
if l, _ := List(d, Filter{UserID: 2}, 10); len(l) != 1 {
|
||||||
|
t.Errorf("Sam: %d", len(l))
|
||||||
|
}
|
||||||
|
if l, _ := List(d, Filter{Text: "SAM@"}, 10); len(l) != 2 {
|
||||||
|
t.Errorf("text: %d", len(l))
|
||||||
|
}
|
||||||
|
page2, _ := List(d, Filter{Before: all[1].ID}, 2)
|
||||||
|
if len(page2) != 2 || page2[0].ID != all[2].ID {
|
||||||
|
t.Errorf("paging: %+v", page2)
|
||||||
|
}
|
||||||
|
if n, _ := Prune(d, 365*24*time.Hour, now); n != 1 {
|
||||||
|
t.Errorf("pruned %d", n)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -145,6 +145,26 @@ ALTER TABLE drafts ADD COLUMN account_id INTEGER NOT NULL DEFAULT 0; -- 0: the c
|
|||||||
ALTER TABLE drafts ADD COLUMN written_by INTEGER NOT NULL DEFAULT 0;
|
ALTER TABLE drafts ADD COLUMN written_by INTEGER NOT NULL DEFAULT 0;
|
||||||
ALTER TABLE drafts ADD COLUMN posted_by INTEGER NOT NULL DEFAULT 0;
|
ALTER TABLE drafts ADD COLUMN posted_by INTEGER NOT NULL DEFAULT 0;
|
||||||
ALTER TABLE drafts ADD COLUMN posted_as TEXT NOT NULL DEFAULT ''; -- the account it went out as, when it did
|
ALTER TABLE drafts ADD COLUMN posted_as TEXT NOT NULL DEFAULT ''; -- the account it went out as, when it did
|
||||||
|
`,
|
||||||
|
},
|
||||||
|
// 36
|
||||||
|
{
|
||||||
|
Note: "the audit log: who did what, and who made each outreach email",
|
||||||
|
SQLite: `
|
||||||
|
CREATE TABLE audit_log (
|
||||||
|
id INTEGER PRIMARY KEY,
|
||||||
|
at TEXT NOT NULL,
|
||||||
|
user_id INTEGER NOT NULL DEFAULT 0, -- 0: Supermarket itself, or the local edition's owner
|
||||||
|
user_name TEXT NOT NULL DEFAULT '', -- as they were called then
|
||||||
|
kind TEXT NOT NULL DEFAULT 'person', -- person, agent or system
|
||||||
|
action TEXT NOT NULL, -- e.g. signin, signin-failed, invited, published, deleted
|
||||||
|
target TEXT NOT NULL DEFAULT '', -- what it was done to: an address, an account, a page
|
||||||
|
detail TEXT NOT NULL DEFAULT '',
|
||||||
|
ip TEXT NOT NULL DEFAULT ''
|
||||||
|
);
|
||||||
|
CREATE INDEX audit_log_at ON audit_log(at);
|
||||||
|
CREATE INDEX audit_log_user ON audit_log(user_id, at);
|
||||||
|
ALTER TABLE outreach ADD COLUMN created_by INTEGER NOT NULL DEFAULT 0;
|
||||||
`,
|
`,
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -50,6 +50,7 @@ type Message struct {
|
|||||||
RepliedAt time.Time
|
RepliedAt time.Time
|
||||||
Reply string
|
Reply string
|
||||||
Error string
|
Error string
|
||||||
|
CreatedBy int64 // who drafted it; 0: unknown, or the local edition
|
||||||
|
|
||||||
// Filled in when listing.
|
// Filled in when listing.
|
||||||
Contact prospects.Contact
|
Contact prospects.Contact
|
||||||
@@ -86,7 +87,7 @@ func nullID(id int64) any {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const columns = `o.id, o.contact_id, coalesce(o.signal_id, 0), o.channel, o.status, o.subject, o.body, o.to_addr,
|
const columns = `o.id, o.contact_id, coalesce(o.signal_id, 0), o.channel, o.status, o.subject, o.body, o.to_addr,
|
||||||
o.message_id, o.created_at, o.queued_at, o.sent_at, o.replied_at, o.reply, o.error,
|
o.message_id, o.created_at, o.queued_at, o.sent_at, o.replied_at, o.reply, o.error, o.created_by,
|
||||||
p.first_name, p.last_name, p.title, p.email, p.email_status, p.linkedin, coalesce(p.company_id, 0),
|
p.first_name, p.last_name, p.title, p.email, p.email_status, p.linkedin, coalesce(p.company_id, 0),
|
||||||
coalesce(c.name, '')`
|
coalesce(c.name, '')`
|
||||||
|
|
||||||
@@ -101,7 +102,7 @@ func scan(rows *sql.Rows) ([]Message, error) {
|
|||||||
var created string
|
var created string
|
||||||
var queued, sent, replied sql.NullString
|
var queued, sent, replied sql.NullString
|
||||||
if err := rows.Scan(&m.ID, &m.ContactID, &m.SignalID, &m.Channel, &m.Status, &m.Subject, &m.Body, &m.To,
|
if err := rows.Scan(&m.ID, &m.ContactID, &m.SignalID, &m.Channel, &m.Status, &m.Subject, &m.Body, &m.To,
|
||||||
&m.MessageID, &created, &queued, &sent, &replied, &m.Reply, &m.Error,
|
&m.MessageID, &created, &queued, &sent, &replied, &m.Reply, &m.Error, &m.CreatedBy,
|
||||||
&m.Contact.FirstName, &m.Contact.LastName, &m.Contact.Title, &m.Contact.Email, &m.Contact.EmailStatus,
|
&m.Contact.FirstName, &m.Contact.LastName, &m.Contact.Title, &m.Contact.Email, &m.Contact.EmailStatus,
|
||||||
&m.Contact.LinkedIn, &m.Contact.CompanyID, &m.Company); err != nil {
|
&m.Contact.LinkedIn, &m.Contact.CompanyID, &m.Company); err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
@@ -405,3 +406,9 @@ func lastSent(d *db.DB) (time.Time, error) {
|
|||||||
err := d.QueryRow(`SELECT max(sent_at) FROM outreach WHERE channel = 'email'`).Scan(&s)
|
err := d.QueryRow(`SELECT max(sent_at) FROM outreach WHERE channel = 'email'`).Scan(&s)
|
||||||
return parseTime(s), err
|
return parseTime(s), err
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// SetCreatedBy records who drafted a message.
|
||||||
|
func SetCreatedBy(d *db.DB, id, user int64) error {
|
||||||
|
_, err := d.Exec(`UPDATE outreach SET created_by = ? WHERE id = ?`, user, id)
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|||||||
@@ -120,7 +120,7 @@ func (rt *routes) Handle(pattern string, h http.Handler) {
|
|||||||
rt.unmapped = append(rt.unmapped, pattern)
|
rt.unmapped = append(rt.unmapped, pattern)
|
||||||
return
|
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 {
|
func (rt *routes) err() error {
|
||||||
|
|||||||
@@ -7,6 +7,7 @@ import (
|
|||||||
"testing"
|
"testing"
|
||||||
|
|
||||||
"supermarket/internal/appmail"
|
"supermarket/internal/appmail"
|
||||||
|
"supermarket/internal/audit"
|
||||||
"supermarket/internal/profile"
|
"supermarket/internal/profile"
|
||||||
"supermarket/internal/users"
|
"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 {
|
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)
|
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) {
|
func TestViewOnlyMember(t *testing.T) {
|
||||||
|
|||||||
@@ -176,6 +176,7 @@ func (s *Server) accountPassword(w http.ResponseWriter, r *http.Request) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
s.Log.Info("account: password changed", "user", u.Email, "sessions ended", n)
|
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")
|
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)
|
_ = users.UseTOTPStep(s.DB, u, step)
|
||||||
s.Log.Info("account: two-factor sign-in on", "user", u.Email)
|
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}})
|
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
|
return
|
||||||
}
|
}
|
||||||
s.Log.Info("account: two-factor sign-in off", "user", u.Email)
|
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")
|
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)
|
_ = users.UseTOTPStep(s.DB, u, step)
|
||||||
s.Log.Info("account: new recovery codes", "user", u.Email)
|
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}})
|
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}})
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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) }
|
||||||
@@ -40,6 +40,16 @@ var services = []service{
|
|||||||
{"listmonk", "Listmonk", "Mailing lists", "/settings/email", []string{secrets.ListmonkToken}},
|
{"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.
|
// serviceOf is the service a secret belongs to, by its name's prefix.
|
||||||
func serviceOf(secret string) string {
|
func serviceOf(secret string) string {
|
||||||
prefix, _, _ := strings.Cut(secret, ".")
|
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)
|
removed := !set && !s.serviceSet(sv)
|
||||||
changes[sv] = connChange{By: who, UserID: id, At: now, Removed: removed}
|
changes[sv] = connChange{By: who, UserID: id, At: now, Removed: removed}
|
||||||
s.Log.Info("connections: changed", "service", sv, "removed", removed, "by", who)
|
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)
|
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}
|
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 {
|
if err := s.DB.PutJSON(connChangesKey, changes); err != nil {
|
||||||
s.Log.Warn("connections: recording a change", "err", err)
|
s.Log.Warn("connections: recording a change", "err", err)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -322,6 +322,7 @@ func (s *Server) draftAction(w http.ResponseWriter, r *http.Request) {
|
|||||||
}
|
}
|
||||||
reddit = reddit || d.Channel == content.ChannelReddit
|
reddit = reddit || d.Channel == content.ChannelReddit
|
||||||
s.Log.Info("content: published", "draft", did, "as", d.PostedAs, "by", by)
|
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 {
|
if reddit {
|
||||||
s.forgetRedditHistory()
|
s.forgetRedditHistory()
|
||||||
@@ -473,6 +474,9 @@ func (s *Server) publishDue(ctx context.Context, now time.Time) {
|
|||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
s.Log.Info("scheduler: published", "draft", d.ID, "channel", d.Channel)
|
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)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -276,6 +276,7 @@ func (s *Server) outreachDraft(w http.ResponseWriter, r *http.Request) {
|
|||||||
set, _ := s.outreachSettings()
|
set, _ := s.outreachSettings()
|
||||||
var m *outreach.Message
|
var m *outreach.Message
|
||||||
if m, 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 {
|
||||||
|
s.setCreatedBy(r, m.ID)
|
||||||
redirect(w, r, "/outreach#m-"+strconv.FormatInt(m.ID, 10), "drafted-outreach")
|
redirect(w, r, "/outreach#m-"+strconv.FormatInt(m.ID, 10), "drafted-outreach")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
@@ -320,11 +321,13 @@ func (s *Server) outreachDraftMany(w http.ResponseWriter, r *http.Request) {
|
|||||||
set, _ := s.outreachSettings()
|
set, _ := s.outreachSettings()
|
||||||
var failed []string
|
var failed []string
|
||||||
for _, id := range ids {
|
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())
|
failed = append(failed, err.Error())
|
||||||
if ctx.Err() != nil {
|
if ctx.Err() != nil {
|
||||||
break
|
break
|
||||||
}
|
}
|
||||||
|
} else {
|
||||||
|
s.setCreatedBy(r, m.ID)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if len(failed) > 0 {
|
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)
|
s.Log.Warn("outreach: sending", "message", idOf(m), "err", err)
|
||||||
} else if m != nil {
|
} else if m != nil {
|
||||||
s.Log.Info("outreach: sent", "message", m.ID, "to", m.To)
|
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()
|
cancel()
|
||||||
@@ -465,3 +469,12 @@ func idOf(m *outreach.Message) int64 {
|
|||||||
}
|
}
|
||||||
return m.ID
|
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)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -376,7 +376,8 @@ func (s *Server) postingSave(w http.ResponseWriter, r *http.Request) {
|
|||||||
s.serverError(w, err)
|
s.serverError(w, err)
|
||||||
return
|
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")
|
redirect(w, r, "/settings/posting", "saved")
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -406,6 +407,7 @@ func (s *Server) postingRemove(w http.ResponseWriter, r *http.Request) {
|
|||||||
s.serverError(w, err)
|
s.serverError(w, err)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
s.audit(r, "account-signed-out", a.Label(), "")
|
||||||
back := "/settings/accounts"
|
back := "/settings/accounts"
|
||||||
if strings.HasPrefix(r.URL.Path, "/settings/account/") {
|
if strings.HasPrefix(r.URL.Path, "/settings/account/") {
|
||||||
back = "/settings/account#posting"
|
back = "/settings/account#posting"
|
||||||
|
|||||||
@@ -40,6 +40,7 @@ import (
|
|||||||
"supermarket/internal/signals"
|
"supermarket/internal/signals"
|
||||||
"supermarket/internal/sites"
|
"supermarket/internal/sites"
|
||||||
"supermarket/internal/tracking"
|
"supermarket/internal/tracking"
|
||||||
|
"supermarket/internal/users"
|
||||||
)
|
)
|
||||||
|
|
||||||
//go:embed templates/*.html
|
//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("POST /settings/backups/upload", s.backupUpload)
|
||||||
mux.HandleFunc("GET /settings/about", s.aboutPage)
|
mux.HandleFunc("GET /settings/about", s.aboutPage)
|
||||||
mux.HandleFunc("GET /settings/connections", s.connectionsPage)
|
mux.HandleFunc("GET /settings/connections", s.connectionsPage)
|
||||||
|
mux.HandleFunc("GET /settings/activity", s.activityPage)
|
||||||
mux.HandleFunc("GET /settings/posting", s.postingPage)
|
mux.HandleFunc("GET /settings/posting", s.postingPage)
|
||||||
mux.HandleFunc("POST /settings/posting", s.postingSave)
|
mux.HandleFunc("POST /settings/posting", s.postingSave)
|
||||||
mux.HandleFunc("POST /settings/posting/{id}/remove", s.postingRemove)
|
mux.HandleFunc("POST /settings/posting/{id}/remove", s.postingRemove)
|
||||||
@@ -489,6 +491,17 @@ func (s *Server) loadTemplates() error {
|
|||||||
},
|
},
|
||||||
"spendChannel": metrics.ChannelName,
|
"spendChannel": metrics.ChannelName,
|
||||||
"dec1f": func(f float64) string { return strconv.FormatFloat(f, 'f', 1, 64) },
|
"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 {
|
"cents": func(f float64) string {
|
||||||
if f < 0 {
|
if f < 0 {
|
||||||
return "·"
|
return "·"
|
||||||
|
|||||||
@@ -6,6 +6,7 @@ import (
|
|||||||
"strings"
|
"strings"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
|
"supermarket/internal/audit"
|
||||||
"supermarket/internal/users"
|
"supermarket/internal/users"
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -116,6 +117,7 @@ func (s *Server) setupSave(w http.ResponseWriter, r *http.Request) {
|
|||||||
}
|
}
|
||||||
s.setupDone.Store(true)
|
s.setupDone.Store(true)
|
||||||
s.Log.Info("setup: the owner is created", "email", u.Email)
|
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 {
|
if err := s.startSession(w, r, u); err != nil {
|
||||||
s.serverError(w, err)
|
s.serverError(w, err)
|
||||||
return
|
return
|
||||||
|
|||||||
+14
-2
@@ -10,6 +10,7 @@ import (
|
|||||||
"time"
|
"time"
|
||||||
|
|
||||||
"supermarket/internal/appmail"
|
"supermarket/internal/appmail"
|
||||||
|
"supermarket/internal/audit"
|
||||||
"supermarket/internal/users"
|
"supermarket/internal/users"
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -199,6 +200,7 @@ func (s *Server) finishSignIn(w http.ResponseWriter, r *http.Request, u *users.U
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
s.Log.Info("signin", "user", u.Email, "ip", clientIP(r))
|
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 {
|
if u.TwoFactor && u.RecoveryLeft < 3 {
|
||||||
redirect(w, r, "/settings/account#two-factor", "codes-low")
|
redirect(w, r, "/settings/account#two-factor", "codes-low")
|
||||||
return
|
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)
|
s.Log.Warn("signin: counting a failure", "err", err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
ip := strings.TrimPrefix(ipKey, "signin:ip:")
|
||||||
if u == nil {
|
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
|
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)
|
locked, err := users.FailedSignIn(s.DB, u, now)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
s.Log.Warn("signin: counting a failure", "err", err)
|
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 {
|
if locked {
|
||||||
s.Log.Warn("signin: account locked", "user", u.Email)
|
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",
|
s.sendMail(appmail.Message{To: u.Email, ToName: u.Name, Subject: "Your Supermarket account is locked",
|
||||||
Body: "Hello" + nameSuffix(u.Name) + ",\n\n" +
|
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" +
|
"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) {
|
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 {
|
if err := s.endSession(w, r); err != nil {
|
||||||
s.serverError(w, err)
|
s.serverError(w, err)
|
||||||
return
|
return
|
||||||
@@ -286,6 +295,7 @@ func (s *Server) forgot(w http.ResponseWriter, r *http.Request) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
s.Log.Info("signin: password reset asked for", "user", u.Email, "ip", clientIP(r))
|
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",
|
s.sendMail(appmail.Message{To: u.Email, ToName: u.Name, Subject: "Reset your Supermarket password",
|
||||||
Body: "Hello" + nameSuffix(u.Name) + ",\n\n" +
|
Body: "Hello" + nameSuffix(u.Name) + ",\n\n" +
|
||||||
"Someone, probably you, asked to reset your password at " + s.PublicURL + ".\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)
|
_ = users.ClearFails(s.DB, "signin:email:"+u.Email)
|
||||||
s.Log.Info("signin: password reset", "user", u.Email, "ip", clientIP(r))
|
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")
|
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 {
|
if err := users.PruneThrottle(s.DB, now); err != nil {
|
||||||
s.Log.Warn("accounts: pruning counts", "err", err)
|
s.Log.Warn("accounts: pruning counts", "err", err)
|
||||||
}
|
}
|
||||||
|
s.pruneAudit(now)
|
||||||
})
|
})
|
||||||
select {
|
select {
|
||||||
case <-ctx.Done():
|
case <-ctx.Done():
|
||||||
|
|||||||
@@ -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}}&user={{.}}{{end}}{{with $d.Filter.Action}}&action={{.}}{{end}}{{with $d.Filter.Text}}&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}}
|
{{range .Drafts}}
|
||||||
<tr>
|
<tr>
|
||||||
<td>{{.PublishedAt.Local.Format "2 Jan 2006 15:04"}}</td>
|
<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>{{.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>
|
<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>
|
</tr>
|
||||||
|
|||||||
@@ -18,7 +18,7 @@
|
|||||||
<div class="drafts">
|
<div class="drafts">
|
||||||
{{range .Drafts}}
|
{{range .Drafts}}
|
||||||
<div class="draft{{if eq .Status "failed"}} failed{{end}}">
|
<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}}
|
{{if .Error}}<p class="error">{{.Error}}</p>{{end}}
|
||||||
{{$rv := index $reddit .ID}}
|
{{$rv := index $reddit .ID}}
|
||||||
{{if $rv}}
|
{{if $rv}}
|
||||||
|
|||||||
@@ -157,6 +157,7 @@
|
|||||||
<a href="/settings/ai" {{if eq .Nav "settings/ai"}}aria-current="page"{{end}}>{{template "icon" "ai"}}AI</a>
|
<a href="/settings/ai" {{if eq .Nav "settings/ai"}}aria-current="page"{{end}}>{{template "icon" "ai"}}AI</a>
|
||||||
<div class="nav-label">Data</div>
|
<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/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>
|
<a href="/settings/about" {{if eq .Nav "settings/about"}}aria-current="page"{{end}}>{{template "icon" "info"}}About</a>
|
||||||
{{end}}
|
{{end}}
|
||||||
</nav>
|
</nav>
|
||||||
|
|||||||
@@ -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}}
|
{{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}}
|
{{else}}<a href="{{.Contact.LinkedIn}}" target="_blank" rel="noopener noreferrer">LinkedIn profile ↗</a>{{end}}
|
||||||
{{with index $d.SignalNames .SignalID}} · signal <strong>{{.}}</strong>{{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>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
+14
-1
@@ -9,6 +9,7 @@ import (
|
|||||||
"time"
|
"time"
|
||||||
|
|
||||||
"supermarket/internal/appmail"
|
"supermarket/internal/appmail"
|
||||||
|
"supermarket/internal/audit"
|
||||||
"supermarket/internal/posting"
|
"supermarket/internal/posting"
|
||||||
"supermarket/internal/profile"
|
"supermarket/internal/profile"
|
||||||
"supermarket/internal/users"
|
"supermarket/internal/users"
|
||||||
@@ -246,6 +247,7 @@ func (s *Server) userInvite(w http.ResponseWriter, r *http.Request) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
s.Log.Info("users: invited", "user", u.Email, "role", role, "by", v.User.Email)
|
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")
|
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)
|
s.renderUser(w, r, v, u, m, "You can't change your own access: ask another admin.", http.StatusForbidden)
|
||||||
return
|
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
|
var err error
|
||||||
switch action {
|
switch action {
|
||||||
case "access":
|
case "access":
|
||||||
@@ -572,6 +584,7 @@ func (s *Server) inviteAccept(w http.ResponseWriter, r *http.Request) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
s.Log.Info("users: joined", "user", u.Email)
|
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 {
|
if err := s.startSession(w, r, u); err != nil {
|
||||||
s.serverError(w, err)
|
s.serverError(w, err)
|
||||||
return
|
return
|
||||||
|
|||||||
Reference in New Issue
Block a user