forked from longtao.wu/droboticflow
Contract step of the account-phone-login expand-migrate-contract rollout. Phone is now the sole account identifier end to end: - domain.UserRecord/CreateUserInput: delete Email, drop Phone's omitempty (required going forward). - store: delete email_unique Mongo index; phone_unique is now non-sparse (unique, not sparse) since every account creation path requires a phone. Delete FindUserByEmail, ensureUserEmailAvailableLocked, and ErrDuplicateUserEmail (confirmed dead via grep - all real call sites were already migrated to the *Phone equivalents by tickets 01-03). Mongo duplicate-key fallback and the account-mutation-guard's stale-write snapshot/filter now key off Phone instead of Email. - api: drop the now-impossible ErrDuplicateUserEmail branch in renderUserMutationError. The account-hierarchy audit endpoint and the supplier-deletion receipt struct both switch their identifying field from Email to Phone, since both are populated fresh from current account state (not frozen historical snapshots) - continuing to read a "email" key would silently go blank for every account created after this change. - frontend: src/types.ts User.phone is now required (email removed); AccountHierarchyIssue.email -> .phone in services/api/users.ts and pages/Users.tsx to match the backend audit endpoint's renamed field. - Rewrote the wide blast radius of Go test fixtures that constructed users by email across internal/api/*_test.go and internal/store/*_test.go, including the two dedicated memory-store uniqueness tests (merged into phone-only equivalents) and several opt-in "live" acceptance-fixture tests gated behind env vars for real Fanyu deployments. Repo-wide grep of Go and TS/TSX for Email/email/邮箱 turned up no remaining account-identifier references outside of a few harmless test-only cosmetic labels (e.g. "Email Tenant" as an org display name in a seed helper) and assertions that explicitly check "邮箱" text is absent from API responses. go build/vet clean. go test ./internal/api/... ./internal/store/... ./internal/domain/... : 75 failures, identical test names to the pre-ticket-05 baseline (diffed against a throwaway worktree at the prior tip). npm run lint:web (tsc --noEmit) clean. npm run test:frontend: 599/586/13, matching the stated baseline exactly. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
103 lines
4.3 KiB
Go
103 lines
4.3 KiB
Go
package api
|
|
|
|
import (
|
|
"context"
|
|
"droboticflow/internal/domain"
|
|
"droboticflow/internal/store"
|
|
"encoding/json"
|
|
"fmt"
|
|
"github.com/go-chi/chi/v5"
|
|
"go.mongodb.org/mongo-driver/bson"
|
|
"go.mongodb.org/mongo-driver/mongo"
|
|
"go.mongodb.org/mongo-driver/mongo/options"
|
|
"net/http"
|
|
"net/http/httptest"
|
|
"os"
|
|
"testing"
|
|
"time"
|
|
)
|
|
|
|
// Operator-only repair of one explicitly identified, already disabled account.
|
|
// Without ACCOUNT_DELETE_APPLY=1 it only reports the matching account's state.
|
|
func TestAccountDeleteLiveRepair(t *testing.T) {
|
|
if os.Getenv("ACCOUNT_DELETE_LIVE") != "1" {
|
|
t.Skip("explicit account repair")
|
|
}
|
|
phone, name, supplierName, actorPhone := os.Getenv("ACCOUNT_DELETE_PHONE"), os.Getenv("ACCOUNT_DELETE_NAME"), os.Getenv("ACCOUNT_DELETE_SUPPLIER"), os.Getenv("ACCOUNT_DELETE_ACTOR_PHONE")
|
|
if phone == "" || name == "" || supplierName == "" || actorPhone == "" {
|
|
t.Fatal("exact target and actor required")
|
|
}
|
|
ctx, cancel := context.WithTimeout(t.Context(), time.Minute)
|
|
defer cancel()
|
|
client, e := mongo.Connect(ctx, options.Client().ApplyURI(os.Getenv("MONGO_URI")))
|
|
if e != nil {
|
|
t.Fatal("connection failed")
|
|
}
|
|
defer client.Disconnect(context.Background())
|
|
db := client.Database(os.Getenv("MONGO_DB"))
|
|
ds := store.NewMongoStore(db)
|
|
must := func(e error) {
|
|
t.Helper()
|
|
if e != nil {
|
|
t.Fatal(e)
|
|
}
|
|
}
|
|
user, e := ds.FindUserByPhone(ctx, phone)
|
|
must(e)
|
|
actor, e := ds.FindUserByPhone(ctx, actorPhone)
|
|
must(e)
|
|
if user == nil || actor == nil || user.Name != name || user.Role == domain.UserRoleAdmin || user.IsSuperAdmin || user.Status != domain.UserStatusDisabled || actor.Role != domain.UserRoleAdmin || actor.IsSuperAdmin || actor.Status != domain.UserStatusActive || actor.DeletedAt != "" || actor.OrganizationID != user.OrganizationID {
|
|
t.Fatal("target or actor scope changed")
|
|
}
|
|
supplier, e := ds.GetSupplier(ctx, user.SupplierID)
|
|
must(e)
|
|
if supplier == nil || supplier.Name != supplierName || supplier.OrganizationID != user.OrganizationID {
|
|
t.Fatal("supplier scope changed")
|
|
}
|
|
org, e := ds.GetOrganization(ctx, user.OrganizationID)
|
|
must(e)
|
|
if org == nil || org.Status == domain.OrganizationStatusDisabled {
|
|
t.Fatal("account scope disabled")
|
|
}
|
|
sessions, e := db.Collection("sessions").CountDocuments(ctx, bson.M{"userId": user.ID})
|
|
must(e)
|
|
fmt.Printf("target=%s status=%s deleted=%t sessions=%d\n", user.ID, user.Status, user.DeletedAt != "", sessions)
|
|
if os.Getenv("ACCOUNT_DELETE_APPLY") != "1" {
|
|
return
|
|
}
|
|
_, e = db.Collection("accountDeletionRepairs").UpdateOne(ctx, bson.M{"_id": "complete-requested-delete-" + user.ID}, bson.M{"$setOnInsert": bson.M{"userId": user.ID, "priorStatus": user.Status, "priorDeletedAt": user.DeletedAt, "actorId": actor.ID, "createdAt": nowISO(), "reason": "Complete user-requested deletion previously recorded only as disabled"}}, options.Update().SetUpsert(true))
|
|
must(e)
|
|
route := chi.NewRouteContext()
|
|
route.URLParams.Add("id", user.ID)
|
|
req := httptest.NewRequest(http.MethodDelete, "/api/users/"+user.ID, nil).WithContext(context.WithValue(context.WithValue(ctx, chi.RouteCtxKey, route), authContextKey{}, &authenticatedPrincipal{User: *actor, Organization: *org}))
|
|
response := httptest.NewRecorder()
|
|
srv := &server{store: ds}
|
|
srv.handleUsersDelete(response, req)
|
|
if response.Code != 204 {
|
|
t.Fatalf("deletion handler: %d %s", response.Code, response.Body.String())
|
|
}
|
|
saved, e := ds.GetUser(ctx, user.ID)
|
|
must(e)
|
|
if saved == nil || saved.DeletedAt == "" || saved.Status != domain.UserStatusDisabled || saved.Phone != phone {
|
|
t.Fatal("deletion readback failed")
|
|
}
|
|
listReq := httptest.NewRequest(http.MethodGet, "/api/users?includeDisabled=true", nil).WithContext(context.WithValue(ctx, authContextKey{}, &authenticatedPrincipal{User: *actor, Organization: *org}))
|
|
listResp := httptest.NewRecorder()
|
|
srv.handleUsersList(listResp, listReq)
|
|
var list struct {
|
|
Items []domain.UserRecord `json:"items"`
|
|
}
|
|
must(json.Unmarshal(listResp.Body.Bytes(), &list))
|
|
for _, u := range list.Items {
|
|
if u.ID == user.ID {
|
|
t.Fatal("deleted account remains in directory")
|
|
}
|
|
}
|
|
sessions, e = db.Collection("sessions").CountDocuments(ctx, bson.M{"userId": user.ID})
|
|
must(e)
|
|
if sessions != 0 {
|
|
t.Fatal("sessions remain")
|
|
}
|
|
fmt.Println("VERIFIED: deletion finalized; full directory excludes account; sessions zero; audit identity preserved")
|
|
}
|