docs: add implementation plan for profile deletion
This commit is contained in:
766
docs/superpowers/plans/2026-07-26-profile-deletion.md
Normal file
766
docs/superpowers/plans/2026-07-26-profile-deletion.md
Normal file
@@ -0,0 +1,766 @@
|
|||||||
|
# Profile Deletion Implementation Plan
|
||||||
|
|
||||||
|
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
|
||||||
|
|
||||||
|
**Goal:** Let a signed-in geniusrun user permanently delete their entire account (Garmin credentials, custom rules, every synced activity) from a "Danger zone" button on the Profile page, and log them out afterward.
|
||||||
|
|
||||||
|
**Architecture:** Add `ON DELETE CASCADE` to every FK pointing at `users(id)` (and `workout_kinds(id)`) in `schema.sql`, so a single `DELETE FROM users` removes everything. Wrap that in a new `store.DeleteUser`, expose it via `DELETE /api/profile`, and have that handler also tear down the deleted user's cached Garmin subprocess/client and on-disk token-store directory. The frontend gates the call behind a type-`DELETE`-to-confirm UI, then performs a real POST navigation to the existing `/api/session/logout` route (the same one the header's Log out button already uses) so the OIDC session ends too.
|
||||||
|
|
||||||
|
**Tech Stack:** Go (`net/http`, `database/sql` via `modernc.org/sqlite`, chi router), React + TypeScript (Vite), no frontend test framework.
|
||||||
|
|
||||||
|
## Global Constraints
|
||||||
|
|
||||||
|
- `internal/store/schema.sql` is edited directly, never migrated — this is a pre-production app (see `CLAUDE.md`).
|
||||||
|
- Every store/API method that touches per-user data takes an explicit `userID` and must filter/scope by it — the entire cross-user isolation boundary depends on this (see `CLAUDE.md`'s Authentication section).
|
||||||
|
- Cross-user isolation must be tested adversarially (two real users, real IDs), not just checked for non-collision — matches `internal/store/isolation_test.go` / `internal/api/isolation_test.go` convention.
|
||||||
|
- After any `schema.sql` change, regenerate `docs/DATABASE.md` via `go run ./cmd/dumpschema` (run from `backend/`).
|
||||||
|
- `gofmt -l .` must report nothing before committing; `go vet ./...` and `go build ./...` must pass.
|
||||||
|
- No frontend test suite exists — frontend changes are verified via `npm run build`, `npm run lint`, and a manual browser check.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### Task 1: Cascading deletes in the store layer
|
||||||
|
|
||||||
|
**Files:**
|
||||||
|
- Modify: `backend/internal/store/schema.sql:29,85,103,121,222,232`
|
||||||
|
- Modify: `backend/internal/store/users.go` (add `DeleteUser`)
|
||||||
|
- Modify: `backend/internal/store/users_test.go` (add `TestDeleteUser_RemovesUserAndCascadesEverything`)
|
||||||
|
- Modify: `backend/internal/store/isolation_test.go` (add `TestIsolation_DeleteUserLeavesOtherUsersDataIntact`)
|
||||||
|
- Modify: `docs/DATABASE.md` (regenerated, not hand-edited)
|
||||||
|
|
||||||
|
**Interfaces:**
|
||||||
|
- Produces: `func (db *DB) DeleteUser(ctx context.Context, userID int64) error` — deletes the `users` row for `userID`; every owned row (profile, workout_kinds, workout_type_paces, activities, laps, activity_samples, kind_assignments, sync_state, sync_runs) cascades away via the schema FKs added in this task.
|
||||||
|
|
||||||
|
- [ ] **Step 1: Write the failing test**
|
||||||
|
|
||||||
|
Add to `backend/internal/store/users_test.go`:
|
||||||
|
|
||||||
|
```go
|
||||||
|
func TestDeleteUser_RemovesUserAndCascadesEverything(t *testing.T) {
|
||||||
|
db := openTestDB(t)
|
||||||
|
ctx := context.Background()
|
||||||
|
|
||||||
|
userID, err := db.ProvisionUser(ctx, "delete-me", "Delete Me")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("ProvisionUser: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
activityID, err := db.UpsertActivity(ctx, userID, Activity{GarminActivityID: 1, StartTimeUTC: "2026-07-11 06:00:00", RawJSON: "{}"})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("UpsertActivity: %v", err)
|
||||||
|
}
|
||||||
|
kindID, err := db.CreateWorkoutKind(ctx, userID, WorkoutKind{Name: "Test Delete Kind", RuleJSON: `{"match":"all","conditions":[]}`, IsActive: true})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("CreateWorkoutKind: %v", err)
|
||||||
|
}
|
||||||
|
if err := db.ReplaceLaps(ctx, userID, activityID, []Lap{{LapIndex: 1}}); err != nil {
|
||||||
|
t.Fatalf("ReplaceLaps: %v", err)
|
||||||
|
}
|
||||||
|
if err := db.ReplaceActivitySamples(ctx, userID, activityID, []Sample{{ElapsedSeconds: 0}}); err != nil {
|
||||||
|
t.Fatalf("ReplaceActivitySamples: %v", err)
|
||||||
|
}
|
||||||
|
if _, err := db.InsertKindAssignment(ctx, userID, KindAssignment{
|
||||||
|
ActivityID: activityID, WorkoutKindID: &kindID, AssignmentSource: AssignmentSourceRuleEngine,
|
||||||
|
Status: AssignmentStatusAssigned, CandidateKindsJSON: "[]",
|
||||||
|
}); err != nil {
|
||||||
|
t.Fatalf("InsertKindAssignment: %v", err)
|
||||||
|
}
|
||||||
|
minPace := 300.0
|
||||||
|
if err := db.UpdateWorkoutTypePace(ctx, userID, WorkoutTypePace{WorkoutKindID: kindID, PaceMinSecPerKm: &minPace}); err != nil {
|
||||||
|
t.Fatalf("UpdateWorkoutTypePace: %v", err)
|
||||||
|
}
|
||||||
|
if err := db.UpdateSyncState(ctx, userID, "2020-01-01", true); err != nil {
|
||||||
|
t.Fatalf("UpdateSyncState: %v", err)
|
||||||
|
}
|
||||||
|
if _, err := db.StartSyncRun(ctx, userID, SyncKindBackfill); err != nil {
|
||||||
|
t.Fatalf("StartSyncRun: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := db.DeleteUser(ctx, userID); err != nil {
|
||||||
|
t.Fatalf("DeleteUser: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if _, found, err := db.GetUserBySub(ctx, "delete-me"); err != nil || found {
|
||||||
|
t.Fatalf("expected user gone after DeleteUser, found=%v err=%v", found, err)
|
||||||
|
}
|
||||||
|
|
||||||
|
checks := []struct {
|
||||||
|
query string
|
||||||
|
arg int64
|
||||||
|
}{
|
||||||
|
{`SELECT COUNT(*) FROM profile WHERE user_id = ?`, userID},
|
||||||
|
{`SELECT COUNT(*) FROM workout_kinds WHERE user_id = ?`, userID},
|
||||||
|
{`SELECT COUNT(*) FROM workout_type_paces WHERE workout_kind_id = ?`, kindID},
|
||||||
|
{`SELECT COUNT(*) FROM activities WHERE user_id = ?`, userID},
|
||||||
|
{`SELECT COUNT(*) FROM laps WHERE activity_id = ?`, activityID},
|
||||||
|
{`SELECT COUNT(*) FROM activity_samples WHERE activity_id = ?`, activityID},
|
||||||
|
{`SELECT COUNT(*) FROM kind_assignments WHERE activity_id = ?`, activityID},
|
||||||
|
{`SELECT COUNT(*) FROM sync_state WHERE user_id = ?`, userID},
|
||||||
|
{`SELECT COUNT(*) FROM sync_runs WHERE user_id = ?`, userID},
|
||||||
|
}
|
||||||
|
for _, c := range checks {
|
||||||
|
var count int
|
||||||
|
if err := db.QueryRowContext(ctx, c.query, c.arg).Scan(&count); err != nil {
|
||||||
|
t.Fatalf("count query %q: %v", c.query, err)
|
||||||
|
}
|
||||||
|
if count != 0 {
|
||||||
|
t.Errorf("query %q: got %d rows, want 0 after DeleteUser", c.query, count)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Add to `backend/internal/store/isolation_test.go`:
|
||||||
|
|
||||||
|
```go
|
||||||
|
// TestIsolation_DeleteUserLeavesOtherUsersDataIntact confirms deleting one
|
||||||
|
// user's account never touches another user's profile, taxonomy, or
|
||||||
|
// activities, even though DeleteUser is a single blunt DELETE FROM users.
|
||||||
|
func TestIsolation_DeleteUserLeavesOtherUsersDataIntact(t *testing.T) {
|
||||||
|
db := openTestDB(t)
|
||||||
|
ctx := context.Background()
|
||||||
|
|
||||||
|
userA, err := db.ProvisionUser(ctx, "sub-a", "A")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("ProvisionUser(a): %v", err)
|
||||||
|
}
|
||||||
|
userB, err := db.ProvisionUser(ctx, "sub-b", "B")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("ProvisionUser(b): %v", err)
|
||||||
|
}
|
||||||
|
if _, err := db.UpsertActivity(ctx, userB, Activity{GarminActivityID: 1, StartTimeUTC: "2026-07-11 06:00:00", RawJSON: "{}"}); err != nil {
|
||||||
|
t.Fatalf("UpsertActivity(b): %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := db.DeleteUser(ctx, userA); err != nil {
|
||||||
|
t.Fatalf("DeleteUser(a): %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if _, found, err := db.GetUserBySub(ctx, "sub-b"); err != nil || !found {
|
||||||
|
t.Fatalf("expected userB to survive userA's deletion, found=%v err=%v", found, err)
|
||||||
|
}
|
||||||
|
profileB, err := db.GetProfile(ctx, userB)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("GetProfile(b) after deleting a: %v", err)
|
||||||
|
}
|
||||||
|
if profileB.Name != "B" {
|
||||||
|
t.Errorf("userB's profile changed after deleting userA: %+v", profileB)
|
||||||
|
}
|
||||||
|
kindsB, err := db.ListWorkoutKinds(ctx, userB, false)
|
||||||
|
if err != nil || len(kindsB) != 8 {
|
||||||
|
t.Fatalf("userB's taxonomy affected by deleting userA: len=%d err=%v", len(kindsB), err)
|
||||||
|
}
|
||||||
|
activitiesB, err := db.ListActivities(ctx, userB, ActivityFilter{})
|
||||||
|
if err != nil || len(activitiesB) != 1 {
|
||||||
|
t.Fatalf("userB's activities affected by deleting userA: len=%d err=%v", len(activitiesB), err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
- [ ] **Step 2: Run tests to verify they fail**
|
||||||
|
|
||||||
|
Run: `cd backend && go test ./internal/store/... -run 'TestDeleteUser|TestIsolation_DeleteUser' -v`
|
||||||
|
Expected: FAIL — `db.DeleteUser undefined (type *DB has no field or method DeleteUser)`.
|
||||||
|
|
||||||
|
- [ ] **Step 3: Add `ON DELETE CASCADE` to schema.sql**
|
||||||
|
|
||||||
|
In `backend/internal/store/schema.sql`, change these six lines (each currently ends `REFERENCES users(id),` or `REFERENCES workout_kinds(id),`):
|
||||||
|
|
||||||
|
Line 29 (`profile.user_id`), from:
|
||||||
|
```sql
|
||||||
|
user_id INTEGER NOT NULL REFERENCES users(id),
|
||||||
|
```
|
||||||
|
to:
|
||||||
|
```sql
|
||||||
|
user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
||||||
|
```
|
||||||
|
|
||||||
|
Line 85 (`workout_kinds.user_id`), from:
|
||||||
|
```sql
|
||||||
|
user_id INTEGER NOT NULL REFERENCES users(id),
|
||||||
|
```
|
||||||
|
to:
|
||||||
|
```sql
|
||||||
|
user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
||||||
|
```
|
||||||
|
|
||||||
|
Line 103 (`workout_type_paces.workout_kind_id`), from:
|
||||||
|
```sql
|
||||||
|
workout_kind_id INTEGER PRIMARY KEY REFERENCES workout_kinds(id),
|
||||||
|
```
|
||||||
|
to:
|
||||||
|
```sql
|
||||||
|
workout_kind_id INTEGER PRIMARY KEY REFERENCES workout_kinds(id) ON DELETE CASCADE,
|
||||||
|
```
|
||||||
|
|
||||||
|
Line 121 (`activities.user_id`), from:
|
||||||
|
```sql
|
||||||
|
user_id INTEGER NOT NULL REFERENCES users(id),
|
||||||
|
```
|
||||||
|
to:
|
||||||
|
```sql
|
||||||
|
user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
||||||
|
```
|
||||||
|
|
||||||
|
Line 222 (`sync_state.user_id`), from:
|
||||||
|
```sql
|
||||||
|
user_id INTEGER NOT NULL REFERENCES users(id),
|
||||||
|
```
|
||||||
|
to:
|
||||||
|
```sql
|
||||||
|
user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
||||||
|
```
|
||||||
|
|
||||||
|
Line 232 (`sync_runs.user_id`), from:
|
||||||
|
```sql
|
||||||
|
user_id INTEGER NOT NULL REFERENCES users(id),
|
||||||
|
```
|
||||||
|
to:
|
||||||
|
```sql
|
||||||
|
user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
||||||
|
```
|
||||||
|
|
||||||
|
`laps`/`activity_samples`/`kind_assignments` already cascade off `activities(id)` — no change needed there. SQLite's `foreign_keys` pragma is already on for every connection (`db.go`), so these cascades (including the two-level `users → workout_kinds → workout_type_paces` chain) take effect immediately, no code change required for the pragma itself.
|
||||||
|
|
||||||
|
- [ ] **Step 4: Add `DeleteUser` to `backend/internal/store/users.go`**
|
||||||
|
|
||||||
|
Append after `ProvisionUser` (end of file):
|
||||||
|
|
||||||
|
```go
|
||||||
|
|
||||||
|
// DeleteUser permanently deletes userID's account. Every row that belongs
|
||||||
|
// to it -- profile, workout kinds (and their paces), activities (and their
|
||||||
|
// laps/samples/kind_assignments), sync_state, and sync_runs -- cascades
|
||||||
|
// away via the ON DELETE CASCADE foreign keys in schema.sql, so this is a
|
||||||
|
// single statement rather than per-table deletes. Irreversible; the API
|
||||||
|
// layer gates this behind a UI confirmation (see
|
||||||
|
// docs/superpowers/specs/2026-07-26-profile-deletion-design.md).
|
||||||
|
func (db *DB) DeleteUser(ctx context.Context, userID int64) error {
|
||||||
|
if _, err := db.ExecContext(ctx, `DELETE FROM users WHERE id = ?`, userID); err != nil {
|
||||||
|
return fmt.Errorf("delete user %d: %w", userID, err)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
- [ ] **Step 5: Run tests to verify they pass**
|
||||||
|
|
||||||
|
Run: `cd backend && go test ./internal/store/... -run 'TestDeleteUser|TestIsolation_DeleteUser' -v`
|
||||||
|
Expected: PASS.
|
||||||
|
|
||||||
|
- [ ] **Step 6: Run the full store test suite**
|
||||||
|
|
||||||
|
Run: `cd backend && go test ./internal/store/...`
|
||||||
|
Expected: PASS (confirms the new `ON DELETE CASCADE` clauses didn't break `ResetAllSyncedData` or any other existing behavior).
|
||||||
|
|
||||||
|
- [ ] **Step 7: Regenerate `docs/DATABASE.md`**
|
||||||
|
|
||||||
|
Run: `cd backend && go run ./cmd/dumpschema`
|
||||||
|
Expected: `docs/DATABASE.md` updates to show `ON DELETE CASCADE` on the six changed columns.
|
||||||
|
|
||||||
|
- [ ] **Step 8: Commit**
|
||||||
|
|
||||||
|
```bash
|
||||||
|
git add backend/internal/store/schema.sql backend/internal/store/users.go backend/internal/store/users_test.go backend/internal/store/isolation_test.go docs/DATABASE.md
|
||||||
|
git commit -m "feat(store): add DeleteUser with cascading account deletion"
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### Task 2: `DELETE /api/profile` and Garmin client/tokenstore teardown
|
||||||
|
|
||||||
|
**Files:**
|
||||||
|
- Modify: `backend/internal/api/server.go:5-21` (imports), `:95-117` (new `removeGarminClient` after `syncFor`), `:167-170` (route)
|
||||||
|
- Modify: `backend/internal/api/profile.go` (add `handleDeleteProfile`)
|
||||||
|
- Modify: `backend/internal/api/api_test.go` (imports + 3 new tests)
|
||||||
|
- Modify: `backend/internal/api/isolation_test.go` (1 new test)
|
||||||
|
|
||||||
|
**Interfaces:**
|
||||||
|
- Consumes: `store.DB.DeleteUser(ctx, userID) error` (Task 1); `garmin.Client.Close() error` and `.UpdateCredentials` (existing); `Server.userGarmin/userSync/userAuthStatus/userAuthMessage/userSyncRunning map[int64]...` and `Server.mu sync.Mutex` (existing fields); `Server.GarminBase garmin.Config` (existing, has `.TokenStorePath string`).
|
||||||
|
- Produces: `func (s *Server) removeGarminClient(userID int64)` — used only within this task's handler, not exported further. `DELETE /api/profile` route → `handleDeleteProfile`, responding `204` on success, `409` if a sync is running for that user.
|
||||||
|
|
||||||
|
- [ ] **Step 1: Write the failing tests**
|
||||||
|
|
||||||
|
Add `"os"` to `backend/internal/api/api_test.go`'s import block (needed for Step 1's token-store test):
|
||||||
|
|
||||||
|
```go
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"context"
|
||||||
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
|
"net/http"
|
||||||
|
"net/http/httptest"
|
||||||
|
"net/url"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"strconv"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"geniusrun/backend/internal/auth"
|
||||||
|
authmock "geniusrun/backend/internal/auth/mock"
|
||||||
|
"geniusrun/backend/internal/garmin"
|
||||||
|
"geniusrun/backend/internal/garmin/mock"
|
||||||
|
"geniusrun/backend/internal/store"
|
||||||
|
appsync "geniusrun/backend/internal/sync"
|
||||||
|
)
|
||||||
|
```
|
||||||
|
|
||||||
|
Append to `backend/internal/api/api_test.go`:
|
||||||
|
|
||||||
|
```go
|
||||||
|
func TestDeleteProfile_DeletesUserAndTerminatesGarminClient(t *testing.T) {
|
||||||
|
s, db, userID := newTestServer(t)
|
||||||
|
router := s.Router()
|
||||||
|
|
||||||
|
// Force the per-user Garmin client to be built and cached.
|
||||||
|
rec := doJSON(t, router, http.MethodPost, "/api/auth/login", nil)
|
||||||
|
if rec.Code != http.StatusOK {
|
||||||
|
t.Fatalf("auth/login status = %d, body = %s", rec.Code, rec.Body.String())
|
||||||
|
}
|
||||||
|
client, err := s.garminFor(context.Background(), userID)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("garminFor: %v", err)
|
||||||
|
}
|
||||||
|
mockClient, ok := client.(*mock.Client)
|
||||||
|
if !ok {
|
||||||
|
t.Fatalf("expected *mock.Client, got %T", client)
|
||||||
|
}
|
||||||
|
|
||||||
|
rec = doJSON(t, router, http.MethodDelete, "/api/profile", nil)
|
||||||
|
if rec.Code != http.StatusNoContent {
|
||||||
|
t.Fatalf("delete status = %d, body = %s", rec.Code, rec.Body.String())
|
||||||
|
}
|
||||||
|
|
||||||
|
if _, found, err := db.GetUserBySub(context.Background(), "test-user"); err != nil || found {
|
||||||
|
t.Fatalf("expected user gone after delete, found=%v err=%v", found, err)
|
||||||
|
}
|
||||||
|
if !mockClient.ClosedCalled {
|
||||||
|
t.Error("expected the cached garmin client to be Close()d on profile deletion")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestDeleteProfile_RejectsWhileSyncInProgress(t *testing.T) {
|
||||||
|
s, db, userID := newTestServer(t)
|
||||||
|
s.mu.Lock()
|
||||||
|
s.userSyncRunning[userID] = true
|
||||||
|
s.mu.Unlock()
|
||||||
|
|
||||||
|
rec := doJSON(t, s.Router(), http.MethodDelete, "/api/profile", nil)
|
||||||
|
if rec.Code != http.StatusConflict {
|
||||||
|
t.Fatalf("status = %d, want 409, body = %s", rec.Code, rec.Body.String())
|
||||||
|
}
|
||||||
|
if _, found, err := db.GetUserBySub(context.Background(), "test-user"); err != nil || !found {
|
||||||
|
t.Fatalf("expected user to survive a rejected delete, found=%v err=%v", found, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestDeleteProfile_RemovesTokenStoreDirectory(t *testing.T) {
|
||||||
|
db, err := store.Open(filepath.Join(t.TempDir(), "geniusrun_test.db"))
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("store.Open: %v", err)
|
||||||
|
}
|
||||||
|
t.Cleanup(func() { db.Close() })
|
||||||
|
userID, err := db.ProvisionUser(context.Background(), "test-user", "Test User")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("ProvisionUser: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
tokenStoreRoot := t.TempDir()
|
||||||
|
userTokenDir := filepath.Join(tokenStoreRoot, strconv.FormatInt(userID, 10))
|
||||||
|
if err := os.MkdirAll(userTokenDir, 0o755); err != nil {
|
||||||
|
t.Fatalf("MkdirAll: %v", err)
|
||||||
|
}
|
||||||
|
if err := os.WriteFile(filepath.Join(userTokenDir, "session.json"), []byte("{}"), 0o644); err != nil {
|
||||||
|
t.Fatalf("WriteFile: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
m := &mock.Client{}
|
||||||
|
garminFactory := func(garmin.Config) garmin.Client { return m }
|
||||||
|
s := NewServer(db, garminFactory, garmin.Config{TokenStorePath: tokenStoreRoot}, appsync.Config{}, &authmock.Verifier{}, testSessionConfig)
|
||||||
|
|
||||||
|
rec := doJSON(t, s.Router(), http.MethodDelete, "/api/profile", nil)
|
||||||
|
if rec.Code != http.StatusNoContent {
|
||||||
|
t.Fatalf("delete status = %d, body = %s", rec.Code, rec.Body.String())
|
||||||
|
}
|
||||||
|
if _, err := os.Stat(userTokenDir); !os.IsNotExist(err) {
|
||||||
|
t.Fatalf("expected token store dir %q to be removed, stat err = %v", userTokenDir, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Append to `backend/internal/api/isolation_test.go`:
|
||||||
|
|
||||||
|
```go
|
||||||
|
// TestIsolation_DeleteProfileOnlyDeletesOwnAccount confirms one user
|
||||||
|
// deleting their own profile never touches another user's account, even
|
||||||
|
// though DeleteUser is keyed purely by the session-resolved userID.
|
||||||
|
func TestIsolation_DeleteProfileOnlyDeletesOwnAccount(t *testing.T) {
|
||||||
|
s, db, userA := newTestServer(t) // provisions "test-user" (userA)
|
||||||
|
if _, err := db.ProvisionUser(newCtx(), "user-b", "B"); err != nil {
|
||||||
|
t.Fatalf("ProvisionUser(b): %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
router := s.Router()
|
||||||
|
rec := doJSONAs(t, router, "user-b", http.MethodDelete, "/api/profile", nil)
|
||||||
|
if rec.Code != http.StatusNoContent {
|
||||||
|
t.Fatalf("userB delete status = %d, body = %s", rec.Code, rec.Body.String())
|
||||||
|
}
|
||||||
|
|
||||||
|
if _, found, err := db.GetUserBySub(newCtx(), "user-b"); err != nil || found {
|
||||||
|
t.Fatalf("expected userB gone after their own delete, found=%v err=%v", found, err)
|
||||||
|
}
|
||||||
|
u, found, err := db.GetUserBySub(newCtx(), "test-user")
|
||||||
|
if err != nil || !found || u.ID != userA {
|
||||||
|
t.Fatalf("expected userA to survive userB's deletion, found=%v err=%v id=%d want=%d", found, err, u.ID, userA)
|
||||||
|
}
|
||||||
|
rec = doJSON(t, router, http.MethodGet, "/api/profile", nil) // as userA
|
||||||
|
if rec.Code != http.StatusOK {
|
||||||
|
t.Fatalf("userA profile status after userB deleted themselves = %d, body = %s", rec.Code, rec.Body.String())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
- [ ] **Step 2: Run tests to verify they fail**
|
||||||
|
|
||||||
|
Run: `cd backend && go test ./internal/api/... -run 'TestDeleteProfile|TestIsolation_DeleteProfile' -v`
|
||||||
|
Expected: FAIL — 404s (no `DELETE /api/profile` route registered yet).
|
||||||
|
|
||||||
|
- [ ] **Step 3: Add the `os` import and `removeGarminClient` to `server.go`**
|
||||||
|
|
||||||
|
Change the import block (add `"os"` between `"net/http"` and `"path/filepath"`):
|
||||||
|
|
||||||
|
```go
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
|
"log"
|
||||||
|
"net/http"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"strconv"
|
||||||
|
"sync"
|
||||||
|
|
||||||
|
"github.com/go-chi/chi/v5"
|
||||||
|
|
||||||
|
"geniusrun/backend/internal/auth"
|
||||||
|
"geniusrun/backend/internal/garmin"
|
||||||
|
"geniusrun/backend/internal/store"
|
||||||
|
appsync "geniusrun/backend/internal/sync"
|
||||||
|
)
|
||||||
|
```
|
||||||
|
|
||||||
|
Insert this new method right after `syncFor` (i.e. between the existing `syncFor` closing brace and the `RunIncrementalSyncForAllUsers` doc comment):
|
||||||
|
|
||||||
|
```go
|
||||||
|
|
||||||
|
// removeGarminClient drops userID's cached garmin.Client/sync.Service (if
|
||||||
|
// any) and every other per-user in-memory entry for userID, terminating the
|
||||||
|
// client's subprocess and best-effort removing its on-disk token-store
|
||||||
|
// directory. Called when a user's account has just been deleted from the
|
||||||
|
// DB, so nothing in memory keeps referencing a userID that no longer
|
||||||
|
// exists.
|
||||||
|
func (s *Server) removeGarminClient(userID int64) {
|
||||||
|
s.mu.Lock()
|
||||||
|
client, ok := s.userGarmin[userID]
|
||||||
|
delete(s.userGarmin, userID)
|
||||||
|
delete(s.userSync, userID)
|
||||||
|
delete(s.userAuthStatus, userID)
|
||||||
|
delete(s.userAuthMessage, userID)
|
||||||
|
delete(s.userSyncRunning, userID)
|
||||||
|
s.mu.Unlock()
|
||||||
|
|
||||||
|
if ok {
|
||||||
|
if err := client.Close(); err != nil {
|
||||||
|
log.Printf("api: close garmin client for deleted user %d: %v", userID, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if s.GarminBase.TokenStorePath == "" {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
tokenStoreDir := filepath.Join(s.GarminBase.TokenStorePath, strconv.FormatInt(userID, 10))
|
||||||
|
if err := os.RemoveAll(tokenStoreDir); err != nil {
|
||||||
|
log.Printf("api: remove token store dir for deleted user %d: %v", userID, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
- [ ] **Step 4: Register the route in `Router()`**
|
||||||
|
|
||||||
|
In `server.go`, change:
|
||||||
|
|
||||||
|
```go
|
||||||
|
r.Route("/profile", func(r chi.Router) {
|
||||||
|
r.Get("/", s.handleGetProfile)
|
||||||
|
r.Put("/", s.handleUpdateProfile)
|
||||||
|
})
|
||||||
|
```
|
||||||
|
|
||||||
|
to:
|
||||||
|
|
||||||
|
```go
|
||||||
|
r.Route("/profile", func(r chi.Router) {
|
||||||
|
r.Get("/", s.handleGetProfile)
|
||||||
|
r.Put("/", s.handleUpdateProfile)
|
||||||
|
r.Delete("/", s.handleDeleteProfile)
|
||||||
|
})
|
||||||
|
```
|
||||||
|
|
||||||
|
- [ ] **Step 5: Add `handleDeleteProfile` to `profile.go`**
|
||||||
|
|
||||||
|
Append to `backend/internal/api/profile.go`:
|
||||||
|
|
||||||
|
```go
|
||||||
|
|
||||||
|
// handleDeleteProfile permanently deletes the signed-in user's entire
|
||||||
|
// geniusrun account (profile, workout kinds/paces, activities and
|
||||||
|
// everything under them, sync state/runs -- see schema.sql's ON DELETE
|
||||||
|
// CASCADE from users(id)) and tears down their cached Garmin client and
|
||||||
|
// token-store directory. It does not touch the session cookie itself --
|
||||||
|
// the frontend follows a successful call with a real logout navigation
|
||||||
|
// (see docs/superpowers/specs/2026-07-26-profile-deletion-design.md).
|
||||||
|
func (s *Server) handleDeleteProfile(w http.ResponseWriter, r *http.Request) {
|
||||||
|
userID := userIDFromContext(r.Context())
|
||||||
|
|
||||||
|
s.mu.Lock()
|
||||||
|
inProgress := s.userSyncRunning[userID]
|
||||||
|
s.mu.Unlock()
|
||||||
|
if inProgress {
|
||||||
|
writeError(w, http.StatusConflict, "a sync is in progress for this account; wait for it to finish before deleting your profile")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := s.DB.DeleteUser(r.Context(), userID); err != nil {
|
||||||
|
writeError(w, http.StatusInternalServerError, err.Error())
|
||||||
|
return
|
||||||
|
}
|
||||||
|
s.removeGarminClient(userID)
|
||||||
|
w.WriteHeader(http.StatusNoContent)
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
- [ ] **Step 6: Run tests to verify they pass**
|
||||||
|
|
||||||
|
Run: `cd backend && go test ./internal/api/... -run 'TestDeleteProfile|TestIsolation_DeleteProfile' -v`
|
||||||
|
Expected: PASS.
|
||||||
|
|
||||||
|
- [ ] **Step 7: Run the full backend test suite**
|
||||||
|
|
||||||
|
Run: `cd backend && go build ./... && go vet ./... && gofmt -l . && go test ./...`
|
||||||
|
Expected: `gofmt -l .` prints nothing; `go build`/`go vet`/`go test` all succeed.
|
||||||
|
|
||||||
|
- [ ] **Step 8: Commit**
|
||||||
|
|
||||||
|
```bash
|
||||||
|
git add backend/internal/api/server.go backend/internal/api/profile.go backend/internal/api/api_test.go backend/internal/api/isolation_test.go
|
||||||
|
git commit -m "feat(api): add DELETE /api/profile with Garmin client/tokenstore teardown"
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### Task 3: Frontend Danger zone UI
|
||||||
|
|
||||||
|
**Files:**
|
||||||
|
- Modify: `frontend/src/api/client.ts` (add `deleteProfile`)
|
||||||
|
- Modify: `frontend/src/pages/Profile.tsx` (add Danger zone fieldset + confirm flow)
|
||||||
|
- Modify: `frontend/src/App.css` (small `.danger-zone-confirm` rule)
|
||||||
|
|
||||||
|
**Interfaces:**
|
||||||
|
- Consumes: `DELETE /api/profile` (Task 2, returns `204` or throws via the existing `request()` helper's non-2xx handling); `BASE_URL` (already exported from `client.ts`).
|
||||||
|
- Produces: `api.deleteProfile(): Promise<void>`, used only from `Profile.tsx`.
|
||||||
|
|
||||||
|
- [ ] **Step 1: Add `deleteProfile` to the API client**
|
||||||
|
|
||||||
|
In `frontend/src/api/client.ts`, in the `// Profile` section, change:
|
||||||
|
|
||||||
|
```ts
|
||||||
|
// Profile
|
||||||
|
getProfile: () => request<Profile>("/api/profile"),
|
||||||
|
updateProfile: (profile: Profile) =>
|
||||||
|
request<Profile>("/api/profile", { method: "PUT", body: JSON.stringify(profile) }),
|
||||||
|
```
|
||||||
|
|
||||||
|
to:
|
||||||
|
|
||||||
|
```ts
|
||||||
|
// Profile
|
||||||
|
getProfile: () => request<Profile>("/api/profile"),
|
||||||
|
updateProfile: (profile: Profile) =>
|
||||||
|
request<Profile>("/api/profile", { method: "PUT", body: JSON.stringify(profile) }),
|
||||||
|
// Permanently deletes the signed-in user's entire account. The caller is
|
||||||
|
// responsible for following a successful call with a real logout
|
||||||
|
// navigation -- this does not touch the session cookie (see Profile.tsx).
|
||||||
|
deleteProfile: () => request<void>("/api/profile", { method: "DELETE" }),
|
||||||
|
```
|
||||||
|
|
||||||
|
- [ ] **Step 2: Add the Danger zone section to `Profile.tsx`**
|
||||||
|
|
||||||
|
Change the import line:
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
import { api } from "../api/client";
|
||||||
|
```
|
||||||
|
|
||||||
|
to:
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
import { api, BASE_URL } from "../api/client";
|
||||||
|
```
|
||||||
|
|
||||||
|
Add these three state variables inside `Profile`, right after the existing `saveTimeoutRef` declaration:
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
const [deleteConfirmOpen, setDeleteConfirmOpen] = useState(false);
|
||||||
|
const [deleteConfirmText, setDeleteConfirmText] = useState("");
|
||||||
|
const [deleting, setDeleting] = useState(false);
|
||||||
|
```
|
||||||
|
|
||||||
|
Add this function right after `flushPendingSave`:
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
async function deleteAccount() {
|
||||||
|
setDeleting(true);
|
||||||
|
setError(null);
|
||||||
|
try {
|
||||||
|
await api.deleteProfile();
|
||||||
|
// Deletion doesn't clear the session cookie -- follow with a real
|
||||||
|
// logout navigation (must be a POST, same as the header's Log out
|
||||||
|
// button in App.tsx) so Keycloak's own SSO session ends too, not just
|
||||||
|
// geniusrun's local one.
|
||||||
|
const form = document.createElement("form");
|
||||||
|
form.method = "post";
|
||||||
|
form.action = `${BASE_URL}/api/session/logout`;
|
||||||
|
document.body.appendChild(form);
|
||||||
|
form.submit();
|
||||||
|
} catch (e) {
|
||||||
|
setError(String(e));
|
||||||
|
setDeleting(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Add this fieldset right after `<TrainingTypesCard />` (still inside the closing `</div>` of `.profile-page`):
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
<fieldset className="kind-editor danger-zone">
|
||||||
|
<legend>Danger zone</legend>
|
||||||
|
{!deleteConfirmOpen ? (
|
||||||
|
<button type="button" className="button-danger" onClick={() => setDeleteConfirmOpen(true)}>
|
||||||
|
Delete profile
|
||||||
|
</button>
|
||||||
|
) : (
|
||||||
|
<div className="danger-zone-confirm">
|
||||||
|
<p>
|
||||||
|
This permanently deletes your account -- Garmin credentials, every custom rule, and every synced
|
||||||
|
activity -- and logs you out. This cannot be undone.
|
||||||
|
</p>
|
||||||
|
<label>
|
||||||
|
Type DELETE to confirm
|
||||||
|
<input
|
||||||
|
type="text"
|
||||||
|
value={deleteConfirmText}
|
||||||
|
onChange={(e) => setDeleteConfirmText(e.target.value)}
|
||||||
|
disabled={deleting}
|
||||||
|
/>
|
||||||
|
</label>
|
||||||
|
<div className="controls">
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
disabled={deleting}
|
||||||
|
onClick={() => {
|
||||||
|
setDeleteConfirmOpen(false);
|
||||||
|
setDeleteConfirmText("");
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
Cancel
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className="button-danger"
|
||||||
|
disabled={deleting || deleteConfirmText !== "DELETE"}
|
||||||
|
onClick={deleteAccount}
|
||||||
|
>
|
||||||
|
Permanently delete
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</fieldset>
|
||||||
|
```
|
||||||
|
|
||||||
|
- [ ] **Step 3: Add the confirmation block's CSS**
|
||||||
|
|
||||||
|
In `frontend/src/App.css`, add right after the `.button-danger:hover:not(:disabled)` rule:
|
||||||
|
|
||||||
|
```css
|
||||||
|
.danger-zone-confirm {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: 0.5rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.danger-zone-confirm p {
|
||||||
|
margin: 0;
|
||||||
|
color: #9aa0ab;
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
- [ ] **Step 4: Build and lint**
|
||||||
|
|
||||||
|
Run: `cd frontend && npm run build && npm run lint`
|
||||||
|
Expected: build succeeds; lint reports no new warnings (the 3 pre-existing `PaceField.tsx` `only-export-components` warnings are unrelated and expected to remain).
|
||||||
|
|
||||||
|
- [ ] **Step 5: Manual browser verification**
|
||||||
|
|
||||||
|
With the backend running (`cd backend && ./start.sh`) and frontend dev server running (`cd frontend && ./start.sh`), in a browser:
|
||||||
|
1. Log in, go to the Profile page, scroll to "Danger zone".
|
||||||
|
2. Click "Delete profile" — the confirm block appears; "Permanently delete" is disabled.
|
||||||
|
3. Type `delete` (lowercase) — button stays disabled. Type `DELETE` — button enables.
|
||||||
|
4. Click "Cancel" — block collapses, typed text is cleared if reopened.
|
||||||
|
5. Reopen, type `DELETE`, click "Permanently delete" — expect a full-page navigation ending on the login screen (Keycloak or geniusrun's own login gate, matching what the existing "Log out" button already does).
|
||||||
|
6. Log back in with the same account — expect the "Create your profile" screen (`CreateProfile.tsx`), confirming the account was actually deleted, not just logged out.
|
||||||
|
|
||||||
|
- [ ] **Step 6: Commit**
|
||||||
|
|
||||||
|
```bash
|
||||||
|
git add frontend/src/api/client.ts frontend/src/pages/Profile.tsx frontend/src/App.css
|
||||||
|
git commit -m "feat(profile): add Danger zone account deletion UI"
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### Task 4: Final verification
|
||||||
|
|
||||||
|
**Files:** none (verification only)
|
||||||
|
|
||||||
|
- [ ] **Step 1: Full backend check**
|
||||||
|
|
||||||
|
Run: `cd backend && gofmt -l . && go vet ./... && go build ./... && go test ./...`
|
||||||
|
Expected: `gofmt -l .` empty; everything else passes.
|
||||||
|
|
||||||
|
- [ ] **Step 2: Full frontend check**
|
||||||
|
|
||||||
|
Run: `cd frontend && npm run build && npm run lint`
|
||||||
|
Expected: both succeed, no new lint warnings.
|
||||||
|
|
||||||
|
- [ ] **Step 3: Confirm `docs/DATABASE.md` is current**
|
||||||
|
|
||||||
|
Run: `cd backend && go run ./cmd/dumpschema && git status --short docs/DATABASE.md`
|
||||||
|
Expected: no output from `git status` (already committed in Task 1, and hasn't drifted since).
|
||||||
|
|
||||||
|
- [ ] **Step 4: Update `docs/IDEAS.md`**
|
||||||
|
|
||||||
|
Remove the now-implemented line from `docs/IDEAS.md`'s Backlog section:
|
||||||
|
|
||||||
|
```
|
||||||
|
- profile deletion: add a way to delete our profile with a dedicated button on the profile page (which by extension will also logout the user, to be consistent with the logic that login will trigger the profile creation)
|
||||||
|
```
|
||||||
|
|
||||||
|
- [ ] **Step 5: Commit**
|
||||||
|
|
||||||
|
```bash
|
||||||
|
git add docs/IDEAS.md
|
||||||
|
git commit -m "docs: remove profile deletion from IDEAS backlog (implemented)"
|
||||||
|
```
|
||||||
Reference in New Issue
Block a user