Phase 10, part 1: users, sessions and form tokens
Schema 32 adds users, memberships and sessions, on both databases. internal/users keeps accounts (Argon2id passwords), roles and modules, and sessions whose rows hold only a hash of the cookie's value; they end after a week unused or 30 days. On the server edition, every page but the public ones needs a session and sends others to /signin. Every edition's forms now carry a CSRF token (a cookie repeated in each form, added as pages render; htmx sends it as a header), besides the same-origin check. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,178 @@
|
||||
package users
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"crypto/sha256"
|
||||
"database/sql"
|
||||
"encoding/base64"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"time"
|
||||
|
||||
"supermarket/internal/db"
|
||||
)
|
||||
|
||||
// Session lengths: a session ends after a week unused, and after 30 days
|
||||
// whatever happens.
|
||||
const (
|
||||
SessionIdle = 7 * 24 * time.Hour
|
||||
SessionMax = 30 * 24 * time.Hour
|
||||
// seenEvery is how often a session's last use is written down: not on
|
||||
// every request.
|
||||
seenEvery = time.Minute
|
||||
)
|
||||
|
||||
// Session is a signed-in browser. Its ID is the hash of the cookie's
|
||||
// value: a copy of the database doesn't let anyone in.
|
||||
type Session struct {
|
||||
ID string
|
||||
User int64
|
||||
Created time.Time
|
||||
Seen time.Time
|
||||
Expires time.Time
|
||||
IP string
|
||||
UserAgent string
|
||||
}
|
||||
|
||||
// ErrNoSession is a cookie that leads nowhere: unknown, ended or expired,
|
||||
// or its user can't sign in any more.
|
||||
var ErrNoSession = errors.New("not signed in")
|
||||
|
||||
func hashToken(token string) string {
|
||||
sum := sha256.Sum256([]byte(token))
|
||||
return hex.EncodeToString(sum[:])
|
||||
}
|
||||
|
||||
// NewToken is 32 random bytes, for a cookie or a link.
|
||||
func NewToken() (string, error) {
|
||||
b := make([]byte, 32)
|
||||
if _, err := rand.Read(b); err != nil {
|
||||
return "", err
|
||||
}
|
||||
return base64.RawURLEncoding.EncodeToString(b), nil
|
||||
}
|
||||
|
||||
// StartSession signs a user in: it returns the token for the cookie.
|
||||
func StartSession(d *db.DB, user int64, ip, userAgent string, now time.Time) (string, *Session, error) {
|
||||
token, err := NewToken()
|
||||
if err != nil {
|
||||
return "", nil, err
|
||||
}
|
||||
if len(userAgent) > 300 {
|
||||
userAgent = userAgent[:300]
|
||||
}
|
||||
s := &Session{ID: hashToken(token), User: user, Created: now, Seen: now, Expires: expiry(now, now), IP: ip, UserAgent: userAgent}
|
||||
_, err = d.Exec(`INSERT INTO sessions (id, user_id, created_at, seen_at, expires_at, ip, user_agent) VALUES (?, ?, ?, ?, ?, ?, ?)`,
|
||||
s.ID, s.User, ts(s.Created), ts(s.Seen), ts(s.Expires), s.IP, s.UserAgent)
|
||||
if err != nil {
|
||||
return "", nil, err
|
||||
}
|
||||
return token, s, nil
|
||||
}
|
||||
|
||||
// expiry is when a session created at created, last used at seen, ends.
|
||||
func expiry(created, seen time.Time) time.Time {
|
||||
idle, max := seen.Add(SessionIdle), created.Add(SessionMax)
|
||||
if idle.Before(max) {
|
||||
return idle
|
||||
}
|
||||
return max
|
||||
}
|
||||
|
||||
const sessionCols = `id, user_id, created_at, seen_at, expires_at, ip, user_agent`
|
||||
|
||||
func scanSession(row interface{ Scan(...any) error }) (*Session, error) {
|
||||
var s Session
|
||||
var created, seen, expires string
|
||||
if err := row.Scan(&s.ID, &s.User, &created, &seen, &expires, &s.IP, &s.UserAgent); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
s.Created, s.Seen, s.Expires = parseTS(created), parseTS(seen), parseTS(expires)
|
||||
return &s, nil
|
||||
}
|
||||
|
||||
// Lookup finds the session and user a cookie's token belongs to, and
|
||||
// notes that it was used. Only active users have sessions that work.
|
||||
func Lookup(d *db.DB, token string, now time.Time) (*Session, *User, error) {
|
||||
if token == "" {
|
||||
return nil, nil, ErrNoSession
|
||||
}
|
||||
s, err := scanSession(d.QueryRow(`SELECT `+sessionCols+` FROM sessions WHERE id = ?`, hashToken(token)))
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
return nil, nil, ErrNoSession
|
||||
}
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
if !now.Before(s.Expires) {
|
||||
_, _ = d.Exec(`DELETE FROM sessions WHERE id = ?`, s.ID)
|
||||
return nil, nil, ErrNoSession
|
||||
}
|
||||
u, err := ByID(d, s.User)
|
||||
if errors.Is(err, ErrNotFound) {
|
||||
return nil, nil, ErrNoSession
|
||||
}
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
if u.Status != Active {
|
||||
return nil, nil, ErrNoSession
|
||||
}
|
||||
if now.Sub(s.Seen) >= seenEvery {
|
||||
s.Seen, s.Expires = now, expiry(s.Created, now)
|
||||
if _, err := d.Exec(`UPDATE sessions SET seen_at = ?, expires_at = ? WHERE id = ?`, ts(s.Seen), ts(s.Expires), s.ID); err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
}
|
||||
return s, u, nil
|
||||
}
|
||||
|
||||
// EndSession signs a cookie's session out.
|
||||
func EndSession(d *db.DB, token string) error {
|
||||
_, err := d.Exec(`DELETE FROM sessions WHERE id = ?`, hashToken(token))
|
||||
return err
|
||||
}
|
||||
|
||||
// EndSessionByID signs one of a user's sessions out, by its ID (from
|
||||
// Sessions): only theirs.
|
||||
func EndSessionByID(d *db.DB, user int64, id string) error {
|
||||
_, err := d.Exec(`DELETE FROM sessions WHERE id = ? AND user_id = ?`, id, user)
|
||||
return err
|
||||
}
|
||||
|
||||
// EndOtherSessions signs a user out everywhere but the session keep (""
|
||||
// for everywhere). It returns how many ended.
|
||||
func EndOtherSessions(d *db.DB, user int64, keep string) (int64, error) {
|
||||
res, err := d.Exec(`DELETE FROM sessions WHERE user_id = ? AND id <> ?`, user, keep)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return res.RowsAffected()
|
||||
}
|
||||
|
||||
// Sessions are a user's sessions, the most recently used first.
|
||||
func Sessions(d *db.DB, user int64, now time.Time) ([]*Session, error) {
|
||||
rows, err := d.Query(`SELECT `+sessionCols+` FROM sessions WHERE user_id = ? AND expires_at > ? ORDER BY seen_at DESC`, user, ts(now))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
var out []*Session
|
||||
for rows.Next() {
|
||||
s, err := scanSession(rows)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out = append(out, s)
|
||||
}
|
||||
return out, rows.Err()
|
||||
}
|
||||
|
||||
// PruneSessions deletes the sessions that have ended.
|
||||
func PruneSessions(d *db.DB, now time.Time) (int64, error) {
|
||||
res, err := d.Exec(`DELETE FROM sessions WHERE expires_at <= ?`, ts(now))
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return res.RowsAffected()
|
||||
}
|
||||
@@ -0,0 +1,396 @@
|
||||
// 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
|
||||
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
|
||||
|
||||
passwordHash string
|
||||
}
|
||||
|
||||
// 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
|
||||
}
|
||||
|
||||
// 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.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, time_zone, photo, emails, created_at, signed_in_at`
|
||||
|
||||
func scanUser(row interface{ Scan(...any) error }) (*User, error) {
|
||||
var u User
|
||||
var kind, status, emails, created, signedIn string
|
||||
err := row.Scan(&u.ID, &u.Email, &u.Name, &kind, &status, &u.passwordHash, &u.Title, &u.TimeZone, &u.Photo, &emails, &created, &signedIn)
|
||||
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 != ""
|
||||
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, time_zone, photo, emails, created_at)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
|
||||
u.Email, strings.TrimSpace(u.Name), string(u.Kind), string(u.Status), u.passwordHash, u.Title, 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.
|
||||
func SetStatus(d *db.DB, id int64, s Status) error {
|
||||
_, err := d.Exec(`UPDATE users SET status = ? WHERE id = ?`, string(s), id)
|
||||
return err
|
||||
}
|
||||
|
||||
// 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 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
|
||||
}
|
||||
@@ -0,0 +1,223 @@
|
||||
package users
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"supermarket/internal/db"
|
||||
)
|
||||
|
||||
func openDB(t *testing.T) *db.DB {
|
||||
t.Helper()
|
||||
d, err := db.Open(filepath.Join(t.TempDir(), "app.db"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { d.Close() })
|
||||
return d
|
||||
}
|
||||
|
||||
func TestPasswords(t *testing.T) {
|
||||
h, err := HashPassword("correct horse battery")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !strings.HasPrefix(h, "$argon2id$v=19$m=19456,t=2,p=1$") {
|
||||
t.Errorf("hash %s", h)
|
||||
}
|
||||
if !VerifyPassword(h, "correct horse battery") || VerifyPassword(h, "correct horse batterY") {
|
||||
t.Error("verify")
|
||||
}
|
||||
h2, _ := HashPassword("correct horse battery")
|
||||
if h == h2 {
|
||||
t.Error("no salt")
|
||||
}
|
||||
for _, bad := range []string{"", "x", "$argon2id$v=19$m=0,t=2,p=1$aa$bb", "$argon2i$v=19$m=19456,t=2,p=1$aa$bb", "$argon2id$v=19$m=99999999,t=2,p=1$aa$bb"} {
|
||||
if VerifyPassword(bad, "x") {
|
||||
t.Errorf("%q verified", bad)
|
||||
}
|
||||
}
|
||||
if err := CheckNewPassword("short", "a@b.c"); err == nil {
|
||||
t.Error("short password accepted")
|
||||
}
|
||||
if err := CheckNewPassword("Pat@Example.com", "pat@example.com"); err == nil {
|
||||
t.Error("the email as a password accepted")
|
||||
}
|
||||
if err := CheckNewPassword("a long enough one", "pat@example.com"); err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestUsersAndMemberships(t *testing.T) {
|
||||
d := openDB(t)
|
||||
now := time.Date(2026, 11, 25, 10, 0, 0, 0, time.UTC)
|
||||
if ok, err := HasOwner(d, Team); err != nil || ok {
|
||||
t.Fatalf("owner on a new database: %v %v", ok, err)
|
||||
}
|
||||
u := &User{Email: " Pat@Example.com ", Name: "Pat"}
|
||||
if err := Create(d, u, now); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if u.Email != "pat@example.com" || u.Status != Invited || u.Kind != Person {
|
||||
t.Errorf("created %+v", u)
|
||||
}
|
||||
if err := Create(d, &User{Email: "PAT@example.com"}, now); !errors.Is(err, ErrExists) {
|
||||
t.Errorf("same address again: %v", err)
|
||||
}
|
||||
if err := Create(d, &User{Email: "not an address"}, now); err == nil {
|
||||
t.Error("bad address accepted")
|
||||
}
|
||||
got, err := ByEmail(d, "PAT@EXAMPLE.COM")
|
||||
if err != nil || got.ID != u.ID || got.HasPassword {
|
||||
t.Fatalf("by email: %+v %v", got, err)
|
||||
}
|
||||
if CheckPassword(got, "") || CheckPassword(nil, "x") {
|
||||
t.Error("no password matched")
|
||||
}
|
||||
if err := SetPassword(d, got, "a long enough one"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
got, _ = ByID(d, u.ID)
|
||||
if !got.HasPassword || !CheckPassword(got, "a long enough one") || CheckPassword(got, "another one!") {
|
||||
t.Error("password")
|
||||
}
|
||||
|
||||
if err := Join(d, Team, u.ID, Owner, nil, now); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if ok, _ := HasOwner(d, Team); !ok {
|
||||
t.Error("no owner")
|
||||
}
|
||||
m, err := MembershipOf(d, Team, u.ID)
|
||||
if err != nil || !m.Admin() || !m.Can("metrics", true) {
|
||||
t.Errorf("owner: %+v %v", m, err)
|
||||
}
|
||||
|
||||
jo := &User{Email: "jo@example.com", Name: "Jo"}
|
||||
if err := Create(d, jo, now); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := MembershipOf(d, Team, jo.ID); !errors.Is(err, ErrNotFound) {
|
||||
t.Errorf("no membership yet: %v", err)
|
||||
}
|
||||
if err := Join(d, Team, jo.ID, Member, map[string]Access{"seo": Edit, "metrics": View}, now); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := Join(d, Team, jo.ID, Member, map[string]Access{"seo": "all"}, now); err == nil {
|
||||
t.Error("bad access accepted")
|
||||
}
|
||||
m, _ = MembershipOf(d, Team, jo.ID)
|
||||
for _, c := range []struct {
|
||||
module string
|
||||
write bool
|
||||
want bool
|
||||
}{{"seo", false, true}, {"seo", true, true}, {"metrics", false, true}, {"metrics", true, false}, {"content", false, false}} {
|
||||
if got := m.Can(c.module, c.write); got != c.want {
|
||||
t.Errorf("member Can(%s, %v) = %v", c.module, c.write, got)
|
||||
}
|
||||
}
|
||||
// Changing the role.
|
||||
if err := Join(d, Team, jo.ID, Admin, map[string]Access{"seo": View}, now); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if m, _ = MembershipOf(d, Team, jo.ID); m.Role != Admin || len(m.Modules) != 0 {
|
||||
t.Errorf("made admin: %+v", m)
|
||||
}
|
||||
|
||||
jo.Title, jo.TimeZone, jo.Emails = "Writer", "Europe/Paris", []string{"seo-daily"}
|
||||
if err := SaveProfile(d, jo); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
list, err := List(d)
|
||||
if err != nil || len(list) != 2 || list[0].Name != "Jo" || list[0].Title != "Writer" || len(list[0].Emails) != 1 {
|
||||
t.Errorf("list: %+v %v", list, err)
|
||||
}
|
||||
if n, _ := Count(d); n != 2 {
|
||||
t.Errorf("count %d", n)
|
||||
}
|
||||
if err := Delete(d, jo.ID); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := MembershipOf(d, Team, jo.ID); !errors.Is(err, ErrNotFound) {
|
||||
t.Error("membership outlived its user")
|
||||
}
|
||||
}
|
||||
|
||||
func TestSessions(t *testing.T) {
|
||||
d := openDB(t)
|
||||
now := time.Date(2026, 11, 25, 10, 0, 0, 0, time.UTC)
|
||||
u := &User{Email: "pat@example.com", Status: Active}
|
||||
if err := Create(d, u, now); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
token, s, err := StartSession(d, u.ID, "203.0.113.5", "Firefox", now)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if s.ID == token || len(token) < 40 {
|
||||
t.Errorf("token %q, id %q", token, s.ID)
|
||||
}
|
||||
if _, _, err := Lookup(d, "nonsense", now); !errors.Is(err, ErrNoSession) {
|
||||
t.Errorf("unknown token: %v", err)
|
||||
}
|
||||
if _, _, err := Lookup(d, "", now); !errors.Is(err, ErrNoSession) {
|
||||
t.Errorf("empty token: %v", err)
|
||||
}
|
||||
got, who, err := Lookup(d, token, now.Add(time.Hour))
|
||||
if err != nil || who.ID != u.ID || got.IP != "203.0.113.5" {
|
||||
t.Fatalf("lookup: %+v %+v %v", got, who, err)
|
||||
}
|
||||
if !got.Expires.Equal(now.Add(time.Hour + SessionIdle)) {
|
||||
t.Errorf("expiry not slid: %v", got.Expires)
|
||||
}
|
||||
// Used every few days, it still ends after 30 days.
|
||||
at := now
|
||||
for i := 0; i < 9; i++ {
|
||||
at = at.Add(3 * 24 * time.Hour)
|
||||
if _, _, err := Lookup(d, token, at); err != nil {
|
||||
t.Fatalf("day %d: %v", i*3, err)
|
||||
}
|
||||
}
|
||||
if _, _, err := Lookup(d, token, now.Add(SessionMax)); !errors.Is(err, ErrNoSession) {
|
||||
t.Errorf("after 30 days: %v", err)
|
||||
}
|
||||
|
||||
// Idle for a week.
|
||||
t2, _, _ := StartSession(d, u.ID, "", "", now)
|
||||
if _, _, err := Lookup(d, t2, now.Add(SessionIdle)); !errors.Is(err, ErrNoSession) {
|
||||
t.Errorf("idle a week: %v", err)
|
||||
}
|
||||
|
||||
// A disabled user's sessions stop working.
|
||||
t3, s3, _ := StartSession(d, u.ID, "", "", now)
|
||||
t4, _, _ := StartSession(d, u.ID, "", "", now)
|
||||
if err := SetStatus(d, u.ID, Disabled); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, _, err := Lookup(d, t3, now); !errors.Is(err, ErrNoSession) {
|
||||
t.Errorf("disabled user: %v", err)
|
||||
}
|
||||
SetStatus(d, u.ID, Active)
|
||||
if list, _ := Sessions(d, u.ID, now); len(list) != 2 {
|
||||
t.Errorf("sessions: %d", len(list))
|
||||
}
|
||||
if n, err := EndOtherSessions(d, u.ID, s3.ID); err != nil || n != 1 {
|
||||
t.Errorf("end others: %d %v", n, err)
|
||||
}
|
||||
if _, _, err := Lookup(d, t4, now); !errors.Is(err, ErrNoSession) {
|
||||
t.Error("another session survived")
|
||||
}
|
||||
if err := EndSession(d, t3); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, _, err := Lookup(d, t3, now); !errors.Is(err, ErrNoSession) {
|
||||
t.Error("signed out, still in")
|
||||
}
|
||||
StartSession(d, u.ID, "", "", now)
|
||||
if n, _ := PruneSessions(d, now.Add(SessionMax)); n != 1 {
|
||||
t.Errorf("pruned %d", n)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user