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.

Let a signed-in user change their email address (#196)

Carterbb17929b0049
diff --git a/backend/controllers/auth.go b/backend/controllers/auth.go
index e3e9a52..e555bb9 100644
--- a/backend/controllers/auth.go
+++ b/backend/controllers/auth.go
@@ -14,6 +14,14 @@ import (
var validate = utils.NewValidator()
+// EmailTakenMessage is the 409 for an address another account holds, shared by
+// registration and email change.
+const EmailTakenMessage = "That email is already registered."
+
+// passwordChangedMessage is the 409 when the stored hash moved under a request that had
+// already verified the old one.
+const passwordChangedMessage = "Your password was changed elsewhere. Please try again."
+
// RegistrationClosedMessage is what a rejected signup sees. One constant so the two
// ways of being closed (REGISTRATION=closed, and first-user with the slot taken) are
// indistinguishable to a caller — and so the handler and its tests cannot drift.
@@ -86,7 +94,7 @@ func (h *Handler) Register(c *gin.Context) {
return
}
if errors.Is(err, stores.ErrEmailTaken) || utils.IsUniqueViolation(err) {
- utils.Conflict(c, "That email is already registered.")
+ utils.Conflict(c, EmailTakenMessage)
return
}
if utils.DBError(c, err) {
@@ -152,6 +160,27 @@ func (h *Handler) Login(c *gin.Context) {
utils.OK(c, models.AuthResponse{Token: access, RefreshToken: refresh, User: user})
}
+// reauthenticate loads the caller and checks their current password, writing the 401
+// itself on failure.
+func (h *Handler) reauthenticate(c *gin.Context, password string) (models.User, bool) {
+ // Looked up by ID, not by the email in the token: an address that changed since the
+ // token was minted would otherwise resolve to the wrong row or to none at all.
+ user, err := h.s.User.GetByID(middleware.UserID(c))
+ if err == sql.ErrNoRows {
+ utils.Unauthorized(c, "That account no longer exists.")
+ return models.User{}, false
+ }
+ if utils.DBError(c, err) {
+ return models.User{}, false
+ }
+
+ if !utils.CheckPassword(password, user.Password) {
+ utils.Unauthorized(c, "Your current password is incorrect.")
+ return models.User{}, false
+ }
+ return user, true
+}
+
// ChangePassword sets a new password for the signed-in caller and ends every other
// session. The device that made the change gets a fresh token pair in the response, so
// it stays signed in while the rest fall off as their access tokens lapse.
@@ -168,19 +197,8 @@ func (h *Handler) ChangePassword(c *gin.Context) {
return
}
- // Looked up by ID, not by the email in the token: an address that changed since the
- // token was minted would otherwise resolve to the wrong row or to none at all.
- user, err := h.s.User.GetByID(uid)
- if err == sql.ErrNoRows {
- utils.Unauthorized(c, "That account no longer exists.")
- return
- }
- if utils.DBError(c, err) {
- return
- }
-
- if !utils.CheckPassword(req.CurrentPassword, user.Password) {
- utils.Unauthorized(c, "Your current password is incorrect.")
+ user, ok := h.reauthenticate(c, req.CurrentPassword)
+ if !ok {
return
}
// Rejected before hashing. Allowing it would burn a bcrypt round to no effect and,
@@ -204,7 +222,7 @@ func (h *Handler) ChangePassword(c *gin.Context) {
version, err := h.s.User.ChangePassword(uid, user.Password, newHash)
if errors.Is(err, stores.ErrPasswordChanged) {
- utils.Conflict(c, "Your password was changed elsewhere. Please try again.")
+ utils.Conflict(c, passwordChangedMessage)
return
}
if utils.DBError(c, err) {
@@ -222,6 +240,62 @@ func (h *Handler) ChangePassword(c *gin.Context) {
utils.OK(c, gin.H{"token": access, "refresh_token": refresh})
}
+// ChangeEmail moves the signed-in caller to a new address and ends every other session,
+// as ChangePassword does: with no confirmation mail to the old address, revoking the other
+// sessions is the only containment if someone else's session made the change. The device
+// that made it gets a fresh token pair in the response and stays signed in. The password
+// is checked before the conflict lookup so a wrong password can never learn whether an
+// address is registered. Re-submitting the current spelling is a no-op that ends nothing,
+// and changing only its letter case is allowed and ends nothing either: the sign-in identity
+// is the same, so there is nothing to contain.
+func (h *Handler) ChangeEmail(c *gin.Context) {
+ var req models.ChangeEmailRequest
+ if err := c.ShouldBindJSON(&req); err != nil {
+ utils.BadRequest(c, utils.BindMessage(err))
+ return
+ }
+ if err := validate.Struct(req); err != nil {
+ utils.ValidationError(c, err)
+ return
+ }
+
+ user, ok := h.reauthenticate(c, req.CurrentPassword)
+ if !ok {
+ return
+ }
+ if req.Email == user.Email {
+ h.respondWithSession(c, user)
+ return
+ }
+
+ updated, err := h.s.User.ChangeEmail(user.ID, user.Password, req.Email)
+ if errors.Is(err, stores.ErrEmailTaken) || utils.IsUniqueViolation(err) {
+ utils.Conflict(c, EmailTakenMessage)
+ return
+ }
+ if errors.Is(err, stores.ErrPasswordChanged) {
+ utils.Conflict(c, passwordChangedMessage)
+ return
+ }
+ if utils.DBError(c, err) {
+ return
+ }
+ h.respondWithSession(c, updated)
+}
+
+// respondWithSession answers with the login-shaped body: a token pair minted at the user's
+// current token version, plus the user. The email change already took effect by the time
+// this runs, so a minting failure says what happened rather than reporting a failure that
+// would send the user off to retry.
+func (h *Handler) respondWithSession(c *gin.Context, user models.User) {
+ access, refresh, err := utils.GenerateTokenPair(user.ID, user.Email, user.TokenVersion)
+ if err != nil {
+ utils.Unauthorized(c, "Your email changed. Please sign in again.")
+ return
+ }
+ utils.OK(c, models.AuthResponse{Token: access, RefreshToken: refresh, User: user})
+}
+
func (h *Handler) RefreshToken(c *gin.Context) {
var req models.RefreshRequest
if err := c.ShouldBindJSON(&req); err != nil {
diff --git a/backend/controllers/email_test.go b/backend/controllers/email_test.go
new file mode 100644
index 0000000..0527599
--- /dev/null
+++ b/backend/controllers/email_test.go
@@ -0,0 +1,251 @@
+package controllers
+
+import (
+ "net/http"
+ "strings"
+ "testing"
+
+ "github.com/Cawlumm/lyftr-backend/db"
+)
+
+func changeEmail(t *testing.T, uid int64, email, current string) (int, map[string]any) {
+ t.Helper()
+ body := map[string]string{"email": email}
+ if current != "" {
+ body["current_password"] = current
+ }
+ c, w := newContext(uid, "PUT", "/api/v1/me/email", body)
+ th.ChangeEmail(c)
+ return w.Code, decodeResponse(t, w)
+}
+
+func storedEmail(t *testing.T, uid int64) string {
+ t.Helper()
+ var e string
+ if err := db.DB.QueryRow(`SELECT email FROM users WHERE id = ?`, uid).Scan(&e); err != nil {
+ t.Fatalf("read email: %v", err)
+ }
+ return e
+}
+
+func storedUpdatedAt(t *testing.T, uid int64) string {
+ t.Helper()
+ var s string
+ if err := db.DB.QueryRow(`SELECT CAST(updated_at AS TEXT) FROM users WHERE id = ?`, uid).Scan(&s); err != nil {
+ t.Fatalf("read updated_at: %v", err)
+ }
+ return s
+}
+
+func errorOf(body map[string]any) string {
+ s, _ := body["error"].(string)
+ return s
+}
+
+func TestChangeEmailUpdatesAddressAndSignsOutOtherDevices(t *testing.T) {
+ setupTestDB(t)
+ uid, oldRefresh := registerAndLogin(t, "[email protected]", "password123")
+ versionBefore := tokenVersion(t, uid)
+
+ code, body := changeEmail(t, uid, "[email protected]", "password123")
+ if code != http.StatusOK {
+ t.Fatalf("status = %d, want 200 (%v)", code, body)
+ }
+ data, _ := body["data"].(map[string]any)
+ user, _ := data["user"].(map[string]any)
+ if user["email"] != "[email protected]" {
+ t.Errorf("returned email = %v", user["email"])
+ }
+ newRefresh, _ := data["refresh_token"].(string)
+ if tok, _ := data["token"].(string); tok == "" || newRefresh == "" {
+ t.Errorf("response carries no token pair for this device: %v", data)
+ }
+ if got := storedEmail(t, uid); got != "[email protected]" {
+ t.Errorf("stored email = %q", got)
+ }
+ if v := tokenVersion(t, uid); v != versionBefore+1 {
+ t.Errorf("token_version = %d, want %d", v, versionBefore+1)
+ }
+ if code := refreshWith(t, oldRefresh); code != http.StatusUnauthorized {
+ t.Errorf("refresh with the pre-change token = %d, want 401", code)
+ }
+ if code := refreshWith(t, newRefresh); code != http.StatusOK {
+ t.Errorf("refresh with the token this device was handed = %d, want 200", code)
+ }
+ if code, _ := loginRequest(t, "[email protected]", "password123"); code != http.StatusOK {
+ t.Errorf("login with the new address = %d, want 200", code)
+ }
+ if code, _ := loginRequest(t, "[email protected]", "password123"); code != http.StatusUnauthorized {
+ t.Errorf("login with the old address = %d, want 401", code)
+ }
+}
+
+func TestChangeEmailRejectsWrongCurrentPassword(t *testing.T) {
+ setupTestDB(t)
+ uid, _ := registerAndLogin(t, "[email protected]", "password123")
+
+ code, body := changeEmail(t, uid, "[email protected]", "wrongpassword")
+ if code != http.StatusUnauthorized || errorOf(body) != "Your current password is incorrect." {
+ t.Fatalf("got %d %v", code, body)
+ }
+ if got := storedEmail(t, uid); got != "[email protected]" {
+ t.Errorf("stored email = %q, want unchanged", got)
+ }
+}
+
+func TestChangeEmailWrongPasswordDoesNotRevealTakenAddress(t *testing.T) {
+ setupTestDB(t)
+ registerAndLogin(t, "[email protected]", "password123")
+ uid, _ := registerAndLogin(t, "[email protected]", "password123")
+
+ code, body := changeEmail(t, uid, "[email protected]", "wrongpassword")
+ if code != http.StatusUnauthorized {
+ t.Fatalf("got %d %v, want 401", code, body)
+ }
+}
+
+func TestChangeEmailRejectsAddressHeldInAnotherCase(t *testing.T) {
+ setupTestDB(t)
+ registerAndLogin(t, "[email protected]", "password123")
+ uid, _ := registerAndLogin(t, "[email protected]", "password123")
+
+ code, body := changeEmail(t, uid, "[email protected]", "password123")
+ if code != http.StatusConflict || errorOf(body) != "That email is already registered." {
+ t.Fatalf("got %d %v", code, body)
+ }
+ if got := storedEmail(t, uid); got != "[email protected]" {
+ t.Errorf("stored email = %q, want unchanged", got)
+ }
+}
+
+func TestChangeEmailOnACollidingInstall(t *testing.T) {
+ setupTestDB(t)
+ a, b := seedCollidingAccounts(t, "[email protected]", "password123", "[email protected]", "password123")
+
+ code, body := changeEmail(t, a, "[email protected]", "password123")
+ if code != http.StatusConflict {
+ t.Fatalf("got %d %v, want 409", code, body)
+ }
+ if storedEmail(t, a) != "[email protected]" || storedEmail(t, b) != "[email protected]" {
+ t.Error("a stored email changed")
+ }
+
+ if code, body := changeEmail(t, a, "[email protected]", "password123"); code != http.StatusOK {
+ t.Fatalf("move to a fresh address = %d %v, want 200", code, body)
+ }
+}
+
+func TestChangeEmailAllowsChangingTheCaseOfOwnAddress(t *testing.T) {
+ setupTestDB(t)
+ uid, oldRefresh := registerAndLogin(t, "[email protected]", "password123")
+ versionBefore := tokenVersion(t, uid)
+
+ code, body := changeEmail(t, uid, "[email protected]", "password123")
+ if code != http.StatusOK {
+ t.Fatalf("got %d %v, want 200", code, body)
+ }
+ if got := storedEmail(t, uid); got != "[email protected]" {
+ t.Errorf("stored email = %q", got)
+ }
+ // Sign-in ignores case, so the identity is unchanged and no other session is ended.
+ if v := tokenVersion(t, uid); v != versionBefore {
+ t.Errorf("token_version = %d, want %d", v, versionBefore)
+ }
+ if code := refreshWith(t, oldRefresh); code != http.StatusOK {
+ t.Errorf("refresh with the pre-change token = %d, want 200", code)
+ }
+
+ // A change that is more than case still ends them, even from the cased spelling.
+ if code, body := changeEmail(t, uid, "[email protected]", "password123"); code != http.StatusOK {
+ t.Fatalf("second change got %d %v", code, body)
+ }
+ if v := tokenVersion(t, uid); v != versionBefore+1 {
+ t.Errorf("token_version after a real change = %d, want %d", v, versionBefore+1)
+ }
+ if code := refreshWith(t, oldRefresh); code != http.StatusUnauthorized {
+ t.Errorf("refresh with the original token = %d, want 401", code)
+ }
+}
+
+func TestChangeEmailSameAddressIsANoOp(t *testing.T) {
+ setupTestDB(t)
+ uid, oldRefresh := registerAndLogin(t, "[email protected]", "password123")
+ before := storedUpdatedAt(t, uid)
+ versionBefore := tokenVersion(t, uid)
+
+ code, body := changeEmail(t, uid, "[email protected]", "password123")
+ if code != http.StatusOK {
+ t.Fatalf("got %d %v, want 200", code, body)
+ }
+ // Nothing changed, so nobody is signed out: the version stays and older sessions live.
+ if v := tokenVersion(t, uid); v != versionBefore {
+ t.Errorf("token_version = %d, want %d", v, versionBefore)
+ }
+ if code := refreshWith(t, oldRefresh); code != http.StatusOK {
+ t.Errorf("refresh with the pre-request token = %d, want 200", code)
+ }
+ if got := storedEmail(t, uid); got != "[email protected]" {
+ t.Errorf("stored email = %q", got)
+ }
+ if after := storedUpdatedAt(t, uid); after != before {
+ t.Errorf("updated_at moved from %q to %q", before, after)
+ }
+}
+
+func TestChangeEmailStoresSpellingAsTyped(t *testing.T) {
+ setupTestDB(t)
+ uid, _ := registerAndLogin(t, "[email protected]", "password123")
+
+ const typed = "[email protected]"
+ code, body := changeEmail(t, uid, typed, "password123")
+ if code != http.StatusOK {
+ t.Fatalf("got %d %v", code, body)
+ }
+ if got := storedEmail(t, uid); got != typed {
+ t.Errorf("stored email = %q, want %q", got, typed)
+ }
+ data, _ := body["data"].(map[string]any)
+ user, _ := data["user"].(map[string]any)
+ if user["email"] != typed {
+ t.Errorf("returned email = %v, want %q", user["email"], typed)
+ }
+}
+
+func TestChangeEmailRejectsInvalidInput(t *testing.T) {
+ setupTestDB(t)
+ uid, _ := registerAndLogin(t, "[email protected]", "password123")
+
+ cases := []struct {
+ name, email, password, want string
+ }{
+ {"empty", "", "password123", "Email is a required field."},
+ {"malformed", "not-an-email", "password123", "Email must be a valid email address."},
+ {"padded", " [email protected] ", "password123", "Email must be a valid email address."},
+ {"no password", "[email protected]", "", "Current password is a required field."},
+ }
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ code, body := changeEmail(t, uid, tc.email, tc.password)
+ msg := errorOf(body)
+ if code != http.StatusUnprocessableEntity || !strings.Contains(msg, tc.want) {
+ t.Fatalf("got %d %q, want 422 containing %q", code, msg, tc.want)
+ }
+ for _, leak := range []string{"Key:", "tag", "ChangeEmailRequest"} {
+ if strings.Contains(msg, leak) {
+ t.Errorf("message %q leaks validator text %q", msg, leak)
+ }
+ }
+ if got := storedEmail(t, uid); got != "[email protected]" {
+ t.Errorf("stored email = %q, want unchanged", got)
+ }
+ })
+ }
+}
+
+func TestChangeEmailForADeletedAccount(t *testing.T) {
+ setupTestDB(t)
+ code, body := changeEmail(t, 9999, "[email protected]", "password123")
+ if code != http.StatusUnauthorized || errorOf(body) != "That account no longer exists." {
+ t.Fatalf("got %d %v", code, body)
+ }
+}
diff --git a/backend/models/models.go b/backend/models/models.go
index 1bc1cc2..c5986fc 100644
--- a/backend/models/models.go
+++ b/backend/models/models.go
@@ -257,6 +257,15 @@ type ChangePasswordRequest struct {
NewPassword string `json:"new_password" validate:"required,min=8"`
}
+// ChangeEmailRequest re-authenticates the caller for the same reason as
+// ChangePasswordRequest: a hijacked access token alone must not be able to take the
+// account. The email tag must stay identical to RegisterRequest's, so an address that
+// cannot be registered cannot be moved to either.
+type ChangeEmailRequest struct {
+ Email string `json:"email" validate:"required,email"`
+ CurrentPassword string `json:"current_password" validate:"required"`
+}
+
// MaxWorkoutSets bounds the TOTAL number of sets across every exercise in a
// CreateWorkoutRequest (sum of len(Exercises[i].Sets), not each list's own max=500
// below independently) — enforced by the struct-level validation registered in
diff --git a/backend/routes/routes.go b/backend/routes/routes.go
index c9b7bad..899ec43 100644
--- a/backend/routes/routes.go
+++ b/backend/routes/routes.go
@@ -40,6 +40,7 @@ func Setup(r *gin.Engine, h *controllers.Handler) {
protected.GET("settings", h.GetSettings)
protected.PUT("settings", h.UpdateSettings)
protected.PUT("me/password", h.ChangePassword)
+ protected.PUT("me/email", h.ChangeEmail)
protected.DELETE("me", h.DeleteAccount)
// Workouts
diff --git a/backend/routes/routes_test.go b/backend/routes/routes_test.go
new file mode 100644
index 0000000..6448a02
--- /dev/null
+++ b/backend/routes/routes_test.go
@@ -0,0 +1,40 @@
+package routes
+
+import (
+ "encoding/json"
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "testing"
+
+ "github.com/Cawlumm/lyftr-backend/config"
+ "github.com/Cawlumm/lyftr-backend/controllers"
+ "github.com/Cawlumm/lyftr-backend/stores"
+ "github.com/gin-gonic/gin"
+)
+
+func TestChangeEmailRequiresAuth(t *testing.T) {
+ prev := config.C
+ config.C = &config.Config{Env: "production", CORSOrigin: "http://a.com", JWTSecret: "test-secret-test-secret-test-secret-1"}
+ t.Cleanup(func() { config.C = prev })
+
+ gin.SetMode(gin.TestMode)
+ r := gin.New()
+ Setup(r, controllers.NewHandler(stores.New(nil)))
+
+ req := httptest.NewRequest(http.MethodPut, "/api/v1/me/email", strings.NewReader(`{}`))
+ req.Header.Set("Content-Type", "application/json")
+ w := httptest.NewRecorder()
+ r.ServeHTTP(w, req)
+
+ if w.Code != http.StatusUnauthorized {
+ t.Fatalf("status = %d, want 401", w.Code)
+ }
+ var body map[string]any
+ if err := json.Unmarshal(w.Body.Bytes(), &body); err != nil {
+ t.Fatal(err)
+ }
+ if body["error"] != "You need to sign in to do that." {
+ t.Errorf("error = %v", body["error"])
+ }
+}
diff --git a/backend/stores/user.go b/backend/stores/user.go
index c30658e..6e8cb35 100644
--- a/backend/stores/user.go
+++ b/backend/stores/user.go
@@ -233,12 +233,7 @@ 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):
+ if err := emailTakenTx(tx, email, 0); err != nil {
return 0, err
}
res, err := tx.Exec(`INSERT INTO users (email, password_hash) VALUES (?, ?)`, email, hash)
@@ -252,6 +247,57 @@ func createUserTx(tx *sql.Tx, email, hash string) (int64, error) {
return uid, nil
}
+// emailTakenTx returns ErrEmailTaken when an account other than exceptID holds the
+// address, ignoring letter case.
+// The unique index cannot exist on an install that already holds case-variant accounts, so check here too.
+func emailTakenTx(tx *sql.Tx, email string, exceptID int64) error {
+ var taken int
+ switch err := tx.QueryRow(`SELECT 1 FROM users WHERE email = ? COLLATE NOCASE AND id != ? LIMIT 1`, email, exceptID).Scan(&taken); {
+ case err == nil:
+ return ErrEmailTaken
+ case !errors.Is(err, sql.ErrNoRows):
+ return err
+ }
+ return nil
+}
+
+// ChangeEmail moves the account to a new address and returns the updated user. The
+// check and the write share one transaction because the case-insensitive unique index
+// is absent on installs that hold case-variant accounts. The UPDATE is conditional on
+// the hash the handler verified, as in ChangePassword. It bumps token_version, as
+// ChangePassword does, so every other session ends; the returned user carries the version
+// for the handler to mint this device's replacement tokens at.
+//
+// A change of letter case alone bumps nothing. Sign-in is case-insensitive, so the identity
+// did not change and there is nothing to contain; ending a phone's session over a
+// capitalisation fix would be pure cost. The comparison is SQLite's NOCASE, the same rule
+// that decides "same address" everywhere else, so no Go code folds case.
+func (s *UserStore) ChangeEmail(uid int64, verifiedHash, email string) (models.User, error) {
+ var u models.User
+ _, err := inTx(s.db, func(tx *sql.Tx) (int64, error) {
+ if err := emailTakenTx(tx, email, uid); err != nil {
+ return 0, err
+ }
+ res, err := tx.Exec(
+ `UPDATE users SET token_version = token_version + CASE WHEN email = ? COLLATE NOCASE THEN 0 ELSE 1 END,
+ email = ?, updated_at = CURRENT_TIMESTAMP
+ WHERE id = ? AND password_hash = ?`, email, email, uid, verifiedHash)
+ if err != nil {
+ return 0, err
+ }
+ n, err := res.RowsAffected()
+ if err != nil {
+ return 0, err
+ }
+ if n == 0 {
+ return 0, ErrPasswordChanged
+ }
+ return 0, tx.QueryRow(`SELECT id, email, token_version, created_at, updated_at FROM users WHERE id = ?`, uid).
+ Scan(&u.ID, &u.Email, &u.TokenVersion, &u.CreatedAt, &u.UpdatedAt)
+ })
+ return u, err
+}
+
// ErrEmptyHash guards the two statements that WRITE a password. Everywhere else an
// empty argument simply matches no rows and surfaces as an error, so a guard would be
// noise -- but these two would store the empty string, and bcrypt rejects it against
diff --git a/backend/stores/user_test.go b/backend/stores/user_test.go
index 51ab45e..ea2db08 100644
--- a/backend/stores/user_test.go
+++ b/backend/stores/user_test.go
@@ -179,3 +179,81 @@ func TestDeleteCascadesEveryChildTable(t *testing.T) {
t.Errorf("other account changed: %+v -> %+v", before, after)
}
}
+
+func TestChangeEmail(t *testing.T) {
+ setup := func(t *testing.T) (*sql.DB, *UserStore) {
+ conn := testDB(t)
+ return conn, NewUserStore(conn)
+ }
+ hashOf := func(t *testing.T, conn *sql.DB, uid int64) string {
+ var h string
+ if err := conn.QueryRow(`SELECT password_hash FROM users WHERE id = ?`, uid).Scan(&h); err != nil {
+ t.Fatal(err)
+ }
+ return h
+ }
+
+ t.Run("another account in another case is taken", func(t *testing.T) {
+ conn, s := setup(t)
+ seedAccount(t, conn, "[email protected]", 0)
+ me := seedAccount(t, conn, "[email protected]", 0)
+ if _, err := s.ChangeEmail(me, "x", "[email protected]"); !errors.Is(err, ErrEmailTaken) {
+ t.Fatalf("err = %v, want ErrEmailTaken", err)
+ }
+ })
+
+ t.Run("own case change", func(t *testing.T) {
+ conn, s := setup(t)
+ me := seedAccount(t, conn, "[email protected]", 0)
+ before, _ := s.TokenVersion(me)
+ u, err := s.ChangeEmail(me, "x", "[email protected]")
+ if err != nil {
+ t.Fatal(err)
+ }
+ if u.Email != "[email protected]" || u.CreatedAt.IsZero() {
+ t.Errorf("user = %+v", u)
+ }
+ if after, _ := s.TokenVersion(me); after != before || u.TokenVersion != before {
+ t.Errorf("a case-only change moved token_version %d -> %d (returned %d)", before, after, u.TokenVersion)
+ }
+ })
+
+ t.Run("stale hash", func(t *testing.T) {
+ conn, s := setup(t)
+ me := seedAccount(t, conn, "[email protected]", 0)
+ if _, err := s.ChangeEmail(me, "stale", "[email protected]"); !errors.Is(err, ErrPasswordChanged) {
+ t.Fatalf("err = %v, want ErrPasswordChanged", err)
+ }
+ var e string
+ if err := conn.QueryRow(`SELECT email FROM users WHERE id = ?`, me).Scan(&e); err != nil || e != "[email protected]" {
+ t.Errorf("email = %q, %v; want unchanged", e, err)
+ }
+ })
+
+ t.Run("index absent", func(t *testing.T) {
+ conn, s := setup(t)
+ dropNocaseIndex(t, conn)
+ seedAccount(t, conn, "[email protected]", 0)
+ me := seedAccount(t, conn, "[email protected]", 0)
+ if _, err := s.ChangeEmail(me, "x", "[email protected]"); !errors.Is(err, ErrEmailTaken) {
+ t.Fatalf("err = %v, want ErrEmailTaken", err)
+ }
+ })
+
+ t.Run("token_version bumped", func(t *testing.T) {
+ conn, s := setup(t)
+ me := seedAccount(t, conn, "[email protected]", 0)
+ before, _ := s.TokenVersion(me)
+ u, err := s.ChangeEmail(me, hashOf(t, conn, me), "[email protected]")
+ if err != nil {
+ t.Fatal(err)
+ }
+ after, _ := s.TokenVersion(me)
+ if after != before+1 {
+ t.Errorf("token_version %d -> %d, want +1", before, after)
+ }
+ if u.TokenVersion != after {
+ t.Errorf("returned version %d, stored %d", u.TokenVersion, after)
+ }
+ })
+}
diff --git a/mobile/app/(tabs)/settings/_layout.tsx b/mobile/app/(tabs)/settings/_layout.tsx
index 402f220..cdb6008 100644
--- a/mobile/app/(tabs)/settings/_layout.tsx
+++ b/mobile/app/(tabs)/settings/_layout.tsx
@@ -1,7 +1,7 @@
import { Stack } from 'expo-router'
import { useTheme } from '../../../src/theme/useTheme'
-// Nested stack under Settings: list → change password. Same shape and same reason as the
+// Nested stack under Settings: list → name, email, password. Same shape and same reason as the
// workouts and weight stacks — contentStyle pins the card background to the app surface so
// the push transition doesn't flash the platform default.
export default function SettingsLayout() {
diff --git a/mobile/app/(tabs)/settings/email.tsx b/mobile/app/(tabs)/settings/email.tsx
new file mode 100644
index 0000000..9dbb99f
--- /dev/null
+++ b/mobile/app/(tabs)/settings/email.tsx
@@ -0,0 +1,145 @@
+import { useState } from 'react'
+import { Pressable, ScrollView, View } from 'react-native'
+import { router } from 'expo-router'
+import { ArrowLeft, MailCheck } from 'lucide-react-native'
+import { useAsyncAction, emailChanged, onlyLetterCaseChanged } from '@lyftr/shared'
+import {
+ Alert,
+ AppText,
+ Button,
+ Card,
+ Field,
+ PageHeader,
+ PasswordField,
+ Screen,
+} from '../../../src/components/ui'
+import { useAuthStore } from '../../../src/lib/lyftr'
+import { useTheme } from '../../../src/theme/useTheme'
+
+// Its own screen, laid out like password.tsx and matching web's /settings/email. It needs
+// the current password, so it cannot be an inline row like the name, and it confirms with a
+// card rather than popping back because the sign-in identifier changed: a consequence the
+// person has to be told about.
+export default function ChangeEmailScreen() {
+ const { colors, brand } = useTheme()
+ const user = useAuthStore((s) => s.user)
+ const changeEmail = useAuthStore((s) => s.changeEmail)
+
+ const [email, setEmail] = useState('')
+ const [current, setCurrent] = useState('')
+ const [changedTo, setChangedTo] = useState<string | null>(null)
+ const [caseOnly, setCaseOnly] = useState(false)
+
+ const back = () => (router.canGoBack() ? router.back() : router.navigate('/settings'))
+
+ const save = useAsyncAction(async () => {
+ const onlyCase = onlyLetterCaseChanged(email, user?.email)
+ const updated = await changeEmail(email, current)
+ setCurrent('')
+ setCaseOnly(onlyCase)
+ setChangedTo(updated.email)
+ }, "Couldn't change your email. Please try again.")
+
+ const ready = emailChanged(email, user?.email) && !!current
+
+ const submit = () => {
+ if (!ready) return
+ void save.run()
+ }
+
+ const backLink = (
+ <Pressable
+ onPress={back}
+ hitSlop={8}
+ className="flex-row items-center gap-1.5 self-start active:opacity-60"
+ >
+ <ArrowLeft size={16} color={colors.txMuted} />
+ <AppText variant="body" color="muted">Settings</AppText>
+ </Pressable>
+ )
+
+ if (changedTo !== null) {
+ return (
+ <Screen>
+ <ScrollView showsVerticalScrollIndicator={false}>
+ <View className="gap-5 py-4">
+ {backLink}
+ <Card className="items-center gap-3 p-6">
+ <View className="h-12 w-12 items-center justify-center rounded-full border border-success-500/20 bg-success-500/10">
+ <MailCheck size={24} color={brand.successSoft} strokeWidth={2.2} />
+ </View>
+ <View className="gap-1">
+ <AppText variant="title" className="text-center">Email changed</AppText>
+ <AppText variant="body" color="muted" className="text-center">
+ Sign in with {changedTo} from now on.{' '}
+ {caseOnly
+ ? 'Only the letter case changed, so your other devices stay signed in.'
+ : 'You stay signed in here; your other devices are signed out.'}
+ </AppText>
+ </View>
+ <Button title="Back to settings" variant="secondary" onPress={back} className="mt-1" />
+ </Card>
+ </View>
+ </ScrollView>
+ </Screen>
+ )
+ }
+
+ return (
+ <Screen>
+ <ScrollView showsVerticalScrollIndicator={false} keyboardShouldPersistTaps="handled">
+ <View className="gap-5 py-4">
+ {backLink}
+ <PageHeader
+ title="Change email"
+ subtitle="You will sign in with the new address. Changing more than the letter case signs out your other devices."
+ />
+
+ <Card className="gap-4">
+ <View className="gap-1">
+ <AppText variant="caption" color="muted">Current email</AppText>
+ <AppText variant="body">{user?.email ?? '—'}</AppText>
+ </View>
+
+ <Field
+ label="New email"
+ value={email}
+ onChangeText={setEmail}
+ keyboardType="email-address"
+ autoCapitalize="none"
+ autoCorrect={false}
+ autoComplete="email"
+ textContentType="emailAddress"
+ autoFocus
+ />
+ <PasswordField
+ label="Current password"
+ value={current}
+ onChangeText={setCurrent}
+ textContentType="password"
+ />
+
+ {save.error ? <Alert variant="error">{save.error}</Alert> : null}
+
+ <View className="flex-row gap-2">
+ <Button
+ title="Update email"
+ onPress={submit}
+ loading={save.busy}
+ disabled={!ready}
+ className="flex-1"
+ />
+ <Button
+ title="Cancel"
+ variant="secondary"
+ onPress={back}
+ disabled={save.busy}
+ className="flex-1"
+ />
+ </View>
+ </Card>
+ </View>
+ </ScrollView>
+ </Screen>
+ )
+}
diff --git a/mobile/app/(tabs)/settings/index.tsx b/mobile/app/(tabs)/settings/index.tsx
index 7888ec8..3aea259 100644
--- a/mobile/app/(tabs)/settings/index.tsx
+++ b/mobile/app/(tabs)/settings/index.tsx
@@ -212,7 +212,14 @@ export default function SettingsScreen() {
chevron
onPress={() => router.push('/settings/name')}
/>
- <SettingsRow icon={Mail} label="Email" value={user?.email ?? '—'} divider />
+ <SettingsRow
+ icon={Mail}
+ label="Email"
+ value={user?.email ?? '—'}
+ divider
+ chevron
+ onPress={() => router.push('/settings/email')}
+ />
<SettingsRow icon={CalendarDays} label="Member since" value={memberSince(user?.created_at)} divider />
<SettingsRow
icon={KeyRound}
diff --git a/packages/shared/src/client.test.ts b/packages/shared/src/client.test.ts
index 1419ea3..2998e3f 100644
--- a/packages/shared/src/client.test.ts
+++ b/packages/shared/src/client.test.ts
@@ -275,6 +275,58 @@ describe('userAPI.changePassword', () => {
})
})
+describe('userAPI.changeEmail', () => {
+ it('PUTs the address and password, returns the user and swaps in the new token pair', async () => {
+ const store = memStorage()
+ const client = createClient(store)
+ let sent: any
+ client.api.defaults.adapter = async (config: any) => {
+ sent = { method: config.method, url: config.url, data: JSON.parse(config.data) }
+ return {
+ data: { data: {
+ token: 'new-access', refresh_token: 'new-refresh',
+ user: { id: 1, email: '[email protected]', created_at: '2026-01-01T00:00:00Z' },
+ } },
+ status: 200, statusText: 'OK', headers: {}, config,
+ }
+ }
+ await store.set(STORAGE_KEYS.access, 'live-access')
+ await store.set(STORAGE_KEYS.refresh, 'live-refresh')
+
+ const user = await client.userAPI.changeEmail({ email: '[email protected]', current_password: 'pw' })
+
+ expect(sent).toEqual({ method: 'put', url: '/me/email', data: { email: '[email protected]', current_password: 'pw' } })
+ expect(user.email).toBe('[email protected]')
+ // The change ends every session on the old version, this one included, so this device
+ // has to carry the pair the server handed back or it is signed out at the next refresh.
+ expect(await store.get(STORAGE_KEYS.access)).toBe('new-access')
+ expect(await store.get(STORAGE_KEYS.refresh)).toBe('new-refresh')
+ })
+
+ it('does not trigger the refresh-and-sign-out path on a rejected password', async () => {
+ const store = memStorage()
+ let signedOut = false
+ const client = createClient(store, { onAuthFailure: () => { signedOut = true } })
+ client.api.defaults.adapter = async (config: any) => {
+ const err: any = new Error('Request failed with status code 401')
+ err.config = config
+ err.response = {
+ status: 401, data: { error: 'Your current password is incorrect.' },
+ statusText: 'Unauthorized', headers: {}, config,
+ }
+ throw err
+ }
+ await store.set(STORAGE_KEYS.access, 'live-access')
+ await store.set(STORAGE_KEYS.refresh, 'live-refresh')
+
+ await expect(client.userAPI.changeEmail({ email: '[email protected]', current_password: 'wrong' })).rejects.toBeDefined()
+
+ expect(signedOut).toBe(false)
+ expect(await store.get(STORAGE_KEYS.access)).toBe('live-access')
+ expect(await store.get(STORAGE_KEYS.refresh)).toBe('live-refresh')
+ })
+})
+
// #145: "action buttons stop responding … requires a full app restart". The reporter's
// two clues named the mechanism exactly — it happened when connectivity to their
// homelab dropped, and it cleared "immediately" once the connection came back. Nothing
diff --git a/packages/shared/src/client.ts b/packages/shared/src/client.ts
index 66d7b73..120cefd 100644
--- a/packages/shared/src/client.ts
+++ b/packages/shared/src/client.ts
@@ -197,11 +197,11 @@ export function createClient(
const original = error.config
// A 401 from an endpoint that checks a password in its body is a credential
// error, not an expired session — let the page show it instead of
- // refreshing/redirecting. /me/password belongs here for the same reason
+ // refreshing/redirecting. /me/password and /me/email belong here for the same reason
// /auth/login does: it answers "that password is wrong", and refreshing would
// retry, fail again, and sign the user out over a typo.
const url = original?.url || ''
- const isCredentialCheck = url.includes('/auth/') || url.includes('/me/password')
+ const isCredentialCheck = url.includes('/auth/') || url.includes('/me/password') || url.includes('/me/email')
if (error.response?.status === 401 && !original._retry && !isCredentialCheck) {
original._retry = true
try {
@@ -242,10 +242,18 @@ export function createClient(
getSettings: () => api.get<{ data: types.UserSettings }>('/settings').then(unwrap),
updateSettings: (data: Partial<types.UserSettings>) => api.put<{ data: types.UserSettings }>('/settings', data).then(unwrap),
deleteAccount: () => api.delete('/me'),
- // Persisting the returned pair is not optional. The change invalidates every token
- // minted against the old password, this device's included, so skipping this would
- // sign the user out of the very session that made the change — at the next refresh,
- // minutes later, with nothing on screen to connect it to what they did.
+ // Persisting the returned pair is not optional, for either of these. The change bumps
+ // the account's token version, which invalidates every token minted before it, this
+ // device's included, so skipping this would sign the user out of the very session that
+ // made the change — at the next refresh, minutes later, with nothing on screen to
+ // connect it to what they did. Returns the updated user for the caller's store.
+ changeEmail: async (data: types.ChangeEmailRequest) => {
+ const res = await api.put<{ data: types.AuthResponse }>('/me/email', data)
+ const { token, refresh_token, user } = res.data.data
+ await storage.set(STORAGE_KEYS.access, token)
+ await storage.set(STORAGE_KEYS.refresh, refresh_token)
+ return user
+ },
changePassword: async (data: types.ChangePasswordRequest) => {
const res = await api.put<{ data: types.TokenPair }>('/me/password', data)
const pair = res.data.data
diff --git a/packages/shared/src/stores/auth.test.ts b/packages/shared/src/stores/auth.test.ts
index 0becc8d..bfdec5b 100644
--- a/packages/shared/src/stores/auth.test.ts
+++ b/packages/shared/src/stores/auth.test.ts
@@ -77,3 +77,49 @@ describe('auth store (storage-adapter DI)', () => {
expect(state.user?.email).toBe('[email protected]')
})
})
+
+describe('auth store changeEmail', () => {
+ const signedIn = () =>
+ createMemoryStorage({
+ [STORAGE_KEYS.access]: 'access-123',
+ [STORAGE_KEYS.refresh]: 'refresh-456',
+ [STORAGE_KEYS.user]: JSON.stringify(fakeAuthResponse.user),
+ })
+
+ it('trims the address, caches the returned user and leaves the tokens alone', async () => {
+ const storage = signedIn()
+ const calls: any[] = []
+ const updated = { ...fakeAuthResponse.user, email: '[email protected]' }
+ const client = {
+ authAPI: {},
+ userAPI: { changeEmail: async (d: any) => { calls.push(d); return updated } },
+ } as unknown as LyftrClient
+ const useAuth = createAuthStore(client, storage)
+ await useAuth.getState().hydrate()
+
+ const res = await useAuth.getState().changeEmail(' [email protected] ', 'pw')
+
+ expect(calls).toEqual([{ email: '[email protected]', current_password: 'pw' }])
+ expect(res).toEqual(updated)
+ expect(useAuth.getState().user).toEqual(updated)
+ expect(JSON.parse((await storage.get(STORAGE_KEYS.user))!)).toEqual(updated)
+ expect(await storage.get(STORAGE_KEYS.access)).toBe('access-123')
+ expect(await storage.get(STORAGE_KEYS.refresh)).toBe('refresh-456')
+ })
+
+ it('rejects and changes nothing when the client fails', async () => {
+ const storage = signedIn()
+ const client = {
+ authAPI: {},
+ userAPI: { changeEmail: async () => { throw new Error('nope') } },
+ } as unknown as LyftrClient
+ const useAuth = createAuthStore(client, storage)
+ await useAuth.getState().hydrate()
+
+ await expect(useAuth.getState().changeEmail('[email protected]', 'pw')).rejects.toThrow('nope')
+
+ expect(useAuth.getState().user).toEqual(fakeAuthResponse.user)
+ expect(useAuth.getState().error).toBeNull()
+ expect(JSON.parse((await storage.get(STORAGE_KEYS.user))!)).toEqual(fakeAuthResponse.user)
+ })
+})
diff --git a/packages/shared/src/stores/auth.ts b/packages/shared/src/stores/auth.ts
index 21839f0..6ca8101 100644
--- a/packages/shared/src/stores/auth.ts
+++ b/packages/shared/src/stores/auth.ts
@@ -13,6 +13,7 @@ export interface AuthStore {
login: (email: string, password: string) => Promise<void>
register: (email: string, password: string) => Promise<void>
logout: () => Promise<void>
+ changeEmail: (email: string, currentPassword: string) => Promise<types.User>
clearError: () => void
}
@@ -73,6 +74,16 @@ export function createAuthStore(client: LyftrClient, storage: StorageAdapter) {
set({ user: null, isAuthenticated: false, error: null })
},
+ // No try/catch and no store.error: the screen's useAsyncAction reports the failure
+ // where the tap was, and a failed call leaves state and storage untouched. This is
+ // the only place the outgoing address is trimmed.
+ changeEmail: async (email, currentPassword) => {
+ const user = await client.userAPI.changeEmail({ email: email.trim(), current_password: currentPassword })
+ await storage.set(STORAGE_KEYS.user, JSON.stringify(user))
+ set({ user })
+ return user
+ },
+
clearError: () => set({ error: null }),
}))
}
diff --git a/packages/shared/src/types.ts b/packages/shared/src/types.ts
index 620e798..cfc1561 100644
--- a/packages/shared/src/types.ts
+++ b/packages/shared/src/types.ts
@@ -310,6 +310,11 @@ export interface TokenPair {
refresh_token: string
}
+export interface ChangeEmailRequest {
+ email: string
+ current_password: string
+}
+
export interface ChangePasswordRequest {
current_password: string
new_password: string
diff --git a/packages/shared/src/utils/profile.test.ts b/packages/shared/src/utils/profile.test.ts
index 36b4abe..a4eea05 100644
--- a/packages/shared/src/utils/profile.test.ts
+++ b/packages/shared/src/utils/profile.test.ts
@@ -1,4 +1,4 @@
-import { displayName, nameInitial } from './profile'
+import { displayName, emailChanged, nameInitial, onlyLetterCaseChanged } from './profile'
describe('displayName', () => {
it('prefers the name the person chose', () => {
@@ -46,3 +46,39 @@ describe('nameInitial', () => {
expect(nameInitial('🦍 Carter')).toHaveLength(2) // one code point, two UTF-16 units
})
})
+
+describe('onlyLetterCaseChanged', () => {
+ it('is true when only ASCII letter case differs', () => {
+ expect(onlyLetterCaseChanged('[email protected]', '[email protected]')).toBe(true)
+ expect(onlyLetterCaseChanged(' [email protected] ', '[email protected]')).toBe(true)
+ })
+
+ it('is false for the same spelling, a different address, nothing typed or no current', () => {
+ expect(onlyLetterCaseChanged('[email protected]', '[email protected]')).toBe(false)
+ expect(onlyLetterCaseChanged('[email protected]', '[email protected]')).toBe(false)
+ expect(onlyLetterCaseChanged('', '[email protected]')).toBe(false)
+ expect(onlyLetterCaseChanged('[email protected]', undefined)).toBe(false)
+ })
+
+ it('folds ASCII only, as NOCASE does, so a non-ASCII case difference is a real change', () => {
+ expect(onlyLetterCaseChanged('MÜ[email protected]', 'mü[email protected]')).toBe(false)
+ })
+})
+
+describe('emailChanged', () => {
+ it('is false for nothing typed or the same address', () => {
+ expect(emailChanged('', '[email protected]')).toBe(false)
+ expect(emailChanged(' ', '[email protected]')).toBe(false)
+ expect(emailChanged('[email protected]', '[email protected]')).toBe(false)
+ expect(emailChanged(' [email protected] ', '[email protected]')).toBe(false)
+ })
+
+ it('counts a letter-case change, which the server allows', () => {
+ expect(emailChanged('[email protected]', '[email protected]')).toBe(true)
+ })
+
+ it('is true for a different address, or when there is no current one', () => {
+ expect(emailChanged('[email protected]', '[email protected]')).toBe(true)
+ expect(emailChanged('[email protected]', undefined)).toBe(true)
+ })
+})
diff --git a/packages/shared/src/utils/profile.ts b/packages/shared/src/utils/profile.ts
index 7f37536..b11c351 100644
--- a/packages/shared/src/utils/profile.ts
+++ b/packages/shared/src/utils/profile.ts
@@ -17,6 +17,23 @@ export function displayName(name?: string, email?: string): string {
return local || 'there'
}
+// Whether the typed address differs from the current one. A letter-case change counts:
+// the server allows it.
+export function emailChanged(input: string, current?: string): boolean {
+ const next = input.trim()
+ return next !== '' && next !== (current ?? '')
+}
+
+// Whether the new address differs from the current one only in letter case, which the server
+// accepts without ending any other session. This only picks the wording of the confirmation;
+// the server decides. It folds ASCII A-Z alone, as SQLite's NOCASE does, rather than
+// toLowerCase, so the two cannot disagree about which addresses are the same.
+const asciiFold = (s: string) => s.replace(/[A-Z]/g, (c) => c.toLowerCase())
+export function onlyLetterCaseChanged(input: string, current?: string): boolean {
+ const next = input.trim()
+ return next !== '' && next !== (current ?? '') && asciiFold(next) === asciiFold(current ?? '')
+}
+
// The avatar letter. Takes what displayName already returned rather than deriving it
// again, so the circle and the name beside it always start with the same letter.
//
diff --git a/site/src/content/docs/configuration.md b/site/src/content/docs/configuration.md
index d6c3a8c..70d19b8 100644
--- a/site/src/content/docs/configuration.md
+++ b/site/src/content/docs/configuration.md
@@ -99,6 +99,23 @@ Other devices stop as soon as their current access token expires, which is `JWT_
(one hour by default). Raising `JWT_EXPIRY` widens that window by exactly the same amount, so a
long expiry trades a little convenience for a longer tail after a password change.
+## Changing your email
+
+**Settings → Account → Email**, on the web app and in the Android app. Like a password change it
+asks for your current password, so a stolen session alone cannot take the address over. The web
+form is at `/settings/email`.
+
+You can change it to any address no other account holds. Letter case does not count as a
+difference, so `[email protected]` is taken if `[email protected]` is registered, but you can
+change the case of your own address. The address is stored exactly as you type it.
+
+Like a password change it **signs you out everywhere else**. The device you changed it on stays
+signed in, and you sign in with the new address from now on. The old one stops working at once.
+Lyftr cannot email the old address, so ending the other sessions is how a change made from a session
+that was not yours gets contained. Other devices stop when their current access token expires, the
+same window as a password change. Changing only the letter case, say `carter@` to `Carter@`, is the
+one exception: sign-in already ignores case, so nothing needs containing and no session ends.
+
## If you forget your password
There is no self-service reset. Nothing here can email you a link, and an instance with no mail
diff --git a/web/e2e/auth.spec.ts b/web/e2e/auth.spec.ts
index a0baf6f..34444ec 100644
--- a/web/e2e/auth.spec.ts
+++ b/web/e2e/auth.spec.ts
@@ -158,6 +158,79 @@ test('a wrong current password shows an error without signing the user out', asy
expect(await page.evaluate(() => localStorage.getItem('access_token'))).toBeTruthy()
})
+test('changes the account email and signs in with the new address', async ({ page }) => {
+ const ts = Date.now()
+ const email = `e2e-email+${ts}@lyftr.local`
+ const moved = `E2E-Moved+${ts}@lyftr.local`
+ const password = 'password123'
+
+ await page.goto('/register')
+ await page.getByPlaceholder('[email protected]').fill(email)
+ await page.locator('#password').fill(password)
+ await page.locator('#password-confirm').fill(password)
+ await page.getByRole('button', { name: /create account/i }).click()
+ await page.waitForURL(url => new URL(url).pathname === '/')
+
+ const token = await page.evaluate(() => localStorage.getItem('access_token'))
+ if (token) recordCreatedUser(token)
+
+ await page.goto('/settings')
+ await page.getByRole('link', { name: /change email/i }).click()
+ await expect(page).toHaveURL(/\/settings\/email$/)
+ await page.locator('#new-email').fill(moved)
+ await page.locator('#current-password').fill(password)
+ await page.getByRole('button', { name: /update email/i }).click()
+
+ await expect(page.getByRole('heading', { name: /email changed/i })).toBeVisible()
+ await expect(page.getByText(/other devices are signed out/i)).toBeVisible()
+
+ await page.goto('/settings')
+ await expect(page.getByText(moved)).toBeVisible()
+
+ // This device stays signed in: the client swapped in the pair the server returned. The
+ // other devices are the ones signed out (covered by the backend tests).
+ expect(await page.evaluate(() => localStorage.getItem('access_token'))).toBeTruthy()
+ await page.goto('/workouts')
+ await expect(page).toHaveURL(/\/workouts$/)
+
+ // The address really moved: the old one no longer signs in, the new one does in any case.
+ await page.evaluate(() => localStorage.clear())
+ await page.goto('/login')
+ await page.getByPlaceholder('[email protected]').fill(email)
+ await page.locator('#password').fill(password)
+ await page.getByRole('button', { name: /sign in/i }).click()
+ await expect(page.locator('.alert-error')).toBeVisible()
+
+ await page.getByPlaceholder('[email protected]').fill(moved.toLowerCase())
+ await page.getByRole('button', { name: /sign in/i }).click()
+ await page.waitForURL(url => new URL(url).pathname === '/')
+})
+
+// /me/email returns 401 for a wrong current password, the same shape as /me/password, and
+// must not be mistaken for an expired session.
+test('a wrong current password on change email shows an error without signing the user out', async ({ page }) => {
+ const email = `e2e-email-bad+${Date.now()}@lyftr.local`
+
+ await page.goto('/register')
+ await page.getByPlaceholder('[email protected]').fill(email)
+ await page.locator('#password').fill('password123')
+ await page.locator('#password-confirm').fill('password123')
+ await page.getByRole('button', { name: /create account/i }).click()
+ await page.waitForURL(url => new URL(url).pathname === '/')
+
+ const token = await page.evaluate(() => localStorage.getItem('access_token'))
+ if (token) recordCreatedUser(token)
+
+ await page.goto('/settings/email')
+ await page.locator('#new-email').fill(`other+${Date.now()}@lyftr.local`)
+ await page.locator('#current-password').fill('not-my-password')
+ await page.getByRole('button', { name: /update email/i }).click()
+
+ await expect(page.locator('.alert-error')).toContainText(/current password is incorrect/i)
+ await expect(page).toHaveURL(/\/settings\/email$/)
+ expect(await page.evaluate(() => localStorage.getItem('access_token'))).toBeTruthy()
+})
+
// The W3C Change Password URL. Password managers open it to send a user to the form, and
// expect a redirect — served by nginx in production and by a vite middleware in dev, so
// this runs against either stack. Asserted without following, because a 200 here would
diff --git a/web/src/App.tsx b/web/src/App.tsx
index ffaf492..e682484 100644
--- a/web/src/App.tsx
+++ b/web/src/App.tsx
@@ -22,6 +22,7 @@ import Weight from './pages/Weight'
import WeightDetail from './pages/WeightDetail'
import Settings from './pages/Settings'
import ChangePassword from './pages/ChangePassword'
+import ChangeEmail from './pages/ChangeEmail'
import Login from './pages/Login'
import Register from './pages/Register'
@@ -67,6 +68,7 @@ function App() {
<Route path="/weight/:id" element={<WeightDetail />} />
<Route path="/settings" element={<Settings />} />
<Route path="/settings/password" element={<ChangePassword />} />
+ <Route path="/settings/email" element={<ChangeEmail />} />
{/* Signed in, there was no catch-all at all — only the signed-OUT branch had
one — so any unknown path matched no route and React Router rendered
nothing: a white screen, still signed in, with no nav to click. A stale
diff --git a/web/src/pages/ChangeEmail.test.tsx b/web/src/pages/ChangeEmail.test.tsx
new file mode 100644
index 0000000..c54f33f
--- /dev/null
+++ b/web/src/pages/ChangeEmail.test.tsx
@@ -0,0 +1,91 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest'
+import { render, screen, fireEvent, waitFor } from '@testing-library/react'
+import { MemoryRouter } from 'react-router-dom'
+import ChangeEmail from './ChangeEmail'
+
+const changeEmail = vi.fn()
+
+const state = () => ({
+ user: { id: 1, email: '[email protected]', created_at: '2026-07-01T00:00:00Z' },
+ changeEmail,
+})
+
+vi.mock('../stores/auth', () => ({
+ useAuthStore: (selector?: (s: unknown) => unknown) => (selector ? selector(state()) : state()),
+}))
+
+const renderPage = () =>
+ render(
+ <MemoryRouter>
+ <ChangeEmail />
+ </MemoryRouter>,
+ )
+
+const submitButton = () => screen.getByRole('button', { name: 'Update email' }) as HTMLButtonElement
+const typeEmail = (v: string) => fireEvent.change(screen.getByLabelText('New email'), { target: { value: v } })
+const typePassword = (v: string) => fireEvent.change(screen.getByLabelText('Current password'), { target: { value: v } })
+
+describe('ChangeEmail', () => {
+ beforeEach(() => {
+ changeEmail.mockReset()
+ })
+
+ it('shows the current address', () => {
+ renderPage()
+ expect(screen.getByText('[email protected]')).toBeTruthy()
+ })
+
+ it('enables the button only for a different address and a password', () => {
+ renderPage()
+ expect(submitButton().disabled).toBe(true)
+
+ typeEmail('[email protected]')
+ typePassword('password123')
+ expect(submitButton().disabled).toBe(true)
+
+ typeEmail('[email protected]')
+ expect(submitButton().disabled).toBe(false)
+ })
+
+ it('submits the typed values and confirms with the address the server returned', async () => {
+ changeEmail.mockResolvedValue({ id: 1, email: '[email protected]', created_at: '2026-07-01T00:00:00Z' })
+ renderPage()
+
+ typeEmail('[email protected]')
+ typePassword('password123')
+ fireEvent.click(submitButton())
+
+ await waitFor(() => expect(screen.getByRole('heading', { name: 'Email changed' })).toBeTruthy())
+ expect(changeEmail).toHaveBeenCalledWith('[email protected]', 'password123')
+ expect(screen.getByText('[email protected]')).toBeTruthy()
+ expect(screen.getByText(/Sign in with.*from now on/s).textContent).toContain('[email protected]')
+ expect(screen.getByText(/other devices are signed out/s)).toBeTruthy()
+ })
+
+ it('says the other devices stay signed in when only the letter case changed', async () => {
+ changeEmail.mockResolvedValue({ id: 1, email: '[email protected]', created_at: '2026-07-01T00:00:00Z' })
+ renderPage()
+
+ typeEmail('[email protected]')
+ typePassword('password123')
+ fireEvent.click(submitButton())
+
+ await waitFor(() => expect(screen.getByRole('heading', { name: 'Email changed' })).toBeTruthy())
+ expect(screen.getByText(/Only the letter case changed/).textContent).toContain('other devices stay signed in')
+ expect(screen.queryByText(/other devices are signed out/)).toBeNull()
+ })
+
+ it('shows a refusal in the form and keeps what was typed', async () => {
+ changeEmail.mockRejectedValue({
+ response: { status: 409, data: { error: 'That email is already registered.' } },
+ })
+ renderPage()
+
+ typeEmail('[email protected]')
+ typePassword('password123')
+ fireEvent.click(submitButton())
+
+ await waitFor(() => expect(screen.getByText('That email is already registered.')).toBeTruthy())
+ expect((screen.getByLabelText('New email') as HTMLInputElement).value).toBe('[email protected]')
+ })
+})
diff --git a/web/src/pages/ChangeEmail.tsx b/web/src/pages/ChangeEmail.tsx
new file mode 100644
index 0000000..48bc018
--- /dev/null
+++ b/web/src/pages/ChangeEmail.tsx
@@ -0,0 +1,126 @@
+import { useState } from 'react'
+import { Link } from 'react-router-dom'
+import { ArrowLeft, AlertCircle, Loader, MailCheck } from 'lucide-react'
+import { useAuthStore } from '../stores/auth'
+import { useAsyncAction, emailChanged, onlyLetterCaseChanged } from '@lyftr/shared'
+import PageHeader from '../components/ui/PageHeader'
+import PasswordField from '../components/ui/PasswordField'
+
+// A page rather than an inline row like the name, because it needs the current password.
+// It confirms with a card rather than a toast because the sign-in identifier changed:
+// that is a consequence the user has to be told about, not just a saved field.
+export default function ChangeEmail() {
+ const user = useAuthStore(s => s.user)
+ const changeEmail = useAuthStore(s => s.changeEmail)
+ const [email, setEmail] = useState('')
+ const [current, setCurrent] = useState('')
+ const [changedTo, setChangedTo] = useState<string | null>(null)
+ const [caseOnly, setCaseOnly] = useState(false)
+
+ const save = useAsyncAction(async () => {
+ const onlyCase = onlyLetterCaseChanged(email, user?.email)
+ const updated = await changeEmail(email, current)
+ setCurrent('')
+ setCaseOnly(onlyCase)
+ setChangedTo(updated.email)
+ }, "Couldn't change your email. Please try again.")
+
+ const ready = emailChanged(email, user?.email) && !!current
+
+ const submit = (e: React.FormEvent) => {
+ e.preventDefault()
+ if (!ready) return
+ void save.run()
+ }
+
+ if (changedTo !== null) {
+ return (
+ <div className="space-y-5 animate-slide-up max-w-lg">
+ <Link to="/settings" className="flex items-center gap-1.5 text-sm text-tx-muted hover:text-tx-primary transition-colors">
+ <ArrowLeft className="w-4 h-4" /> Settings
+ </Link>
+
+ <div className="card p-6 flex flex-col items-center text-center gap-3">
+ <div className="w-12 h-12 rounded-full bg-success-500/10 border border-success-500/20 flex items-center justify-center">
+ <MailCheck className="w-6 h-6 text-success-400" />
+ </div>
+ <div>
+ <h1 className="font-display font-bold text-xl text-tx-primary">Email changed</h1>
+ <p className="text-sm text-tx-muted mt-1">
+ Sign in with <span className="break-all text-tx-secondary">{changedTo}</span> from now on.{' '}
+ {caseOnly
+ ? 'Only the letter case changed, so your other devices stay signed in.'
+ : 'You stay signed in here; your other devices are signed out.'}
+ </p>
+ </div>
+ <Link to="/settings" className="btn-secondary btn-sm mt-1">Back to settings</Link>
+ </div>
+ </div>
+ )
+ }
+
+ return (
+ <div className="space-y-5 animate-slide-up max-w-lg">
+ <Link to="/settings" className="flex items-center gap-1.5 text-sm text-tx-muted hover:text-tx-primary transition-colors">
+ <ArrowLeft className="w-4 h-4" /> Settings
+ </Link>
+
+ <PageHeader
+ title="Change email"
+ subtitle="You will sign in with the new address. Changing more than the letter case signs out your other devices."
+ />
+
+ <form onSubmit={submit} className="card p-4 space-y-4">
+ <div>
+ <p className="text-xs text-tx-muted">Current email</p>
+ <p className="text-sm text-tx-primary font-mono break-all">{user?.email}</p>
+ </div>
+
+ <div>
+ <label htmlFor="new-email" className="label">
+ New email
+ </label>
+ <input
+ id="new-email"
+ type="email"
+ className="input"
+ autoComplete="email"
+ autoCapitalize="none"
+ spellCheck={false}
+ required
+ value={email}
+ onChange={e => setEmail(e.target.value)}
+ />
+ </div>
+
+ <PasswordField
+ id="current-password"
+ label="Current password"
+ value={current}
+ onChange={setCurrent}
+ autoComplete="current-password"
+ />
+
+ {save.error && (
+ <div className="alert-error">
+ <AlertCircle className="w-5 h-5 flex-shrink-0" />
+ <span>{save.error}</span>
+ </div>
+ )}
+
+ <div className="flex gap-2 pt-1">
+ <button
+ type="submit"
+ disabled={save.busy || !ready}
+ className="btn-primary btn-sm flex-1 flex items-center justify-center gap-2"
+ >
+ {save.busy ? <><Loader className="w-3.5 h-3.5 animate-spin" /> Saving</> : 'Update email'}
+ </button>
+ <Link to="/settings" className="btn-secondary btn-sm flex-1 flex items-center justify-center">
+ Cancel
+ </Link>
+ </div>
+ </form>
+ </div>
+ )
+}
diff --git a/web/src/pages/Settings.tsx b/web/src/pages/Settings.tsx
index d709460..ae8085f 100644
--- a/web/src/pages/Settings.tsx
+++ b/web/src/pages/Settings.tsx
@@ -13,7 +13,7 @@ import ServerSettings from '../components/ServerSettings'
import { Link } from 'react-router-dom'
import {
Moon, Sun, LogOut, Trash2, Check, AlertCircle, Loader,
- RefreshCw, Pencil, Clock, Minus, Plus, KeyRound,
+ RefreshCw, Pencil, Clock, Minus, Plus, KeyRound, Mail,
} from 'lucide-react'
// Wraps per row, on content rather than on viewport width.
@@ -299,7 +299,12 @@ export default function Settings() {
)}
</SettingRow>
<SettingRow label="Email" description="Your login email address">
- <span className="text-sm text-tx-muted font-mono">{user?.email}</span>
+ <div className="flex flex-wrap items-center justify-end gap-2">
+ <span className="text-sm text-tx-muted font-mono break-all">{user?.email}</span>
+ <Link to="/settings/email" aria-label="Change email" className="btn-secondary btn-sm">
+ <Mail className="w-3.5 h-3.5" /> Change
+ </Link>
+ </div>
</SettingRow>
<SettingRow label="Member since">
<span className="text-sm text-tx-muted">{memberSince(user?.created_at)}</span>