The multi-tenant edition's plans (Free and Paid as decided, or a plans file) and each team's billing account, with a 14-day trial of Paid. A team's plan caps what its people and agents may change: modules outside it stay readable, a lapsed team changes nothing, and agents, Market entries, crawls and background jobs keep to it. Without a Stripe key, no billing. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
481 lines
15 KiB
Go
481 lines
15 KiB
Go
// Package users holds the people (and, from Phase 11, agents) who sign in
|
|
// to the server and multi-tenant editions: their accounts, their role and
|
|
// modules in the team, and their sessions. The local edition has none:
|
|
// whoever opens it is the owner.
|
|
package users
|
|
|
|
import (
|
|
"crypto/rand"
|
|
"crypto/subtle"
|
|
"database/sql"
|
|
"encoding/base64"
|
|
"encoding/json"
|
|
"errors"
|
|
"fmt"
|
|
"net/mail"
|
|
"strings"
|
|
"time"
|
|
|
|
"golang.org/x/crypto/argon2"
|
|
|
|
"supermarket/internal/db"
|
|
)
|
|
|
|
// Kind is what signs in: a person, or an agent with a key (Phase 11).
|
|
type Kind string
|
|
|
|
const (
|
|
Person Kind = "person"
|
|
Agent Kind = "agent"
|
|
)
|
|
|
|
// Status is where an account is.
|
|
type Status string
|
|
|
|
const (
|
|
Invited Status = "invited" // asked to join; hasn't chosen a password yet
|
|
Active Status = "active" // may sign in
|
|
Disabled Status = "disabled" // may not sign in; kept for the record
|
|
)
|
|
|
|
// Role is what someone may do in the team.
|
|
type Role string
|
|
|
|
const (
|
|
Owner Role = "owner" // everything, and billing (multi-tenant)
|
|
Admin Role = "admin" // everything: users, connections, every module
|
|
Member Role = "member" // the modules they're given
|
|
)
|
|
|
|
// Access is how much of a module a member has.
|
|
type Access string
|
|
|
|
const (
|
|
View Access = "view" // sees its pages
|
|
Edit Access = "edit" // and changes things
|
|
)
|
|
|
|
// Team is the one team until the multi-tenant edition (Phase 13).
|
|
const Team int64 = 1
|
|
|
|
// timeFormat sorts as text: fixed width, UTC.
|
|
const timeFormat = "2006-01-02T15:04:05.000Z"
|
|
|
|
func ts(t time.Time) string { return t.UTC().Format(timeFormat) }
|
|
|
|
func parseTS(s string) time.Time {
|
|
t, _ := time.Parse(timeFormat, s)
|
|
return t
|
|
}
|
|
|
|
// User is an account.
|
|
type User struct {
|
|
ID int64
|
|
Email string
|
|
Name string
|
|
Kind Kind
|
|
Status Status
|
|
Title string
|
|
Description string // an agent's: what it's for
|
|
TimeZone string
|
|
Photo string
|
|
Emails []string // the emails they want (the daily SEO email, …)
|
|
Created time.Time
|
|
SignedIn time.Time // their last sign-in; zero if never
|
|
HasPassword bool
|
|
|
|
FailedSignIns int // failed in a row since the last sign-in
|
|
LockedAt time.Time // zero unless locked after too many failures
|
|
TwoFactor bool // signs in with an authenticator app's code too
|
|
RecoveryLeft int // unused recovery codes
|
|
OIDCSubject string // <issuer>|<subject> at the Core, once they've signed in with it
|
|
|
|
passwordHash string
|
|
totpStep int64
|
|
recoveryCodes []string
|
|
}
|
|
|
|
// Locked says whether the account is locked after too many failures.
|
|
func (u *User) Locked() bool { return !u.LockedAt.IsZero() }
|
|
|
|
// Membership is a user's place in a team.
|
|
type Membership struct {
|
|
Team int64
|
|
User int64
|
|
Role Role
|
|
Modules map[string]Access // a member's; admins and owners have them all
|
|
// Cap limits every role, admins too: a module missing from it can't be
|
|
// reached, one at View only read (the team's plan). nil: no cap.
|
|
Cap map[string]Access
|
|
}
|
|
|
|
// Admin says whether the role runs the whole system.
|
|
func (m Membership) Admin() bool { return m.Role == Owner || m.Role == Admin }
|
|
|
|
// Can says whether the member may see a module (write false) or change
|
|
// things in it (write true).
|
|
func (m Membership) Can(module string, write bool) bool {
|
|
if m.Cap != nil {
|
|
c, ok := m.Cap[module]
|
|
if !ok || (write && c != Edit) {
|
|
return false
|
|
}
|
|
}
|
|
if m.Admin() {
|
|
return true
|
|
}
|
|
a, ok := m.Modules[module]
|
|
if !ok {
|
|
return false
|
|
}
|
|
return !write || a == Edit
|
|
}
|
|
|
|
// Errors.
|
|
var (
|
|
ErrNotFound = errors.New("no such user")
|
|
ErrExists = errors.New("someone already has that email address")
|
|
)
|
|
|
|
// NormalEmail checks an email address and returns it trimmed, in lower
|
|
// case: addresses are compared without case.
|
|
func NormalEmail(s string) (string, error) {
|
|
s = strings.TrimSpace(s)
|
|
a, err := mail.ParseAddress(s)
|
|
if err != nil || a.Address != s || !strings.Contains(s, "@") {
|
|
return "", fmt.Errorf("%q isn't an email address", s)
|
|
}
|
|
return strings.ToLower(s), nil
|
|
}
|
|
|
|
const userCols = `id, email, name, kind, status, password_hash, title, description, time_zone, photo, emails, created_at, signed_in_at, failed_signins, locked_at, two_factor, totp_step, recovery_codes, oidc_subject`
|
|
|
|
func scanUser(row interface{ Scan(...any) error }) (*User, error) {
|
|
var u User
|
|
var kind, status, emails, created, signedIn, locked, codes string
|
|
var twoFactor int
|
|
err := row.Scan(&u.ID, &u.Email, &u.Name, &kind, &status, &u.passwordHash, &u.Title, &u.Description, &u.TimeZone, &u.Photo, &emails, &created, &signedIn,
|
|
&u.FailedSignIns, &locked, &twoFactor, &u.totpStep, &codes, &u.OIDCSubject)
|
|
if errors.Is(err, sql.ErrNoRows) {
|
|
return nil, ErrNotFound
|
|
}
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
u.Kind, u.Status = Kind(kind), Status(status)
|
|
_ = json.Unmarshal([]byte(emails), &u.Emails)
|
|
u.Created, u.SignedIn = parseTS(created), parseTS(signedIn)
|
|
u.HasPassword = u.passwordHash != ""
|
|
u.LockedAt, u.TwoFactor = parseTS(locked), twoFactor != 0
|
|
_ = json.Unmarshal([]byte(codes), &u.recoveryCodes)
|
|
u.RecoveryLeft = len(u.recoveryCodes)
|
|
return &u, nil
|
|
}
|
|
|
|
// Create adds a user. Its email is normalized; ID and Created are set.
|
|
func Create(d *db.DB, u *User, now time.Time) error {
|
|
email, err := NormalEmail(u.Email)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if _, err := ByEmail(d, email); err == nil {
|
|
return ErrExists
|
|
} else if !errors.Is(err, ErrNotFound) {
|
|
return err
|
|
}
|
|
u.Email = email
|
|
if u.Kind == "" {
|
|
u.Kind = Person
|
|
}
|
|
if u.Status == "" {
|
|
u.Status = Invited
|
|
}
|
|
if u.Emails == nil {
|
|
u.Emails = []string{}
|
|
}
|
|
emails, _ := json.Marshal(u.Emails)
|
|
u.Created = now
|
|
u.ID, err = d.Insert(`INSERT INTO users (email, name, kind, status, password_hash, title, description, time_zone, photo, emails, created_at)
|
|
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
|
|
u.Email, strings.TrimSpace(u.Name), string(u.Kind), string(u.Status), u.passwordHash, u.Title, strings.TrimSpace(u.Description), u.TimeZone, u.Photo, string(emails), ts(now))
|
|
return err
|
|
}
|
|
|
|
// ByID finds a user.
|
|
func ByID(d *db.DB, id int64) (*User, error) {
|
|
return scanUser(d.QueryRow(`SELECT `+userCols+` FROM users WHERE id = ?`, id))
|
|
}
|
|
|
|
// ByEmail finds a user by email address, whatever its case.
|
|
func ByEmail(d *db.DB, email string) (*User, error) {
|
|
return scanUser(d.QueryRow(`SELECT `+userCols+` FROM users WHERE email = ? COLLATE NOCASE`, strings.TrimSpace(email)))
|
|
}
|
|
|
|
// List is every user, people first, then by name.
|
|
func List(d *db.DB) ([]*User, error) {
|
|
rows, err := d.Query(`SELECT ` + userCols + ` FROM users ORDER BY kind DESC, name COLLATE NOCASE, email`)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
defer rows.Close()
|
|
var out []*User
|
|
for rows.Next() {
|
|
u, err := scanUser(rows)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
out = append(out, u)
|
|
}
|
|
return out, rows.Err()
|
|
}
|
|
|
|
// Count is how many users there are.
|
|
func Count(d *db.DB) (int, error) {
|
|
var n int
|
|
err := d.QueryRow(`SELECT count(*) FROM users`).Scan(&n)
|
|
return n, err
|
|
}
|
|
|
|
// SaveProfile writes the fields a user fills in about themselves.
|
|
func SaveProfile(d *db.DB, u *User) error {
|
|
if u.Emails == nil {
|
|
u.Emails = []string{}
|
|
}
|
|
emails, _ := json.Marshal(u.Emails)
|
|
_, err := d.Exec(`UPDATE users SET name = ?, title = ?, time_zone = ?, photo = ?, emails = ? WHERE id = ?`,
|
|
strings.TrimSpace(u.Name), strings.TrimSpace(u.Title), u.TimeZone, u.Photo, string(emails), u.ID)
|
|
return err
|
|
}
|
|
|
|
// SetStatus activates, disables or re-invites a user. A disabled user's
|
|
// sessions end.
|
|
func SetStatus(d *db.DB, id int64, s Status) error {
|
|
if _, err := d.Exec(`UPDATE users SET status = ? WHERE id = ?`, string(s), id); err != nil {
|
|
return err
|
|
}
|
|
if s == Disabled {
|
|
_, err := d.Exec(`DELETE FROM sessions WHERE user_id = ?`, id)
|
|
return err
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// SignedIn records a sign-in.
|
|
func SignedIn(d *db.DB, id int64, now time.Time) error {
|
|
_, err := d.Exec(`UPDATE users SET signed_in_at = ? WHERE id = ?`, ts(now), id)
|
|
return err
|
|
}
|
|
|
|
// Delete removes a user, their memberships and their sessions.
|
|
func Delete(d *db.DB, id int64) error {
|
|
tx, err := d.Begin()
|
|
if err != nil {
|
|
return err
|
|
}
|
|
defer tx.Rollback()
|
|
// Not left to ON DELETE CASCADE: SQLite enforces it only with
|
|
// foreign_keys on, and an imported database may not have had them.
|
|
for _, q := range []string{`DELETE FROM sessions WHERE user_id = ?`, `DELETE FROM links WHERE user_id = ?`, `DELETE FROM agent_keys WHERE user_id = ?`, `DELETE FROM memberships WHERE user_id = ?`, `DELETE FROM users WHERE id = ?`} {
|
|
if _, err := tx.Exec(q, id); err != nil {
|
|
return err
|
|
}
|
|
}
|
|
return tx.Commit()
|
|
}
|
|
|
|
// Passwords.
|
|
|
|
// MinPassword is the shortest password accepted. Length is what makes a
|
|
// password strong; there are no rules about kinds of characters.
|
|
const MinPassword = 10
|
|
|
|
// CheckNewPassword says what's wrong with a password someone chose.
|
|
func CheckNewPassword(pw, email string) error {
|
|
switch {
|
|
case len([]rune(pw)) < MinPassword:
|
|
return fmt.Errorf("the password needs at least %d characters", MinPassword)
|
|
case len(pw) > 1024:
|
|
return errors.New("the password is too long")
|
|
case strings.EqualFold(strings.TrimSpace(pw), strings.TrimSpace(email)):
|
|
return errors.New("the password can't be your email address")
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// Argon2id's cost: OWASP's suggestion of 19 MiB, two passes.
|
|
const (
|
|
argonTime = 2
|
|
argonMemory = 19 * 1024
|
|
argonThreads = 1
|
|
argonKeyLen = 32
|
|
)
|
|
|
|
// HashPassword hashes a password with Argon2id, in the PHC string format
|
|
// ($argon2id$v=19$m=…,t=…,p=…$salt$hash).
|
|
func HashPassword(pw string) (string, error) {
|
|
salt := make([]byte, 16)
|
|
if _, err := rand.Read(salt); err != nil {
|
|
return "", err
|
|
}
|
|
key := argon2.IDKey([]byte(pw), salt, argonTime, argonMemory, argonThreads, argonKeyLen)
|
|
b64 := base64.RawStdEncoding
|
|
return fmt.Sprintf("$argon2id$v=%d$m=%d,t=%d,p=%d$%s$%s", argon2.Version, argonMemory, argonTime, argonThreads, b64.EncodeToString(salt), b64.EncodeToString(key)), nil
|
|
}
|
|
|
|
// VerifyPassword says whether pw matches a hash from HashPassword. It
|
|
// reads the cost from the hash, so older hashes still verify.
|
|
func VerifyPassword(hash, pw string) bool {
|
|
parts := strings.Split(hash, "$")
|
|
if len(parts) != 6 || parts[1] != "argon2id" {
|
|
return false
|
|
}
|
|
var v int
|
|
var m, t uint32
|
|
var p uint8
|
|
if _, err := fmt.Sscanf(parts[2], "v=%d", &v); err != nil || v != argon2.Version {
|
|
return false
|
|
}
|
|
if _, err := fmt.Sscanf(parts[3], "m=%d,t=%d,p=%d", &m, &t, &p); err != nil || m == 0 || m > 1<<20 || t == 0 || t > 16 || p == 0 {
|
|
return false
|
|
}
|
|
b64 := base64.RawStdEncoding
|
|
salt, err1 := b64.DecodeString(parts[4])
|
|
want, err2 := b64.DecodeString(parts[5])
|
|
if err1 != nil || err2 != nil || len(want) == 0 {
|
|
return false
|
|
}
|
|
got := argon2.IDKey([]byte(pw), salt, t, m, p, uint32(len(want)))
|
|
return subtle.ConstantTimeCompare(got, want) == 1
|
|
}
|
|
|
|
// dummyHash is checked against when there's no user, so a sign-in takes
|
|
// as long whether or not the address has an account.
|
|
var dummyHash, _ = HashPassword("not anyone's password")
|
|
|
|
// CheckPassword says whether pw is the user's password. A user without
|
|
// one never matches.
|
|
func CheckPassword(u *User, pw string) bool {
|
|
if u == nil || u.passwordHash == "" {
|
|
VerifyPassword(dummyHash, pw)
|
|
return false
|
|
}
|
|
return VerifyPassword(u.passwordHash, pw)
|
|
}
|
|
|
|
// SetPassword changes a user's password ("" removes it).
|
|
func SetPassword(d *db.DB, u *User, pw string) error {
|
|
hash := ""
|
|
if pw != "" {
|
|
var err error
|
|
if hash, err = HashPassword(pw); err != nil {
|
|
return err
|
|
}
|
|
}
|
|
if _, err := d.Exec(`UPDATE users SET password_hash = ? WHERE id = ?`, hash, u.ID); err != nil {
|
|
return err
|
|
}
|
|
u.passwordHash, u.HasPassword = hash, hash != ""
|
|
return nil
|
|
}
|
|
|
|
// Memberships.
|
|
|
|
// Join gives a user a role (and a member their modules) in the team, or
|
|
// changes it.
|
|
func Join(d *db.DB, team, user int64, role Role, modules map[string]Access, now time.Time) error {
|
|
switch role {
|
|
case Owner, Admin, Member:
|
|
default:
|
|
return fmt.Errorf("no role %q", role)
|
|
}
|
|
if role != Member || modules == nil {
|
|
modules = map[string]Access{}
|
|
}
|
|
for m, a := range modules {
|
|
if a != View && a != Edit {
|
|
return fmt.Errorf("module %s: no access %q", m, a)
|
|
}
|
|
}
|
|
js, _ := json.Marshal(modules)
|
|
_, err := d.Exec(`INSERT INTO memberships (team_id, user_id, role, modules, created_at) VALUES (?, ?, ?, ?, ?)
|
|
ON CONFLICT (team_id, user_id) DO UPDATE SET role = excluded.role, modules = excluded.modules`,
|
|
team, user, string(role), string(js), ts(now))
|
|
return err
|
|
}
|
|
|
|
// MembershipOf is a user's place in the team; ErrNotFound if they have none.
|
|
func MembershipOf(d *db.DB, team, user int64) (Membership, error) {
|
|
m := Membership{Team: team, User: user}
|
|
var role, modules string
|
|
err := d.QueryRow(`SELECT role, modules FROM memberships WHERE team_id = ? AND user_id = ?`, team, user).Scan(&role, &modules)
|
|
if errors.Is(err, sql.ErrNoRows) {
|
|
return m, ErrNotFound
|
|
}
|
|
if err != nil {
|
|
return m, err
|
|
}
|
|
m.Role = Role(role)
|
|
m.Modules = map[string]Access{}
|
|
_ = json.Unmarshal([]byte(modules), &m.Modules)
|
|
return m, nil
|
|
}
|
|
|
|
// HasOwner says whether the team has its owner yet: until then, the
|
|
// server edition is waiting to be set up.
|
|
func HasOwner(d *db.DB, team int64) (bool, error) {
|
|
var n int
|
|
err := d.QueryRow(`SELECT count(*) FROM memberships WHERE team_id = ? AND role = 'owner'`, team).Scan(&n)
|
|
return n > 0, err
|
|
}
|
|
|
|
// TeamUser is a user with their place in the team.
|
|
type TeamUser struct {
|
|
*User
|
|
Membership
|
|
}
|
|
|
|
// Members are the team's users, people first, then by name.
|
|
func Members(d *db.DB, team int64) ([]TeamUser, error) {
|
|
cols := strings.ReplaceAll("u."+userCols, ", ", ", u.")
|
|
rows, err := d.Query(`SELECT `+cols+`, m.role, m.modules FROM users u JOIN memberships m ON m.user_id = u.id
|
|
WHERE m.team_id = ? ORDER BY u.kind DESC, u.name COLLATE NOCASE, u.email`, team)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
defer rows.Close()
|
|
var out []TeamUser
|
|
for rows.Next() {
|
|
var role, modules string
|
|
u, err := scanUser(rowWith{rows, []any{&role, &modules}})
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
m := Membership{Team: team, User: u.ID, Role: Role(role), Modules: map[string]Access{}}
|
|
_ = json.Unmarshal([]byte(modules), &m.Modules)
|
|
out = append(out, TeamUser{User: u, Membership: m})
|
|
}
|
|
return out, rows.Err()
|
|
}
|
|
|
|
// rowWith scans a user's columns followed by some more.
|
|
type rowWith struct {
|
|
row interface{ Scan(...any) error }
|
|
more []any
|
|
}
|
|
|
|
func (r rowWith) Scan(dest ...any) error { return r.row.Scan(append(dest, r.more...)...) }
|
|
|
|
// ByOIDCSubject finds the user the Core knows by a subject.
|
|
func ByOIDCSubject(d *db.DB, subject string) (*User, error) {
|
|
if subject == "" {
|
|
return nil, ErrNotFound
|
|
}
|
|
return scanUser(d.QueryRow(`SELECT `+userCols+` FROM users WHERE oidc_subject = ?`, subject))
|
|
}
|
|
|
|
// SetOIDCSubject remembers who a user is at the Core.
|
|
func SetOIDCSubject(d *db.DB, id int64, subject string) error {
|
|
_, err := d.Exec(`UPDATE users SET oidc_subject = ? WHERE id = ?`, subject, id)
|
|
return err
|
|
}
|