Skip to content

armgit / lyftr

Public Imported from GitHub
0

Self-hosted fitness tracker. Log workouts, track nutrition, and monitor progress. Docker deployment, mobile-friendly.

Treat email addresses as case-insensitive (#119) (#192)

Cartera84e65ecc1fa
diff --git a/backend/controllers/auth.go b/backend/controllers/auth.go
index 0f11f6e..e3e9a52 100644
--- a/backend/controllers/auth.go
+++ b/backend/controllers/auth.go
@@ -85,7 +85,7 @@ func (h *Handler) Register(c *gin.Context) {
utils.Forbidden(c, RegistrationClosedMessage)
return
}
- if utils.IsUniqueViolation(err) {
+ if errors.Is(err, stores.ErrEmailTaken) || utils.IsUniqueViolation(err) {
utils.Conflict(c, "That email is already registered.")
return
}
diff --git a/backend/controllers/auth_test.go b/backend/controllers/auth_test.go
index 84dfd3a..4e3ff68 100644
--- a/backend/controllers/auth_test.go
+++ b/backend/controllers/auth_test.go
@@ -10,6 +10,7 @@ import (
"github.com/Cawlumm/lyftr-backend/config"
"github.com/Cawlumm/lyftr-backend/db"
"github.com/Cawlumm/lyftr-backend/stores"
+ "github.com/Cawlumm/lyftr-backend/utils"
)
func registerRequest(t *testing.T, email string) int {
@@ -250,3 +251,112 @@ func TestLoginDoesNotLeakAccountExistenceByTiming(t *testing.T) {
existing, missing, ratio)
}
}
+
+func loginRequest(t *testing.T, email, password string) (int, map[string]any) {
+ t.Helper()
+ c, w := newContext(0, "POST", "/api/v1/auth/login",
+ map[string]string{"email": email, "password": password})
+ th.Login(c)
+ return w.Code, decodeResponse(t, w)
+}
+
+// seedCollidingAccounts models an install that predates the case-insensitive index:
+// the index is dropped and two case variants are inserted directly.
+func seedCollidingAccounts(t *testing.T, a, passA, b, passB string) (int64, int64) {
+ t.Helper()
+ if _, err := db.DB.Exec(`DROP INDEX idx_users_email_nocase`); err != nil {
+ t.Fatalf("drop index: %v", err)
+ }
+ insert := func(email, pass string) int64 {
+ hash, err := utils.HashPassword(pass)
+ if err != nil {
+ t.Fatalf("hash: %v", err)
+ }
+ res, err := db.DB.Exec(`INSERT INTO users (email, password_hash) VALUES (?, ?)`, email, hash)
+ if err != nil {
+ t.Fatalf("insert %s: %v", email, err)
+ }
+ id, _ := res.LastInsertId()
+ if _, err := db.DB.Exec(`INSERT INTO user_settings (user_id) VALUES (?)`, id); err != nil {
+ t.Fatalf("insert settings: %v", err)
+ }
+ return id
+ }
+ return insert(a, passA), insert(b, passB)
+}
+
+func TestRegisterRejectsAnAddressDifferingOnlyInCase(t *testing.T) {
+ setupTestDB(t)
+ if code := registerRequest(t, "[email protected]"); code != http.StatusCreated {
+ t.Fatalf("first register = %d, want 201", code)
+ }
+ c, w := newContext(0, "POST", "/api/v1/auth/register",
+ map[string]string{"email": "[email protected]", "password": "password123"})
+ th.Register(c)
+ if w.Code != http.StatusConflict {
+ t.Fatalf("status = %d, want 409", w.Code)
+ }
+ if msg := decodeResponse(t, w)["error"]; msg != "That email is already registered." {
+ t.Errorf("error = %v", msg)
+ }
+ if n := userCount(t); n != 1 {
+ t.Errorf("users = %d, want 1", n)
+ }
+}
+
+func TestLoginIgnoresCase(t *testing.T) {
+ setupTestDB(t)
+ registerAndLogin(t, "[email protected]", "password123")
+
+ code, body := loginRequest(t, "[email protected]", "password123")
+ if code != http.StatusOK {
+ t.Fatalf("status = %d, want 200", code)
+ }
+ data, _ := body["data"].(map[string]any)
+ user, _ := data["user"].(map[string]any)
+ if user["email"] != "[email protected]" {
+ t.Errorf("email = %v, want the stored spelling", user["email"])
+ }
+
+ code, body = loginRequest(t, "[email protected]", "wrongpassword1")
+ if code != http.StatusUnauthorized || body["error"] != "Invalid email or password." {
+ t.Errorf("wrong password = %d %v, want 401 generic", code, body["error"])
+ }
+}
+
+func TestLoginOnACollidingInstall(t *testing.T) {
+ setupTestDB(t)
+ upper, lower := seedCollidingAccounts(t, "[email protected]", "password-upper", "[email protected]", "password-lower")
+
+ check := func(email, pass string, want int64) {
+ code, body := loginRequest(t, email, pass)
+ if code != http.StatusOK {
+ t.Fatalf("%s = %d, want 200", email, code)
+ }
+ data, _ := body["data"].(map[string]any)
+ user, _ := data["user"].(map[string]any)
+ if id, _ := user["id"].(float64); int64(id) != want {
+ t.Errorf("%s signed in as %v, want %d", email, id, want)
+ }
+ }
+ check("[email protected]", "password-upper", upper)
+ check("[email protected]", "password-lower", lower)
+
+ for _, pass := range []string{"password-upper", "password-lower"} {
+ if code, _ := loginRequest(t, "[email protected]", pass); code != http.StatusUnauthorized {
+ t.Errorf("ambiguous address with %q = %d, want 401", pass, code)
+ }
+ }
+}
+
+func TestRegisterOnACollidingInstallStillRefusesAVariant(t *testing.T) {
+ setupTestDB(t)
+ seedCollidingAccounts(t, "[email protected]", "password-upper", "[email protected]", "password-lower")
+
+ if code := registerRequest(t, "[email protected]"); code != http.StatusConflict {
+ t.Fatalf("status = %d, want 409", code)
+ }
+ if n := userCount(t); n != 2 {
+ t.Errorf("users = %d, want 2", n)
+ }
+}
diff --git a/backend/controllers/password_test.go b/backend/controllers/password_test.go
index 98b2e6c..175bbd3 100644
--- a/backend/controllers/password_test.go
+++ b/backend/controllers/password_test.go
@@ -268,7 +268,7 @@ func TestResetPasswordReplacesHashAndRevokesSessions(t *testing.T) {
if err != nil {
t.Fatalf("hash: %v", err)
}
- if err := th.s.User.ResetPassword("[email protected]", newHash); err != nil {
+ if _, err := th.s.User.ResetPassword("[email protected]", newHash); err != nil {
t.Fatalf("reset: %v", err)
}
@@ -296,7 +296,7 @@ func TestResetPasswordUnknownEmail(t *testing.T) {
setupTestDB(t)
registerAndLogin(t, "[email protected]", "password123")
- err := th.s.User.ResetPassword("[email protected]", "irrelevant-hash")
+ _, err := th.s.User.ResetPassword("[email protected]", "irrelevant-hash")
if !errors.Is(err, stores.ErrNoSuchUser) {
t.Fatalf("err = %v, want ErrNoSuchUser", err)
}
@@ -312,7 +312,7 @@ func TestResetPasswordLeavesOtherAccountsAlone(t *testing.T) {
if err != nil {
t.Fatalf("hash: %v", err)
}
- if err := th.s.User.ResetPassword("[email protected]", newHash); err != nil {
+ if _, err := th.s.User.ResetPassword("[email protected]", newHash); err != nil {
t.Fatalf("reset: %v", err)
}
@@ -362,7 +362,7 @@ func TestPasswordWritesRefuseAnEmptyHash(t *testing.T) {
if _, err := th.s.User.ChangePassword(uid, before, ""); !errors.Is(err, stores.ErrEmptyHash) {
t.Errorf("ChangePassword with an empty hash: err = %v, want ErrEmptyHash", err)
}
- if err := th.s.User.ResetPassword("[email protected]", ""); !errors.Is(err, stores.ErrEmptyHash) {
+ if _, err := th.s.User.ResetPassword("[email protected]", ""); !errors.Is(err, stores.ErrEmptyHash) {
t.Errorf("ResetPassword with an empty hash: err = %v, want ErrEmptyHash", err)
}
if storedHash(t, uid) != before {
@@ -420,3 +420,60 @@ func TestPasswordLengthLimitIsAClientError(t *testing.T) {
}
})
}
+
+func TestResetPasswordIgnoresCase(t *testing.T) {
+ setupTestDB(t)
+ uid, _ := registerAndLogin(t, "[email protected]", "password123")
+
+ newHash, err := utils.HashPassword("operatorset789")
+ if err != nil {
+ t.Fatalf("hash: %v", err)
+ }
+ stored, err := th.s.User.ResetPassword("[email protected]", newHash)
+ if err != nil {
+ t.Fatalf("reset: %v", err)
+ }
+ if stored != "[email protected]" {
+ t.Errorf("reported %q, want the stored spelling [email protected]", stored)
+ }
+ if !utils.CheckPassword("operatorset789", storedHash(t, uid)) {
+ t.Error("the new password does not verify")
+ }
+ if v := tokenVersion(t, uid); v != 2 {
+ t.Errorf("token_version = %d, want 2", v)
+ }
+}
+
+func TestResetPasswordRefusesAnAmbiguousAddress(t *testing.T) {
+ setupTestDB(t)
+ upper, lower := seedCollidingAccounts(t, "[email protected]", "password-upper", "[email protected]", "password-lower")
+ upperBefore, lowerBefore := storedHash(t, upper), storedHash(t, lower)
+
+ newHash, err := utils.HashPassword("operatorset789")
+ if err != nil {
+ t.Fatalf("hash: %v", err)
+ }
+ _, err = th.s.User.ResetPassword("[email protected]", newHash)
+ if !errors.Is(err, stores.ErrAmbiguousEmail) {
+ t.Fatalf("err = %v, want ErrAmbiguousEmail", err)
+ }
+ if !strings.Contains(err.Error(), "[email protected]") || !strings.Contains(err.Error(), "[email protected]") {
+ t.Errorf("error %q does not list both spellings", err)
+ }
+ if storedHash(t, upper) != upperBefore || storedHash(t, lower) != lowerBefore {
+ t.Error("a hash changed")
+ }
+ if tokenVersion(t, upper) != 1 || tokenVersion(t, lower) != 1 {
+ t.Error("a token_version changed")
+ }
+
+ if _, err := th.s.User.ResetPassword("[email protected]", newHash); err != nil {
+ t.Fatalf("exact reset: %v", err)
+ }
+ if storedHash(t, lower) == lowerBefore || tokenVersion(t, lower) != 2 {
+ t.Error("the named account was not reset")
+ }
+ if storedHash(t, upper) != upperBefore || tokenVersion(t, upper) != 1 {
+ t.Error("the other account changed")
+ }
+}
diff --git a/backend/db/migrations.go b/backend/db/migrations.go
index c08719b..602ccbb 100644
--- a/backend/db/migrations.go
+++ b/backend/db/migrations.go
@@ -172,6 +172,49 @@ func alterMigrations() {
ensureIndex("idx_saved_foods_unique",
`CREATE UNIQUE INDEX IF NOT EXISTS idx_saved_foods_unique ON saved_foods(user_id, name, brand)`)
}
+
+ // Email identity is SQLite's NOCASE collation, which folds ASCII A-Z only: domains are
+ // ASCII or punycode and SMTPUTF8 local parts are rare, so 'É@x.com' and 'é@x.com' stay
+ // two addresses. The BINARY UNIQUE on the column stays (SQLite cannot drop it without
+ // rebuilding the table); it is harmless, since byte-identical addresses are NOCASE-equal.
+ // No migration_flags row: the collision check must re-run every boot until it is clean.
+ if emailsFoldUnique() {
+ ensureIndex("idx_users_email_nocase",
+ `CREATE UNIQUE INDEX IF NOT EXISTS idx_users_email_nocase ON users(email COLLATE NOCASE)`)
+ }
+}
+
+// emailsFoldUnique reports whether no two addresses differ only in letter case, i.e.
+// whether the case-insensitive unique index may be created. Accounts hold separate user
+// data, so a collision is logged and left alone, never merged or deleted. False means
+// "not now", never a reason to fail the boot.
+func emailsFoldUnique() bool {
+ const skip = "migrations: email collision check: %v (skipping the case-insensitive email index this boot)"
+ rows, err := DB.Query(`SELECT group_concat(email, ', ') FROM users GROUP BY email COLLATE NOCASE HAVING COUNT(*) > 1`)
+ if err != nil {
+ log.Printf(skip, err)
+ return false
+ }
+ var groups []string
+ for rows.Next() {
+ var g string
+ if err := rows.Scan(&g); err != nil {
+ rows.Close()
+ log.Printf(skip, err)
+ return false
+ }
+ groups = append(groups, g)
+ }
+ err = rows.Err()
+ rows.Close()
+ if err != nil {
+ log.Printf(skip, err)
+ return false
+ }
+ for _, g := range groups {
+ log.Printf("migrations: accounts %s differ only in letter case; each still signs in with its exact spelling. Lyftr will not merge or delete them. To enforce case-insensitive addresses, remove the one you do not want with: docker compose exec backend ./lyftr-api delete-account <exact address> (it lists what will be deleted and asks you to confirm); the index is created on the next start.", g)
+ }
+ return len(groups) == 0
}
// dedupeSavedFoods collapses duplicate stars, keeping the lowest id in each
diff --git a/backend/db/migrations_test.go b/backend/db/migrations_test.go
index eebb3da..4144cb0 100644
--- a/backend/db/migrations_test.go
+++ b/backend/db/migrations_test.go
@@ -1,9 +1,13 @@
package db
import (
+ "bytes"
"database/sql"
"fmt"
+ "log"
"math/rand"
+ "os"
+ "strings"
"testing"
"time"
@@ -787,3 +791,112 @@ func TestAlterMigrations_addsDisplayNameToAnExistingSettingsRow(t *testing.T) {
t.Fatalf("display_name = %q after re-running migrations", name)
}
}
+
+func emailIndexCount(t *testing.T) int {
+ t.Helper()
+ var n int
+ if err := DB.QueryRow(`SELECT COUNT(*) FROM sqlite_master WHERE type='index' AND name='idx_users_email_nocase'`).Scan(&n); err != nil {
+ t.Fatalf("count index: %v", err)
+ }
+ return n
+}
+
+func captureLog(t *testing.T) *bytes.Buffer {
+ t.Helper()
+ var buf bytes.Buffer
+ log.SetOutput(&buf)
+ t.Cleanup(func() { log.SetOutput(os.Stderr) })
+ return &buf
+}
+
+func seedEmailUser(t *testing.T, email string) int64 {
+ t.Helper()
+ res, err := DB.Exec(`INSERT INTO users (email, password_hash) VALUES (?, 'x')`, email)
+ if err != nil {
+ t.Fatalf("seed %s: %v", email, err)
+ }
+ id, _ := res.LastInsertId()
+ if _, err := DB.Exec(`INSERT INTO user_settings (user_id) VALUES (?)`, id); err != nil {
+ t.Fatalf("seed settings: %v", err)
+ }
+ return id
+}
+
+func TestEmailNocaseIndex_createdOnACleanInstall(t *testing.T) {
+ setupMigrationTestDB(t)
+ seedEmailUser(t, "[email protected]")
+
+ alterMigrations()
+
+ if emailIndexCount(t) != 1 {
+ t.Fatal("index missing")
+ }
+ var email string
+ if err := DB.QueryRow(`SELECT email FROM users`).Scan(&email); err != nil || email != "[email protected]" {
+ t.Errorf("email = %q, %v; want it untouched", email, err)
+ }
+ if _, err := DB.Exec(`INSERT INTO users (email, password_hash) VALUES ('[email protected]', 'x')`); err == nil {
+ t.Error("a case variant was accepted")
+ }
+}
+
+func TestEmailNocaseIndex_skippedWhenAddressesCollide(t *testing.T) {
+ setupMigrationTestDB(t)
+ a := seedEmailUser(t, "[email protected]")
+ b := seedEmailUser(t, "[email protected]")
+ buf := captureLog(t)
+
+ alterMigrations()
+
+ if emailIndexCount(t) != 0 {
+ t.Error("index created despite a collision")
+ }
+ var n int
+ if err := DB.QueryRow(`SELECT COUNT(*) FROM users WHERE (id = ? AND email = '[email protected]') OR (id = ? AND email = '[email protected]')`, a, b).Scan(&n); err != nil || n != 2 {
+ t.Errorf("users = %d, %v; want both untouched", n, err)
+ }
+ if err := DB.QueryRow(`SELECT COUNT(*) FROM user_settings WHERE user_id IN (?, ?)`, a, b).Scan(&n); err != nil || n != 2 {
+ t.Errorf("user_settings = %d, %v; want both kept", n, err)
+ }
+ out := buf.String()
+ if !strings.Contains(out, "[email protected]") || !strings.Contains(out, "[email protected]") {
+ t.Errorf("log does not name both spellings: %s", out)
+ }
+ if !strings.Contains(out, "delete-account") || strings.Contains(out, "Settings") {
+ t.Errorf("log should name delete-account and not Settings: %s", out)
+ }
+}
+
+func TestEmailNocaseIndex_isIdempotentAcrossBoots(t *testing.T) {
+ setupMigrationTestDB(t)
+ seedEmailUser(t, "[email protected]")
+ alterMigrations()
+ alterMigrations()
+ if emailIndexCount(t) != 1 {
+ t.Fatal("clean install: index count != 1")
+ }
+ var n int
+ if err := DB.QueryRow(`SELECT COUNT(*) FROM users`).Scan(&n); err != nil || n != 1 {
+ t.Fatalf("users = %d, %v", n, err)
+ }
+
+ setupMigrationTestDB(t)
+ seedEmailUser(t, "[email protected]")
+ b := seedEmailUser(t, "[email protected]")
+ alterMigrations()
+ alterMigrations()
+ if emailIndexCount(t) != 0 {
+ t.Fatal("colliding install: index exists")
+ }
+ if err := DB.QueryRow(`SELECT COUNT(*) FROM users`).Scan(&n); err != nil || n != 2 {
+ t.Fatalf("users = %d, %v", n, err)
+ }
+
+ if _, err := DB.Exec(`DELETE FROM users WHERE id = ?`, b); err != nil {
+ t.Fatalf("delete: %v", err)
+ }
+ alterMigrations()
+ if emailIndexCount(t) != 1 {
+ t.Error("index not created after the collision was resolved")
+ }
+}
diff --git a/backend/deleteaccount.go b/backend/deleteaccount.go
new file mode 100644
index 0000000..8caa95b
--- /dev/null
+++ b/backend/deleteaccount.go
@@ -0,0 +1,110 @@
+package main
+
+import (
+ "bufio"
+ "errors"
+ "fmt"
+ "io"
+ "os"
+ "strings"
+
+ "github.com/Cawlumm/lyftr-backend/config"
+ "github.com/Cawlumm/lyftr-backend/db"
+ "github.com/Cawlumm/lyftr-backend/stores"
+)
+
+const deleteUsage = `usage: lyftr-api delete-account <email>
+
+Deletes an account and everything in it, after showing what that is and asking you
+to type the address again.
+
+The address must match the stored one exactly, letter case included.
+
+Run it against the container holding your data volume:
+
+ docker compose exec backend ./lyftr-api delete-account [email protected]
+`
+
+// runDeleteAccount is the operator's way to remove an account, chiefly the unwanted one of
+// two that differ only in letter case, so the case-insensitive email index can be created.
+//
+// The lookup is exact: a destructive command must not resolve by folding case, so a
+// near-miss lists the stored spellings and deletes nothing. The confirmation is the address
+// typed back, read from stdin and never taken as a flag (the GitHub and Heroku
+// type-the-name pattern; Nextcloud's `occ user:delete` and Gitea's `admin user delete` ask
+// nothing). There is no --yes: piping the exact address is the unattended path, and the
+// address is not a secret.
+//
+// Returns the process exit code.
+func runDeleteAccount(args []string) int {
+ if len(args) != 1 || strings.HasPrefix(args[0], "-") || strings.TrimSpace(args[0]) == "" {
+ fmt.Fprint(os.Stderr, deleteUsage)
+ return 2
+ }
+ email := strings.TrimSpace(args[0])
+
+ config.Load()
+ db.Connect()
+
+ s := stores.New(db.DB)
+ u, spellings, err := s.User.GetByExactEmail(email)
+ switch {
+ case errors.Is(err, stores.ErrNoSuchUser):
+ fmt.Fprintf(os.Stderr, "no account found for %s\n", email)
+ return 1
+ case errors.Is(err, stores.ErrInexactEmail):
+ fmt.Fprintf(os.Stderr, "no account is spelled exactly %s; these differ only in letter case:\n", email)
+ for _, sp := range spellings {
+ fmt.Fprintf(os.Stderr, " %s\n", sp)
+ }
+ fmt.Fprintln(os.Stderr, "Nothing was deleted. Run it again with the exact spelling of the one to delete.")
+ return 1
+ case err != nil:
+ fmt.Fprintf(os.Stderr, "lookup failed: %v\n", err)
+ return 1
+ }
+
+ d, err := s.User.CountData(u.ID)
+ if err != nil {
+ fmt.Fprintf(os.Stderr, "could not count the account's data: %v\n", err)
+ return 1
+ }
+ fmt.Printf("This deletes %s and its settings, along with:\n", u.Email)
+ fmt.Printf(" %-16s %d\n", "workouts", d.Workouts)
+ fmt.Printf(" %-16s %d\n", "workout sets", d.Sets)
+ fmt.Printf(" %-16s %d\n", "food logs", d.FoodLogs)
+ fmt.Printf(" %-16s %d\n", "weight logs", d.WeightLogs)
+ fmt.Printf(" %-16s %d\n", "programs", d.Programs)
+ fmt.Printf(" %-16s %d\n", "saved foods", d.SavedFoods)
+ fmt.Printf(" %-16s %d\n", "active sessions", d.ActiveSessions)
+ fmt.Println("This cannot be undone. Exercises are shared and are not affected.")
+
+ if n, err := s.User.Count(); err == nil && n == 1 {
+ switch config.C.Registration {
+ case config.RegistrationFirstUser:
+ fmt.Println("This is the only account. With REGISTRATION=first-user, whoever registers next becomes the owner.")
+ case config.RegistrationClosed:
+ fmt.Println("This is the only account. With REGISTRATION=closed, nobody will be able to sign in or register.")
+ default:
+ fmt.Println("This is the only account on this server.")
+ }
+ }
+
+ fmt.Printf("Type %s to confirm: ", u.Email)
+ line, err := bufio.NewReader(os.Stdin).ReadString('\n')
+ if err != nil && (!errors.Is(err, io.EOF) || line == "") {
+ fmt.Fprintln(os.Stderr, "\nno confirmation on stdin (run with -it for a prompt). Nothing was deleted.")
+ return 1
+ }
+ if strings.TrimRight(line, "\r\n") != u.Email {
+ fmt.Fprintln(os.Stderr, "\nThat does not match. Nothing was deleted.")
+ return 1
+ }
+
+ if err := s.User.Delete(u.ID); err != nil {
+ fmt.Fprintf(os.Stderr, "delete failed: %v\n", err)
+ return 1
+ }
+ fmt.Printf("Deleted %s and everything it held.\n", u.Email)
+ return 0
+}
diff --git a/backend/deleteaccount_test.go b/backend/deleteaccount_test.go
new file mode 100644
index 0000000..fe368bb
--- /dev/null
+++ b/backend/deleteaccount_test.go
@@ -0,0 +1,258 @@
+package main
+
+import (
+ "bytes"
+ "io"
+ "log"
+ "os"
+ "path/filepath"
+ "strings"
+ "testing"
+
+ "github.com/Cawlumm/lyftr-backend/config"
+ "github.com/Cawlumm/lyftr-backend/db"
+ "github.com/Cawlumm/lyftr-backend/stores"
+)
+
+// setupDeleteDB points the config at a fresh temp-file database, builds the schema and
+// drops the nocase email index so case-variant accounts can be seeded. The env is set
+// explicitly so backend/.env cannot leak in (godotenv never overrides a set variable).
+func setupDeleteDB(t *testing.T, registration string) {
+ t.Helper()
+ t.Setenv("DB_PATH", filepath.Join(t.TempDir(), "lyftr.db"))
+ t.Setenv("ENV", "test")
+ t.Setenv("REGISTRATION", registration)
+ t.Setenv("DEMO_MODE", "false")
+
+ var sink bytes.Buffer
+ log.SetOutput(&sink)
+ t.Cleanup(func() { log.SetOutput(os.Stderr) })
+
+ reconnect()
+ // Registered after TempDir, so it runs first: Windows cannot remove an open SQLite file.
+ t.Cleanup(func() { db.DB.Close() })
+ if _, err := db.DB.Exec(`DROP INDEX IF EXISTS idx_users_email_nocase`); err != nil {
+ t.Fatal(err)
+ }
+}
+
+// reconnect opens the database the way the server and the subcommands do.
+func reconnect() {
+ if db.DB != nil {
+ db.DB.Close()
+ }
+ config.Load()
+ db.Connect()
+}
+
+func execSQL(t *testing.T, q string, args ...any) int64 {
+ t.Helper()
+ res, err := db.DB.Exec(q, args...)
+ if err != nil {
+ t.Fatalf("exec %q: %v", q, err)
+ }
+ id, _ := res.LastInsertId()
+ return id
+}
+
+func seedFullAccount(t *testing.T, email string) int64 {
+ t.Helper()
+ uid := execSQL(t, `INSERT INTO users (email, password_hash) VALUES (?, 'x')`, email)
+ execSQL(t, `INSERT INTO user_settings (user_id) VALUES (?)`, uid)
+ execSQL(t, `INSERT OR IGNORE INTO exercises (name) VALUES ('Squat')`)
+ var ex int64
+ if err := db.DB.QueryRow(`SELECT id FROM exercises WHERE name = 'Squat'`).Scan(&ex); err != nil {
+ t.Fatal(err)
+ }
+ w := execSQL(t, `INSERT INTO workouts (user_id, name) VALUES (?, 'w')`, uid)
+ we := execSQL(t, `INSERT INTO workout_exercises (workout_id, exercise_id) VALUES (?, ?)`, w, ex)
+ execSQL(t, `INSERT INTO sets (workout_exercise_id) VALUES (?)`, we)
+ execSQL(t, `INSERT INTO food_logs (user_id, name, logged_on) VALUES (?, 'f', '2026-01-01')`, uid)
+ execSQL(t, `INSERT INTO weight_logs (user_id, weight, logged_on) VALUES (?, 180, '2026-01-01')`, uid)
+ execSQL(t, `INSERT INTO saved_foods (user_id, name) VALUES (?, 's')`, uid)
+ execSQL(t, `INSERT INTO active_sessions (user_id, data) VALUES (?, '{}')`, uid)
+ p := execSQL(t, `INSERT INTO programs (user_id, name) VALUES (?, 'p')`, uid)
+ d := execSQL(t, `INSERT INTO program_days (program_id) VALUES (?)`, p)
+ pe := execSQL(t, `INSERT INTO program_exercises (program_id, exercise_id, program_day_id) VALUES (?, ?, ?)`, p, ex, d)
+ execSQL(t, `INSERT INTO program_sets (program_exercise_id) VALUES (?)`, pe)
+ return uid
+}
+
+func userCount(t *testing.T) int {
+ t.Helper()
+ n, err := stores.New(db.DB).User.Count()
+ if err != nil {
+ t.Fatal(err)
+ }
+ return n
+}
+
+func dataOf(t *testing.T, uid int64) stores.AccountData {
+ t.Helper()
+ d, err := stores.New(db.DB).User.CountData(uid)
+ if err != nil {
+ t.Fatal(err)
+ }
+ return d
+}
+
+// runDelete runs the subcommand with stdin, capturing stdout and stderr. Log output goes
+// to a separate buffer so the boot warning, which names the same spellings, cannot
+// satisfy an assertion about the command's own output. The command reconnects, so the
+// test's handle is closed first and db.DB is the command's afterwards.
+func runDelete(t *testing.T, stdin string, args ...string) (code int, stdout, stderr string) {
+ t.Helper()
+ db.DB.Close()
+ withStdin(t, stdin)
+
+ var logSink bytes.Buffer
+ log.SetOutput(&logSink)
+
+ origOut, origErr := os.Stdout, os.Stderr
+ ro, wo, _ := os.Pipe()
+ re, we, _ := os.Pipe()
+ os.Stdout, os.Stderr = wo, we
+ outc, errc := make(chan string), make(chan string)
+ go func() { b, _ := io.ReadAll(ro); outc <- string(b) }()
+ go func() { b, _ := io.ReadAll(re); errc <- string(b) }()
+
+ code = runDeleteAccount(args)
+
+ wo.Close()
+ we.Close()
+ os.Stdout, os.Stderr = origOut, origErr
+ return code, <-outc, <-errc
+}
+
+func TestDeleteAccountExactMatchDeletesAndCascades(t *testing.T) {
+ setupDeleteDB(t, "open")
+ uid := seedFullAccount(t, "[email protected]")
+ seedFullAccount(t, "[email protected]")
+
+ code, out, errOut := runDelete(t, "[email protected]\n", "[email protected]")
+ if code != 0 {
+ t.Fatalf("exit %d, stderr %q", code, errOut)
+ }
+ if !strings.Contains(out, "This deletes [email protected] and its settings, along with:") || !strings.Contains(out, "Deleted [email protected]") {
+ t.Errorf("stdout missing header or success line: %q", out)
+ }
+ if userCount(t) != 1 {
+ t.Errorf("users = %d, want 1", userCount(t))
+ }
+ if d := dataOf(t, uid); d != (stores.AccountData{}) {
+ t.Errorf("data left behind: %+v", d)
+ }
+}
+
+func TestDeleteAccountCaseVariantDeletesNothing(t *testing.T) {
+ setupDeleteDB(t, "open")
+ uid := seedFullAccount(t, "[email protected]")
+
+ code, _, errOut := runDelete(t, "[email protected]\n", "[email protected]")
+ if code != 1 {
+ t.Fatalf("exit %d, want 1", code)
+ }
+ if !strings.Contains(errOut, "[email protected]") || !strings.Contains(errOut, "Nothing was deleted") {
+ t.Errorf("stderr should list the spelling: %q", errOut)
+ }
+ if userCount(t) != 1 || dataOf(t, uid).Workouts != 1 {
+ t.Error("something was deleted")
+ }
+}
+
+func TestDeleteAccountWrongConfirmationDeletesNothing(t *testing.T) {
+ for name, stdin := range map[string]string{
+ "different text": "nope\n",
+ "different case": "[email protected]\n",
+ "trailing space": "[email protected] \n",
+ "empty line": "\n",
+ "eof": "",
+ } {
+ t.Run(name, func(t *testing.T) {
+ setupDeleteDB(t, "open")
+ uid := seedFullAccount(t, "[email protected]")
+ code, _, _ := runDelete(t, stdin, "[email protected]")
+ if code != 1 {
+ t.Fatalf("exit %d, want 1", code)
+ }
+ if userCount(t) != 1 || dataOf(t, uid).Workouts != 1 {
+ t.Error("something was deleted")
+ }
+ })
+ }
+}
+
+func TestDeleteAccountUnknownAddress(t *testing.T) {
+ setupDeleteDB(t, "open")
+ seedFullAccount(t, "[email protected]")
+ code, _, errOut := runDelete(t, "[email protected]\n", "[email protected]")
+ if code != 1 || !strings.Contains(errOut, "no account found") {
+ t.Errorf("exit %d, stderr %q", code, errOut)
+ }
+ if userCount(t) != 1 {
+ t.Error("something was deleted")
+ }
+}
+
+func TestDeleteAccountUsage(t *testing.T) {
+ for _, args := range [][]string{nil, {"[email protected]", "[email protected]"}, {"--yes"}, {" "}} {
+ origErr := os.Stderr
+ r, w, _ := os.Pipe()
+ os.Stderr = w
+ code := runDeleteAccount(args)
+ w.Close()
+ os.Stderr = origErr
+ got, _ := io.ReadAll(r)
+ if code != 2 || !strings.Contains(string(got), "docker compose exec") {
+ t.Errorf("args %q: exit %d, stderr %q", args, code, got)
+ }
+ }
+}
+
+func TestDeleteAccountResolvesCollisionAndIndexFollows(t *testing.T) {
+ setupDeleteDB(t, "open")
+ keep := seedFullAccount(t, "[email protected]")
+ drop := seedFullAccount(t, "[email protected]")
+ keptBefore := dataOf(t, keep)
+
+ code, _, errOut := runDelete(t, "[email protected]\n", "[email protected]")
+ if code != 0 {
+ t.Fatalf("exit %d, stderr %q", code, errOut)
+ }
+ if dataOf(t, drop) != (stores.AccountData{}) {
+ t.Error("deleted account kept data")
+ }
+ if dataOf(t, keep) != keptBefore {
+ t.Error("the other account's data changed")
+ }
+ var n int
+ if err := db.DB.QueryRow(`SELECT COUNT(*) FROM user_settings WHERE user_id = ?`, keep).Scan(&n); err != nil || n != 1 {
+ t.Errorf("kept account's settings = %d, %v", n, err)
+ }
+ if err := db.DB.QueryRow(`SELECT COUNT(*) FROM users WHERE email = '[email protected]'`).Scan(&n); err != nil || n != 0 {
+ t.Errorf("deleted spelling still present: %d, %v", n, err)
+ }
+
+ // Second boot: the collision is gone, so the index is created and enforced.
+ reconnect()
+ if err := db.DB.QueryRow(`SELECT COUNT(*) FROM sqlite_master WHERE name = 'idx_users_email_nocase'`).Scan(&n); err != nil || n != 1 {
+ t.Fatalf("index count = %d, %v; want 1", n, err)
+ }
+ if _, err := db.DB.Exec(`INSERT INTO users (email, password_hash) VALUES ('[email protected]', 'x')`); err == nil {
+ t.Error("a case variant was accepted after the index was created")
+ }
+}
+
+func TestDeleteAccountWarnsOnLastAccount(t *testing.T) {
+ setupDeleteDB(t, "first-user")
+ seedFullAccount(t, "[email protected]")
+ code, out, errOut := runDelete(t, "[email protected]\n", "[email protected]")
+ if code != 0 {
+ t.Fatalf("exit %d, stderr %q", code, errOut)
+ }
+ warn := strings.Index(out, "whoever registers next becomes the owner")
+ prompt := strings.Index(out, "to confirm:")
+ if warn < 0 || prompt < 0 || warn > prompt {
+ t.Errorf("warning should precede the prompt: %q", out)
+ }
+}
diff --git a/backend/main.go b/backend/main.go
index 6ce2769..28bdd31 100644
--- a/backend/main.go
+++ b/backend/main.go
@@ -49,6 +49,7 @@ func warnIfUnclaimed() {
// flag.Parse, which would otherwise treat the name as a positional argument and start the
// server as usual.
var subcommands = map[string]func(args []string) int{
+ "delete-account": runDeleteAccount,
"reset-password": runResetPassword,
}
diff --git a/backend/main_test.go b/backend/main_test.go
index 245f304..19f3713 100644
--- a/backend/main_test.go
+++ b/backend/main_test.go
@@ -32,3 +32,9 @@ func TestResetPasswordIsRegistered(t *testing.T) {
t.Fatal("reset-password is not in the subcommand table")
}
}
+
+func TestDeleteAccountIsRegistered(t *testing.T) {
+ if _, ok := subcommands["delete-account"]; !ok {
+ t.Fatal("delete-account is not in the subcommand table")
+ }
+}
diff --git a/backend/resetpassword.go b/backend/resetpassword.go
index 4583ba2..f9ec4e7 100644
--- a/backend/resetpassword.go
+++ b/backend/resetpassword.go
@@ -64,22 +64,21 @@ func runResetPassword(args []string) int {
}
s := stores.New(db.DB)
- if err := s.User.ResetPassword(email, hash); err != nil {
+ stored, err := s.User.ResetPassword(email, hash)
+ if err != nil {
if errors.Is(err, stores.ErrNoSuchUser) {
fmt.Fprintf(os.Stderr, "no account found for %s\n", email)
- // Addresses match exactly here and at login, so a case slip looks identical
- // to a missing account. Someone recovering an account they cannot get into
- // should not be left concluding it is gone.
- if stored, ferr := s.User.FindEmailFold(email); ferr == nil && stored != email {
- fmt.Fprintf(os.Stderr, "did you mean %s? addresses are case-sensitive.\n", stored)
- }
+ return 1
+ }
+ if errors.Is(err, stores.ErrAmbiguousEmail) {
+ fmt.Fprintf(os.Stderr, "%s matches several accounts that differ only in letter case (%v). Nothing was changed; run it again with the exact spelling of the one to reset.\n", email, err)
return 1
}
fmt.Fprintf(os.Stderr, "reset failed: %v\n", err)
return 1
}
- fmt.Printf("Password reset for %s.\n", email)
+ fmt.Printf("Password reset for %s.\n", stored)
fmt.Println("Every existing session for that account has been signed out.")
return 0
}
diff --git a/backend/seed/users.go b/backend/seed/users.go
index 1bf8e52..af35fcf 100644
--- a/backend/seed/users.go
+++ b/backend/seed/users.go
@@ -14,7 +14,10 @@ const DemoEmail = "[email protected]"
func DemoUser(db *sql.DB) {
var count int
- db.QueryRow(`SELECT COUNT(*) FROM users WHERE email = ?`, DemoEmail).Scan(&count)
+ // NOCASE, as everywhere else an address is matched: a case-variant of the demo address is
+ // the demo account for this purpose, and inserting beside it would create the duplicate
+ // the unique index and createUserTx exist to prevent.
+ db.QueryRow(`SELECT COUNT(*) FROM users WHERE email = ? COLLATE NOCASE`, DemoEmail).Scan(&count)
if count > 0 {
return
}
@@ -45,7 +48,7 @@ func DemoUser(db *sql.DB) {
// dropping someone's data on upgrade is not a trade this can make for them.
func WarnLeftoverDemoUser(db *sql.DB) {
var count int
- if err := db.QueryRow(`SELECT COUNT(*) FROM users WHERE email = ?`, DemoEmail).Scan(&count); err != nil || count == 0 {
+ if err := db.QueryRow(`SELECT COUNT(*) FROM users WHERE email = ? COLLATE NOCASE`, DemoEmail).Scan(&count); err != nil || count == 0 {
return
}
log.Printf("WARNING: this instance still has the %s account from an earlier version, and "+
diff --git a/backend/seed/users_test.go b/backend/seed/users_test.go
new file mode 100644
index 0000000..73bba65
--- /dev/null
+++ b/backend/seed/users_test.go
@@ -0,0 +1,56 @@
+package seed
+
+import (
+ "database/sql"
+ "testing"
+
+ _ "modernc.org/sqlite"
+)
+
+func demoTestDB(t *testing.T) *sql.DB {
+ t.Helper()
+ db, err := sql.Open("sqlite", ":memory:")
+ if err != nil {
+ t.Fatal(err)
+ }
+ db.SetMaxOpenConns(1)
+ t.Cleanup(func() { db.Close() })
+ for _, q := range []string{
+ `CREATE TABLE users (id INTEGER PRIMARY KEY, email TEXT NOT NULL UNIQUE, password_hash TEXT NOT NULL)`,
+ `CREATE TABLE user_settings (user_id INTEGER)`,
+ } {
+ if _, err := db.Exec(q); err != nil {
+ t.Fatal(err)
+ }
+ }
+ return db
+}
+
+func userCount(t *testing.T, db *sql.DB) int {
+ t.Helper()
+ var n int
+ if err := db.QueryRow(`SELECT COUNT(*) FROM users`).Scan(&n); err != nil {
+ t.Fatal(err)
+ }
+ return n
+}
+
+func TestDemoUserCreatesTheAccountOnce(t *testing.T) {
+ db := demoTestDB(t)
+ DemoUser(db)
+ DemoUser(db)
+ if n := userCount(t, db); n != 1 {
+ t.Errorf("users = %d, want 1", n)
+ }
+}
+
+func TestDemoUserDoesNotCreateOneBesideACaseVariant(t *testing.T) {
+ db := demoTestDB(t)
+ if _, err := db.Exec(`INSERT INTO users (email, password_hash) VALUES ('[email protected]', 'x')`); err != nil {
+ t.Fatal(err)
+ }
+ DemoUser(db)
+ if n := userCount(t, db); n != 1 {
+ t.Errorf("users = %d, want 1: a second case-variant demo account was created", n)
+ }
+}
diff --git a/backend/stores/user.go b/backend/stores/user.go
index 702bab0..c30658e 100644
--- a/backend/stores/user.go
+++ b/backend/stores/user.go
@@ -3,6 +3,8 @@ package stores
import (
"database/sql"
"errors"
+ "fmt"
+ "strings"
"github.com/Cawlumm/lyftr-backend/models"
)
@@ -19,12 +21,65 @@ func (s *UserStore) GetMe(uid int64) (models.User, error) {
return u, err
}
-// GetByEmail loads a user incl. password_hash for login. sql.ErrNoRows if absent.
+// ErrAmbiguousEmail means an address matches several accounts that differ only in letter
+// case, and none of them is spelled exactly as given.
+var ErrAmbiguousEmail = errors.New("address matches several accounts")
+
+// ErrEmailTaken means another account already holds the address, ignoring letter case.
+var ErrEmailTaken = errors.New("email already registered")
+
+// matchEmail is the one place an address becomes an account. NOCASE decides what "the
+// same address" means (no Go code folds case, so Go and SQL cannot disagree): an exact
+// spelling wins, otherwise a single match is used, and several matches with no exact one
+// are ambiguous. It returns every spelling found alongside ErrAmbiguousEmail. All rows
+// are read and closed before returning: the pool has one connection.
+func (s *UserStore) matchEmail(email string) (models.User, []string, error) {
+ rows, err := s.db.Query(
+ `SELECT id, email, password_hash, token_version, created_at, updated_at
+ FROM users WHERE email = ? COLLATE NOCASE ORDER BY id`, email)
+ if err != nil {
+ return models.User{}, nil, err
+ }
+ var found []models.User
+ for rows.Next() {
+ var u models.User
+ if err := rows.Scan(&u.ID, &u.Email, &u.Password, &u.TokenVersion, &u.CreatedAt, &u.UpdatedAt); err != nil {
+ rows.Close()
+ return models.User{}, nil, err
+ }
+ found = append(found, u)
+ }
+ err = rows.Err()
+ rows.Close()
+ if err != nil {
+ return models.User{}, nil, err
+ }
+ for _, u := range found {
+ if u.Email == email {
+ return u, nil, nil
+ }
+ }
+ switch len(found) {
+ case 0:
+ return models.User{}, nil, sql.ErrNoRows
+ case 1:
+ return found[0], nil, nil
+ }
+ spellings := make([]string, len(found))
+ for i, u := range found {
+ spellings[i] = u.Email
+ }
+ return models.User{}, spellings, ErrAmbiguousEmail
+}
+
+// GetByEmail loads a user incl. password_hash for login, matching the address
+// case-insensitively. sql.ErrNoRows if absent, and also if it is ambiguous between
+// case-variant accounts, so login answers both the same way.
func (s *UserStore) GetByEmail(email string) (models.User, error) {
- var u models.User
- err := s.db.QueryRow(
- `SELECT id, email, password_hash, token_version, created_at, updated_at FROM users WHERE email = ?`, email,
- ).Scan(&u.ID, &u.Email, &u.Password, &u.TokenVersion, &u.CreatedAt, &u.UpdatedAt)
+ u, _, err := s.matchEmail(email)
+ if errors.Is(err, ErrAmbiguousEmail) {
+ return models.User{}, sql.ErrNoRows
+ }
return u, err
}
@@ -178,6 +233,14 @@ func (s *UserStore) CreateFirst(email, hash string) (int64, error) {
}
func createUserTx(tx *sql.Tx, email, hash string) (int64, error) {
+ // The unique index cannot exist on an install that already holds case-variant accounts, so check here too.
+ var taken int
+ switch err := tx.QueryRow(`SELECT 1 FROM users WHERE email = ? COLLATE NOCASE LIMIT 1`, email).Scan(&taken); {
+ case err == nil:
+ return 0, ErrEmailTaken
+ case !errors.Is(err, sql.ErrNoRows):
+ return 0, err
+ }
res, err := tx.Exec(`INSERT INTO users (email, password_hash) VALUES (?, ?)`, email, hash)
if err != nil {
return 0, err
@@ -199,19 +262,6 @@ var ErrEmptyHash = errors.New("refusing to store an empty password hash")
// ErrNoSuchUser means no account carries that address.
var ErrNoSuchUser = errors.New("no account with that email")
-// FindEmailFold returns the stored address matching email case-insensitively, or
-// sql.ErrNoRows. Addresses are stored and matched exactly everywhere else — including at
-// login — so this exists only to turn "no account found" into a useful message for an
-// operator who typed the wrong case while recovering an account. It must not become a way
-// to authenticate, which is why it returns the stored spelling rather than the row.
-func (s *UserStore) FindEmailFold(email string) (string, error) {
- var stored string
- err := s.db.QueryRow(
- `SELECT email FROM users WHERE email = ? COLLATE NOCASE`, email,
- ).Scan(&stored)
- return stored, err
-}
-
// ResetPassword is the operator's way in, for the account whose password is lost. Unlike
// ChangePassword there is no old hash to verify against — the whole point is that nobody
// knows it — so this is keyed on email and guarded only by having a shell on the server.
@@ -220,25 +270,38 @@ func (s *UserStore) FindEmailFold(email string) (string, error) {
// more: an operator resetting a password may be doing it because someone else got in, and
// a new password is worthless while the intruder's refresh token still mints access
// tokens for the rest of its 30 days.
-func (s *UserStore) ResetPassword(email, newHash string) error {
+//
+// It returns the address as stored, because the one passed in may differ from it in letter
+// case and the operator should see which account was actually changed.
+func (s *UserStore) ResetPassword(email, newHash string) (string, error) {
if newHash == "" {
- return ErrEmptyHash
+ return "", ErrEmptyHash
+ }
+ u, spellings, err := s.matchEmail(email)
+ if errors.Is(err, sql.ErrNoRows) {
+ return "", ErrNoSuchUser
+ }
+ if errors.Is(err, ErrAmbiguousEmail) {
+ return "", fmt.Errorf("%w: %s", ErrAmbiguousEmail, strings.Join(spellings, ", "))
+ }
+ if err != nil {
+ return "", err
}
res, err := s.db.Exec(
`UPDATE users SET password_hash = ?, token_version = token_version + 1,
updated_at = CURRENT_TIMESTAMP
- WHERE email = ?`, newHash, email)
+ WHERE id = ?`, newHash, u.ID)
if err != nil {
- return err
+ return "", err
}
n, err := res.RowsAffected()
if err != nil {
- return err
+ return "", err
}
if n == 0 {
- return ErrNoSuchUser
+ return "", ErrNoSuchUser
}
- return nil
+ return u.Email, nil
}
// Delete removes the user; child rows go via ON DELETE CASCADE (foreign_keys=on).
@@ -246,3 +309,50 @@ func (s *UserStore) Delete(uid int64) error {
_, err := s.db.Exec(`DELETE FROM users WHERE id = ?`, uid)
return err
}
+
+// ErrInexactEmail means an address matches an account only when letter case is ignored.
+var ErrInexactEmail = errors.New("address matches only with different letter case")
+
+// GetByExactEmail is the lookup for destructive operator commands, which must never
+// resolve an address by folding case. It layers one check on matchEmail so NOCASE
+// semantics stay in one place. When no account is spelled exactly as given but some match
+// ignoring case, it returns ErrInexactEmail with every stored spelling.
+func (s *UserStore) GetByExactEmail(email string) (models.User, []string, error) {
+ u, spellings, err := s.matchEmail(email)
+ switch {
+ case errors.Is(err, sql.ErrNoRows):
+ return models.User{}, nil, ErrNoSuchUser
+ case errors.Is(err, ErrAmbiguousEmail):
+ return models.User{}, spellings, ErrInexactEmail
+ case err != nil:
+ return models.User{}, nil, err
+ case u.Email != email:
+ return models.User{}, []string{u.Email}, ErrInexactEmail
+ }
+ return u, nil, nil
+}
+
+// AccountData is how much an account holds, for showing an operator what a delete takes.
+type AccountData struct {
+ Workouts, Sets, FoodLogs, WeightLogs, Programs, SavedFoods, ActiveSessions int
+}
+
+// CountData counts the rows Delete will cascade through for one account. It mirrors the
+// user-owned tables in the schema; a test pins that mirror against the foreign keys.
+// user_settings is not counted: every account has exactly one.
+func (s *UserStore) CountData(uid int64) (AccountData, error) {
+ var d AccountData
+ err := s.db.QueryRow(`SELECT
+ (SELECT COUNT(*) FROM workouts WHERE user_id = ?),
+ (SELECT COUNT(*) FROM sets st
+ JOIN workout_exercises we ON we.id = st.workout_exercise_id
+ JOIN workouts w ON w.id = we.workout_id WHERE w.user_id = ?),
+ (SELECT COUNT(*) FROM food_logs WHERE user_id = ?),
+ (SELECT COUNT(*) FROM weight_logs WHERE user_id = ?),
+ (SELECT COUNT(*) FROM programs WHERE user_id = ?),
+ (SELECT COUNT(*) FROM saved_foods WHERE user_id = ?),
+ (SELECT COUNT(*) FROM active_sessions WHERE user_id = ?)`,
+ uid, uid, uid, uid, uid, uid, uid).
+ Scan(&d.Workouts, &d.Sets, &d.FoodLogs, &d.WeightLogs, &d.Programs, &d.SavedFoods, &d.ActiveSessions)
+ return d, err
+}
diff --git a/backend/stores/user_test.go b/backend/stores/user_test.go
new file mode 100644
index 0000000..51ab45e
--- /dev/null
+++ b/backend/stores/user_test.go
@@ -0,0 +1,181 @@
+package stores
+
+import (
+ "database/sql"
+ "errors"
+ "reflect"
+ "testing"
+)
+
+func mustExec(t *testing.T, conn *sql.DB, q string, args ...any) int64 {
+ t.Helper()
+ res, err := conn.Exec(q, args...)
+ if err != nil {
+ t.Fatalf("exec %q: %v", q, err)
+ }
+ id, _ := res.LastInsertId()
+ return id
+}
+
+// seedAccount inserts a user with n workouts (each with one exercise and two sets), n food
+// logs, n weight logs, n saved foods, one active session and one program with a day,
+// an exercise and a set. Case variants require the nocase index to be absent.
+func seedAccount(t *testing.T, conn *sql.DB, email string, n int) int64 {
+ t.Helper()
+ uid := mustExec(t, conn, `INSERT INTO users (email, password_hash) VALUES (?, 'x')`, email)
+ mustExec(t, conn, `INSERT INTO user_settings (user_id) VALUES (?)`, uid)
+ mustExec(t, conn, `INSERT OR IGNORE INTO exercises (name) VALUES ('Squat')`)
+ var ex int64
+ if err := conn.QueryRow(`SELECT id FROM exercises WHERE name = 'Squat'`).Scan(&ex); err != nil {
+ t.Fatalf("exercise: %v", err)
+ }
+ for i := 0; i < n; i++ {
+ w := mustExec(t, conn, `INSERT INTO workouts (user_id, name) VALUES (?, 'w')`, uid)
+ we := mustExec(t, conn, `INSERT INTO workout_exercises (workout_id, exercise_id) VALUES (?, ?)`, w, ex)
+ mustExec(t, conn, `INSERT INTO sets (workout_exercise_id) VALUES (?)`, we)
+ mustExec(t, conn, `INSERT INTO sets (workout_exercise_id) VALUES (?)`, we)
+ mustExec(t, conn, `INSERT INTO food_logs (user_id, name, logged_on) VALUES (?, 'f', '2026-01-01')`, uid)
+ mustExec(t, conn, `INSERT INTO weight_logs (user_id, weight, logged_on) VALUES (?, 180, '2026-01-01')`, uid)
+ mustExec(t, conn, `INSERT INTO saved_foods (user_id, name, brand) VALUES (?, ?, 'b')`, uid, "food"+string(rune('a'+i)))
+ }
+ mustExec(t, conn, `INSERT INTO active_sessions (user_id, data) VALUES (?, '{}')`, uid)
+ p := mustExec(t, conn, `INSERT INTO programs (user_id, name) VALUES (?, 'p')`, uid)
+ d := mustExec(t, conn, `INSERT INTO program_days (program_id) VALUES (?)`, p)
+ pe := mustExec(t, conn, `INSERT INTO program_exercises (program_id, exercise_id, program_day_id) VALUES (?, ?, ?)`, p, ex, d)
+ mustExec(t, conn, `INSERT INTO program_sets (program_exercise_id) VALUES (?)`, pe)
+ return uid
+}
+
+func dropNocaseIndex(t *testing.T, conn *sql.DB) {
+ t.Helper()
+ mustExec(t, conn, `DROP INDEX IF EXISTS idx_users_email_nocase`)
+}
+
+func TestGetByExactEmail(t *testing.T) {
+ conn := testDB(t)
+ dropNocaseIndex(t, conn)
+ s := NewUserStore(conn)
+
+ a := seedAccount(t, conn, "[email protected]", 0)
+ b := seedAccount(t, conn, "[email protected]", 0)
+ solo := seedAccount(t, conn, "[email protected]", 0)
+ mustExec(t, conn, `INSERT INTO users (email, password_hash) VALUES ('[email protected]', 'x'), ('[email protected]', 'x')`)
+
+ t.Run("exact spelling among variants", func(t *testing.T) {
+ u, sp, err := s.GetByExactEmail("[email protected]")
+ if err != nil || sp != nil || u.ID != b {
+ t.Fatalf("got id %d, %v, %v; want %d", u.ID, sp, err, b)
+ }
+ u, _, err = s.GetByExactEmail("[email protected]")
+ if err != nil || u.ID != a {
+ t.Fatalf("got id %d, %v; want %d", u.ID, err, a)
+ }
+ })
+ t.Run("single variant is not resolved", func(t *testing.T) {
+ u, sp, err := s.GetByExactEmail("[email protected]")
+ if !errors.Is(err, ErrInexactEmail) || u.ID != 0 || !reflect.DeepEqual(sp, []string{"[email protected]"}) {
+ t.Fatalf("got %d, %v, %v; want ErrInexactEmail with [email protected]", u.ID, sp, err)
+ }
+ _ = solo
+ })
+ t.Run("several variants, none exact", func(t *testing.T) {
+ _, sp, err := s.GetByExactEmail("[email protected]")
+ if !errors.Is(err, ErrInexactEmail) || !reflect.DeepEqual(sp, []string{"[email protected]", "[email protected]"}) {
+ t.Fatalf("got %v, %v", sp, err)
+ }
+ })
+ t.Run("absent", func(t *testing.T) {
+ _, sp, err := s.GetByExactEmail("[email protected]")
+ if !errors.Is(err, ErrNoSuchUser) || sp != nil {
+ t.Fatalf("got %v, %v", sp, err)
+ }
+ })
+}
+
+func TestCountDataCountsOnlyThatAccount(t *testing.T) {
+ conn := testDB(t)
+ s := NewUserStore(conn)
+ a := seedAccount(t, conn, "[email protected]", 3)
+ b := seedAccount(t, conn, "[email protected]", 1)
+
+ got, err := s.CountData(a)
+ if err != nil {
+ t.Fatal(err)
+ }
+ want := AccountData{Workouts: 3, Sets: 6, FoodLogs: 3, WeightLogs: 3, Programs: 1, SavedFoods: 3, ActiveSessions: 1}
+ if got != want {
+ t.Errorf("a: got %+v, want %+v", got, want)
+ }
+ got, _ = s.CountData(b)
+ want = AccountData{Workouts: 1, Sets: 2, FoodLogs: 1, WeightLogs: 1, Programs: 1, SavedFoods: 1, ActiveSessions: 1}
+ if got != want {
+ t.Errorf("b: got %+v, want %+v", got, want)
+ }
+}
+
+// CountData lists tables by hand. This fails when a table gains a foreign key to users
+// that the summary does not know about.
+func TestCountDataCoversEveryUserOwnedTable(t *testing.T) {
+ conn := testDB(t)
+ rows, err := conn.Query(`SELECT m.name FROM sqlite_master m JOIN pragma_foreign_key_list(m.name) f
+ WHERE m.type = 'table' AND f."table" = 'users' ORDER BY m.name`)
+ if err != nil {
+ t.Fatal(err)
+ }
+ var got []string
+ for rows.Next() {
+ var n string
+ if err := rows.Scan(&n); err != nil {
+ t.Fatal(err)
+ }
+ got = append(got, n)
+ }
+ rows.Close()
+ want := []string{"active_sessions", "food_logs", "programs", "saved_foods", "user_settings", "weight_logs", "workouts"}
+ if !reflect.DeepEqual(got, want) {
+ t.Fatalf("user-owned tables = %v, want %v; add any new table to UserStore.CountData", got, want)
+ }
+}
+
+func TestDeleteCascadesEveryChildTable(t *testing.T) {
+ conn := testDB(t)
+ s := NewUserStore(conn)
+ a := seedAccount(t, conn, "[email protected]", 2)
+ b := seedAccount(t, conn, "[email protected]", 2)
+ before, _ := s.CountData(b)
+
+ if err := s.Delete(a); err != nil {
+ t.Fatal(err)
+ }
+
+ owned := map[string]string{
+ "users": `SELECT COUNT(*) FROM users WHERE id = ?`,
+ "user_settings": `SELECT COUNT(*) FROM user_settings WHERE user_id = ?`,
+ "active_sessions": `SELECT COUNT(*) FROM active_sessions WHERE user_id = ?`,
+ "workouts": `SELECT COUNT(*) FROM workouts WHERE user_id = ?`,
+ "food_logs": `SELECT COUNT(*) FROM food_logs WHERE user_id = ?`,
+ "weight_logs": `SELECT COUNT(*) FROM weight_logs WHERE user_id = ?`,
+ "saved_foods": `SELECT COUNT(*) FROM saved_foods WHERE user_id = ?`,
+ "programs": `SELECT COUNT(*) FROM programs WHERE user_id = ?`,
+ "workout_exercises": `SELECT COUNT(*) FROM workout_exercises WHERE workout_id IN (SELECT id FROM workouts WHERE user_id = ?)`,
+ }
+ for name, q := range owned {
+ var n int
+ if err := conn.QueryRow(q, a).Scan(&n); err != nil || n != 0 {
+ t.Errorf("%s: %d rows left for the deleted account (%v)", name, n, err)
+ }
+ }
+ // Grandchildren have no user_id; with a's rows gone only b's must remain.
+ for table, want := range map[string]int{
+ "workout_exercises": 2, "sets": 4, "program_days": 1, "program_exercises": 1, "program_sets": 1, "exercises": 1,
+ } {
+ var n int
+ if err := conn.QueryRow(`SELECT COUNT(*) FROM ` + table).Scan(&n); err != nil || n != want {
+ t.Errorf("%s: %d rows, want %d (%v)", table, n, want, err)
+ }
+ }
+ after, _ := s.CountData(b)
+ if after != before {
+ t.Errorf("other account changed: %+v -> %+v", before, after)
+ }
+}
diff --git a/docs/API_CHANGES.md b/docs/API_CHANGES.md
index d3c28d8..8cb032f 100644
--- a/docs/API_CHANGES.md
+++ b/docs/API_CHANGES.md
@@ -14,6 +14,14 @@ catches what the author knew and forgot; it cannot catch what the author never n
If your PR changes a status code, narrows an accepted value, or renames a response field,
add the entry in that PR.
+## `POST /api/v1/auth/register` — an address differing only in letter case is a duplicate
+
+An address that differs from an existing account only in letter case (`[email protected]`
+beside `[email protected]`) now answers `409` `That email is already registered.`. It used
+to answer `201` and create a second account.
+
+Only ASCII letters fold. Stored spellings are never rewritten.
+
## `POST /api/v1/food`, `PUT /api/v1/food/:id` — `servings` is capped at 100
Anything above 100 is rejected with `422`. There was no ceiling before.
@@ -189,6 +197,10 @@ with the entire history reads as data loss in reverse — so the rejection is de
Not entries — nothing to fix on a caller's side — but worth a line in the notes because
somebody will see the change.
+- **Sign-in matches the address case-insensitively**, returning the spelling stored at
+ registration. An install that already holds case-variant accounts keeps both: each still
+ signs in with its exact spelling, and the boot log names them;
+ `lyftr-api delete-account <exact address>` removes the one you do not want.
- **Every error message was rewritten into a sentence.** No status code, route, field name
or field type moved. A caller regex-matching error *strings* will break, but error
wording is not part of the contract and never was.
diff --git a/site/src/content/docs/configuration.md b/site/src/content/docs/configuration.md
index 2bc6a93..d6c3a8c 100644
--- a/site/src/content/docs/configuration.md
+++ b/site/src/content/docs/configuration.md
@@ -147,6 +147,31 @@ out, since nothing would let you register the replacement.
If the instance will not start at all, restoring `lyftr.db` from a backup predating the password
change also works, at the cost of everything logged since — see [Backups](/backups/).
+## Deleting an account from the server
+
+An account can be removed from the server's shell, for the case where nobody can (or should) sign in
+to it:
+
+```bash
+docker compose exec backend ./lyftr-api delete-account [email protected]
+```
+
+It prints what will be deleted — workouts, sets, food and weight entries, routines, saved foods —
+and asks you to type the address again. Anything else aborts with nothing deleted. The address must
+match letter case exactly; if it does not, the command lists the spellings it found and deletes
+nothing.
+
+If an upgrade's boot log says some accounts differ only in letter case, this is how to remove the one
+you do not want. The case-insensitive index is created on the next start.
+
+If it is the only account, the command warns first: under `REGISTRATION=first-user` whoever registers
+next becomes the owner, and under `REGISTRATION=closed` nobody can sign in or register. Take a backup
+before you run it — see [Backups](/backups/). A device still signed in to the deleted account keeps its
+access token until that expires (up to an hour): reads come back empty and writes fail, and it is signed
+out when it next refreshes.
+
+Piping the exact address also works, with `-T`: `echo [email protected] | docker compose exec -T backend ./lyftr-api delete-account [email protected]`.
+
## The demo account
Every version before this one seeded `[email protected]` with a password published in this