🐛 Allow phone reuse after account deletion while preserving audit identity
This commit is contained in:
parent
bc00467d24
commit
b8360eba13
@ -138,6 +138,8 @@ _Avoid_:删除意见(确认解决不删除任何历史记录)
|
||||
|
||||
## 账号与项目授权
|
||||
|
||||
**已删除账号身份**:保留原用户 ID、姓名、手机号和历史归属的不可重新启用记录。删除完成后手机号可用于创建新身份,新账号不继承旧账号的任务或历史;仅停用及删除未完成的账号继续占用手机号。
|
||||
|
||||
**账号角色**:一个账号只有一个角色。管理员独立;供应商管理员、标注员、质检审核员和最终验收员均归属一个供应商。
|
||||
|
||||
**项目成员**:账号参与项目的授权关系,生产职责继承账号角色。一个项目可以同时包含多个供应商,各供应商可以在该项目内处理其归属的任务;不能把项目成员角色当作额外账号权限。
|
||||
|
||||
72
cmd/account-phone-index/main.go
Normal file
72
cmd/account-phone-index/main.go
Normal file
@ -0,0 +1,72 @@
|
||||
// account-phone-index previews (default) or explicitly migrates user phone uniqueness.
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"flag"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"time"
|
||||
|
||||
"droboticflow/internal/store"
|
||||
"go.mongodb.org/mongo-driver/bson"
|
||||
"go.mongodb.org/mongo-driver/mongo"
|
||||
"go.mongodb.org/mongo-driver/mongo/options"
|
||||
)
|
||||
|
||||
func main() {
|
||||
if err := run(os.Args[1:], os.Stdout); err != nil {
|
||||
fmt.Fprintln(os.Stderr, "phone index maintenance failed:", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
}
|
||||
|
||||
func run(args []string, stdout io.Writer) error {
|
||||
flags := flag.NewFlagSet("account-phone-index", flag.ContinueOnError)
|
||||
database := flags.String("database", "", "exact database name (required)")
|
||||
apply := flags.Bool("apply", false, "create live-account unique index, then remove legacy phone_unique")
|
||||
if err := flags.Parse(args); err != nil {
|
||||
return err
|
||||
}
|
||||
if flags.NArg() != 0 {
|
||||
return fmt.Errorf("unexpected positional arguments")
|
||||
}
|
||||
uri := os.Getenv("MONGO_URI")
|
||||
if uri == "" || *database == "" {
|
||||
return fmt.Errorf("MONGO_URI and --database are required")
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Minute)
|
||||
defer cancel()
|
||||
client, err := mongo.Connect(ctx, options.Client().ApplyURI(uri))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer client.Disconnect(context.Background())
|
||||
db := client.Database(*database)
|
||||
col := db.Collection("users")
|
||||
cur, err := col.Indexes().List(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
var indexes []bson.M
|
||||
if err = cur.All(ctx, &indexes); err != nil {
|
||||
return err
|
||||
}
|
||||
deleted, err := col.CountDocuments(ctx, bson.M{"deletedAt": bson.M{"$type": "string", "$ne": ""}})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
preview := map[string]any{"database": *database, "apply": *apply, "existingIndexes": indexes, "deletedAccountsPreserved": deleted, "createIndex": "phone_live_unique", "dropIndex": "phone_unique", "businessRecordUpdates": 0}
|
||||
if err = json.NewEncoder(stdout).Encode(preview); err != nil {
|
||||
return err
|
||||
}
|
||||
if !*apply {
|
||||
return nil
|
||||
}
|
||||
if err = store.NewMongoStore(db).MigrateUserPhoneIndex(ctx); err != nil {
|
||||
return err
|
||||
}
|
||||
return json.NewEncoder(stdout).Encode(map[string]any{"completed": true, "database": *database})
|
||||
}
|
||||
76
cmd/account-phone-index/main_test.go
Normal file
76
cmd/account-phone-index/main_test.go
Normal file
@ -0,0 +1,76 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"fmt"
|
||||
"os"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"go.mongodb.org/mongo-driver/bson"
|
||||
"go.mongodb.org/mongo-driver/mongo"
|
||||
"go.mongodb.org/mongo-driver/mongo/options"
|
||||
)
|
||||
|
||||
func TestPreviewAndApplyPhoneIndexLocalMongo(t *testing.T) {
|
||||
if os.Getenv("ACCOUNT_PHONE_REUSE_LOCAL_MONGO") != "1" {
|
||||
t.Skip("isolated local Mongo only")
|
||||
}
|
||||
t.Setenv("MONGO_URI", "mongodb://127.0.0.1:27018/?directConnection=true")
|
||||
ctx, cancel := context.WithTimeout(t.Context(), time.Minute)
|
||||
defer cancel()
|
||||
client, err := mongo.Connect(ctx, options.Client().ApplyURI(os.Getenv("MONGO_URI")))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer client.Disconnect(context.Background())
|
||||
db := client.Database(fmt.Sprintf("phone_reuse_cli_test_%d", time.Now().UnixNano()))
|
||||
defer db.Drop(context.Background())
|
||||
col := db.Collection("users")
|
||||
if _, err = col.Indexes().CreateOne(ctx, mongo.IndexModel{Keys: bson.D{{Key: "phone", Value: 1}}, Options: options.Index().SetName("phone_unique").SetUnique(true)}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err = col.InsertOne(ctx, bson.M{"id": "audit", "phone": "13900000001", "deletedAt": "2026-10-21"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var before []bson.M
|
||||
cur, err := col.Indexes().List(ctx)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err = cur.All(ctx, &before); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var out bytes.Buffer
|
||||
if err = run([]string{"--database", db.Name()}, &out); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var after []bson.M
|
||||
cur, err = col.Indexes().List(ctx)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err = cur.All(ctx, &after); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(before) != len(after) || !strings.Contains(out.String(), `"apply":false`) {
|
||||
t.Fatal("preview mutated indexes or did not identify read-only mode")
|
||||
}
|
||||
if err = run([]string{"--database", db.Name(), "--apply"}, &out); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err = run([]string{"--database", db.Name(), "--apply"}, &out); err != nil {
|
||||
t.Fatalf("retry: %v", err)
|
||||
}
|
||||
if _, err = col.InsertOne(ctx, bson.M{"id": "replacement", "phone": "13900000001"}); err != nil {
|
||||
t.Fatalf("migration ineffective: %v", err)
|
||||
}
|
||||
if count, err := col.CountDocuments(ctx, bson.M{"id": "audit", "phone": "13900000001", "deletedAt": "2026-10-21"}); err != nil || count != 1 {
|
||||
t.Fatal("historical business record changed")
|
||||
}
|
||||
if _, err = col.InsertOne(ctx, bson.M{"id": "duplicate", "phone": "13900000001"}); !mongo.IsDuplicateKeyError(err) {
|
||||
t.Fatalf("unique protection removed: %v", err)
|
||||
}
|
||||
}
|
||||
43
docs/account-phone-reuse.zh-CN.md
Normal file
43
docs/account-phone-reuse.zh-CN.md
Normal file
@ -0,0 +1,43 @@
|
||||
# 删除账号后复用手机号
|
||||
|
||||
## 业务契约
|
||||
|
||||
账号删除完成后,旧用户 ID、姓名、原手机号、删除时间及历史任务归属继续保留。原身份不能重新启用,旧密码和旧会话失效。原手机号可创建一个全新账号,角色及供应商按正常创建权限校验;新账号不继承旧账号的任务、项目成员关系或历史产出。
|
||||
|
||||
仅停用账号不释放手机号。删除操作中途失败、尚未写入 `deletedAt` 的账号也继续占用手机号,须按既有删除重试流程处理。未删除账号的手机号在全平台唯一,跨组织也不允许重复。
|
||||
|
||||
手机号及旧邮箱登录兼容查询排除已删除身份。`GetUser(id)` 继续读取旧身份供审计;不能把手机号当成历史归属关联键。
|
||||
|
||||
## 实现与兼容范围
|
||||
|
||||
MemoryStore 与 MongoStore 使用相同的账号删除判断。Mongo 新索引 `phone_live_unique` 为 phone 的部分唯一索引,包含 `deletedAt` 缺失、null 或空字符串的记录;停用但未删除的账号仍在索引中。新索引冲突仍返回原有 phone 校验错误,前端显示“该手机号已被其他账号使用”。
|
||||
|
||||
应用启动只创建新索引,不自动移除历史 `phone_unique`。因此老数据库在显式迁移前仍会阻止删除后复用;仅部署代码不足以完成修复。新数据库直接使用新约束。
|
||||
|
||||
## 发布与索引迁移顺序
|
||||
|
||||
1. 按正式发布流程部署本修复,确认所有账号读写实例(含 API/processor/Worker)均使用新版查询和索引定义,旧实例已退出。此时旧索引仍保护全量记录。
|
||||
2. 从既有未跟踪配置取得 `MONGO_URI`。默认只读预览,显式指定数据库:
|
||||
|
||||
```sh
|
||||
go run ./cmd/account-phone-index --database <database>
|
||||
```
|
||||
|
||||
预览包含数据库名、现有索引定义、保留的已删除账号数量及计划操作;不输出手机号、密码或业务正文,不修改索引和业务记录。
|
||||
3. 将该数据库/索引变更作为独立迁移计划提交授权。取得明确授权后,才执行相同命令并增加 `--apply`。
|
||||
4. 工具先创建 `phone_live_unique`,成功后才移除旧 `phone_unique`;新索引构建失败就停止,不移除旧约束。整个过程不更新用户、任务或审核记录。中断后可重复执行;任一阶段都有唯一索引保护未删除身份。
|
||||
5. 线上采用只读验收;创建客户账号或执行其他写入测试须单独获得对应授权。客户之后可通过正常管理界面使用原手机号创建新账号。
|
||||
|
||||
原先已经完成删除的账号不需要补写或恢复;新索引自动排除它们。仍有其他未删除账号占用同一手机号时继续拒绝创建,不擅自合并身份。
|
||||
|
||||
## 回退边界
|
||||
|
||||
索引迁移前,可按原发布流程回退代码,旧索引仍在。迁移后,特别是原手机号已创建新账号时,不能直接恢复旧版手机号查询或旧 `phone_unique`:旧版可能查到已删除身份,旧全量唯一索引也可能因历史同手机号记录而构建失败。
|
||||
|
||||
需要回退时保留新版账号查询和新索引,优先前向修复;若必须完整退回,应先冻结账号写入、只读列出冲突并另行审批恢复计划。不得删除旧身份、改写历史手机号、转移历史任务或随意删除新账号来强行恢复旧约束。
|
||||
|
||||
## 验证
|
||||
|
||||
新增 API 契约覆盖:删除后同手机号创建供应商管理员、新旧用户 ID 分离、新密码登录、旧密码拒绝、停用账号继续占号、历史任务及删除记录不变。
|
||||
|
||||
本地真实 Mongo 隔离合成库覆盖:旧索引仍在时的失败、新索引先建后删旧、重复迁移及重新初始化、缺失/null/空删除标记兼容、多次删除后复用、8 路并发仅 1 次创建成功、已删除身份不能复活。迁移工具另验证默认预览不改索引,显式执行不改历史用户记录。
|
||||
118
internal/api/account_phone_reuse_test.go
Normal file
118
internal/api/account_phone_reuse_test.go
Normal file
@ -0,0 +1,118 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"droboticflow/internal/domain"
|
||||
"droboticflow/internal/store"
|
||||
|
||||
"go.mongodb.org/mongo-driver/mongo"
|
||||
"go.mongodb.org/mongo-driver/mongo/options"
|
||||
)
|
||||
|
||||
func accountPhoneReuseContract(t *testing.T, ds store.Store) {
|
||||
t.Helper()
|
||||
accountDeleteContract(t, ds)
|
||||
users, err := ds.ListUsers(t.Context())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var old, admin, disabled domain.UserRecord
|
||||
for _, u := range users {
|
||||
if u.DeletedAt != "" {
|
||||
old = u
|
||||
}
|
||||
if u.Role == domain.UserRoleAdmin {
|
||||
admin = u
|
||||
}
|
||||
if u.DeletedAt == "" && u.Status == domain.UserStatusDisabled {
|
||||
disabled = u
|
||||
}
|
||||
}
|
||||
if old.ID == "" || admin.ID == "" || disabled.ID == "" {
|
||||
t.Fatal("missing contract identities")
|
||||
}
|
||||
h := NewHandler(ds, nil)
|
||||
cookie := loginSession(t, h, admin.Phone, "delete-test-password")
|
||||
create := func(phone string) *httptest.ResponseRecorder {
|
||||
body, _ := json.Marshal(map[string]any{"name": "Replacement manager", "phone": phone, "role": domain.UserRoleSupplierManager, "supplierId": old.SupplierID, "password": "replacement-test-password"})
|
||||
return serveJSONWithCookie(h, http.MethodPost, "/api/users", body, cookie)
|
||||
}
|
||||
if rr := create(disabled.Phone); rr.Code != 400 {
|
||||
t.Fatalf("disabled identity released its phone: %d %s", rr.Code, rr.Body.String())
|
||||
}
|
||||
rr := create(old.Phone)
|
||||
if rr.Code != 201 {
|
||||
t.Fatalf("deleted phone not reusable: %d %s", rr.Code, rr.Body.String())
|
||||
}
|
||||
var replacement domain.UserRecord
|
||||
if err := json.Unmarshal(rr.Body.Bytes(), &replacement); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if replacement.ID == old.ID || replacement.Role != domain.UserRoleSupplierManager {
|
||||
t.Fatal("old audit identity reused")
|
||||
}
|
||||
if rr := create(old.Phone); rr.Code != 400 {
|
||||
t.Fatalf("duplicate live account admitted: %d", rr.Code)
|
||||
}
|
||||
found, err := ds.FindUserByPhone(t.Context(), old.Phone)
|
||||
if err != nil || found == nil || found.ID != replacement.ID {
|
||||
t.Fatalf("login lookup selected old audit identity: %+v %v", found, err)
|
||||
}
|
||||
newCookie := loginSession(t, h, old.Phone, "replacement-test-password")
|
||||
rr = serveJSONWithCookie(h, http.MethodGet, "/api/auth/me", nil, newCookie)
|
||||
if rr.Code != 200 {
|
||||
t.Fatalf("replacement login failed: %d", rr.Code)
|
||||
}
|
||||
body, _ := json.Marshal(map[string]string{"phone": old.Phone, "password": "delete-test-password"})
|
||||
rr = serveJSONWithCookie(h, http.MethodPost, "/api/auth/login", body, nil)
|
||||
if rr.Code != 401 {
|
||||
t.Fatalf("old password admitted: %d", rr.Code)
|
||||
}
|
||||
saved, err := ds.GetUser(t.Context(), old.ID)
|
||||
if err != nil || saved == nil || saved.DeletedAt != old.DeletedAt || saved.Phone != old.Phone || saved.PasswordHash != "" {
|
||||
t.Fatal("old audit identity changed")
|
||||
}
|
||||
historical, err := ds.GetHumanItem(t.Context(), "delete-"+string(domain.HumanItemAccepted))
|
||||
if err != nil || historical.AssignedUserID != old.ID {
|
||||
t.Fatal("old history transferred to new account")
|
||||
}
|
||||
members, err := ds.ListProjectMembers(t.Context(), old.OrganizationID, "")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, m := range members {
|
||||
if m.UserID == old.ID {
|
||||
t.Fatal("deleted membership revived")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestDeletedAccountPhoneReuse(t *testing.T) { accountPhoneReuseContract(t, store.NewMemoryStore()) }
|
||||
|
||||
func TestDeletedAccountPhoneReuseMongo(t *testing.T) {
|
||||
if os.Getenv("ACCOUNT_PHONE_REUSE_LOCAL_MONGO") != "1" {
|
||||
t.Skip("isolated local Mongo only")
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(t.Context(), time.Minute)
|
||||
defer cancel()
|
||||
client, err := mongo.Connect(ctx, options.Client().ApplyURI("mongodb://127.0.0.1:27018/?directConnection=true"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer client.Disconnect(context.Background())
|
||||
db := client.Database(fmt.Sprintf("phone_reuse_api_test_%d", time.Now().UnixNano()))
|
||||
defer db.Drop(context.Background())
|
||||
ds := store.NewMongoStore(db)
|
||||
if err = ds.MigrateUserPhoneIndex(ctx); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
accountPhoneReuseContract(t, ds)
|
||||
}
|
||||
@ -243,7 +243,7 @@ func (store *MemoryStore) ensureOrganizationSlugAvailableLocked(slug string, cur
|
||||
return nil
|
||||
}
|
||||
|
||||
// ensureUserPhoneAvailableLocked enforces phone uniqueness across accounts.
|
||||
// ensureUserPhoneAvailableLocked enforces phone uniqueness across undeleted accounts.
|
||||
// Phone comparison is exact (no case-folding, unlike the removed email
|
||||
// field). An empty phone is treated as available since some code paths
|
||||
// (see upsertUser) validate presence separately; in practice every account
|
||||
@ -255,6 +255,9 @@ func (store *MemoryStore) ensureUserPhoneAvailableLocked(phone string, currentID
|
||||
}
|
||||
normalizedCurrentID := strings.TrimSpace(currentID)
|
||||
for _, item := range store.users {
|
||||
if item.DeletedAt != "" {
|
||||
continue
|
||||
}
|
||||
if strings.TrimSpace(item.Phone) != normalizedPhone {
|
||||
continue
|
||||
}
|
||||
@ -2289,7 +2292,7 @@ func (store *MemoryStore) FindUserByPhone(_ context.Context, phone string) (*dom
|
||||
defer store.mu.Unlock()
|
||||
normalizedPhone := strings.TrimSpace(phone)
|
||||
for _, item := range store.users {
|
||||
if item.Phone == normalizedPhone && normalizedPhone != "" {
|
||||
if item.DeletedAt == "" && item.Phone == normalizedPhone && normalizedPhone != "" {
|
||||
cloned := clone(item)
|
||||
return &cloned, nil
|
||||
}
|
||||
@ -2307,7 +2310,7 @@ func (store *MemoryStore) FindUserByLegacyEmail(_ context.Context, email string)
|
||||
return nil, nil
|
||||
}
|
||||
for _, item := range store.users {
|
||||
if strings.ToLower(strings.TrimSpace(item.LegacyEmail)) == normalizedEmail {
|
||||
if item.DeletedAt == "" && strings.ToLower(strings.TrimSpace(item.LegacyEmail)) == normalizedEmail {
|
||||
cloned := clone(item)
|
||||
return &cloned, nil
|
||||
}
|
||||
|
||||
@ -2218,11 +2218,11 @@ func (store *MongoStore) GetUser(ctx context.Context, id string) (*domain.UserRe
|
||||
return &item, nil
|
||||
}
|
||||
|
||||
// FindUserByPhone looks up a user by phone number. Phone numbers are not
|
||||
// FindUserByPhone looks up an undeleted login identity by phone number. Phone numbers are not
|
||||
// case-folded (unlike the removed email field).
|
||||
func (store *MongoStore) FindUserByPhone(ctx context.Context, phone string) (*domain.UserRecord, error) {
|
||||
var item domain.UserRecord
|
||||
err := store.users.FindOne(ctx, bson.M{"phone": strings.TrimSpace(phone)}).Decode(&item)
|
||||
err := store.users.FindOne(ctx, bson.M{"phone": strings.TrimSpace(phone), "deletedAt": bson.M{"$in": bson.A{"", nil}}}).Decode(&item)
|
||||
if err == mongo.ErrNoDocuments {
|
||||
return nil, nil
|
||||
}
|
||||
@ -2237,7 +2237,7 @@ func (store *MongoStore) FindUserByPhone(ctx context.Context, phone string) (*do
|
||||
// callers must not expose it as a current account identifier.
|
||||
func (store *MongoStore) FindUserByLegacyEmail(ctx context.Context, email string) (*domain.UserRecord, error) {
|
||||
var item domain.UserRecord
|
||||
err := store.users.FindOne(ctx, bson.M{"email": strings.ToLower(strings.TrimSpace(email))}).Decode(&item)
|
||||
err := store.users.FindOne(ctx, bson.M{"email": strings.ToLower(strings.TrimSpace(email)), "deletedAt": bson.M{"$in": bson.A{"", nil}}}).Decode(&item)
|
||||
if err == mongo.ErrNoDocuments {
|
||||
return nil, nil
|
||||
}
|
||||
@ -2396,7 +2396,7 @@ func (store *MongoStore) upsertUser(ctx context.Context, item domain.UserRecord,
|
||||
// (e.g. a pre-migration email_unique index left over in an older database)
|
||||
// would otherwise be misreported to the caller as "phone must be unique".
|
||||
func isPhoneUniqueDuplicateKeyError(err error) bool {
|
||||
return mongo.IsDuplicateKeyError(err) && strings.Contains(err.Error(), "phone_unique")
|
||||
return mongo.IsDuplicateKeyError(err) && (strings.Contains(err.Error(), "phone_unique") || strings.Contains(err.Error(), liveUserPhoneIndex))
|
||||
}
|
||||
|
||||
func (store *MongoStore) CreateSession(ctx context.Context, item domain.SessionRecord) (*domain.SessionRecord, error) {
|
||||
|
||||
@ -302,7 +302,7 @@ func (store *MongoStore) EnsureIndexes(ctx context.Context) error {
|
||||
},
|
||||
store.users: {
|
||||
uniqueIndex("id_unique", bson.D{{Key: "id", Value: 1}}),
|
||||
uniqueIndex("phone_unique", bson.D{{Key: "phone", Value: 1}}),
|
||||
liveUserPhoneIndexModel(),
|
||||
index("organizationId_createdAt", bson.D{{Key: "organizationId", Value: 1}, {Key: "createdAt", Value: 1}}),
|
||||
},
|
||||
store.sessions: {
|
||||
|
||||
33
internal/store/user_phone_index.go
Normal file
33
internal/store/user_phone_index.go
Normal file
@ -0,0 +1,33 @@
|
||||
package store
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"go.mongodb.org/mongo-driver/bson"
|
||||
"go.mongodb.org/mongo-driver/mongo"
|
||||
"go.mongodb.org/mongo-driver/mongo/options"
|
||||
)
|
||||
|
||||
const liveUserPhoneIndex = "phone_live_unique"
|
||||
|
||||
// Missing, null and legacy empty deletion markers all mean not deleted.
|
||||
// Disabled accounts are deliberately included: disabling does not release login identity.
|
||||
func liveUserPhoneIndexModel() mongo.IndexModel {
|
||||
return mongo.IndexModel{
|
||||
Keys: bson.D{{Key: "phone", Value: 1}},
|
||||
Options: options.Index().SetName(liveUserPhoneIndex).SetUnique(true).SetPartialFilterExpression(bson.M{
|
||||
"$or": bson.A{bson.M{"deletedAt": nil}, bson.M{"deletedAt": ""}},
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
// MigrateUserPhoneIndex changes constraints only. Build the new unique index
|
||||
// before dropping the old one, so concurrent creates never have an unguarded gap.
|
||||
// This explicit maintenance action is NOT run by application startup: existing
|
||||
// deployments require a separately approved database migration after code rollout.
|
||||
func (s *MongoStore) MigrateUserPhoneIndex(ctx context.Context) error {
|
||||
if err := ensureCollectionIndexes(ctx, s.users, []mongo.IndexModel{liveUserPhoneIndexModel()}); err != nil {
|
||||
return err
|
||||
}
|
||||
return dropObsoleteIndexes(ctx, s.users, "phone_unique")
|
||||
}
|
||||
133
internal/store/user_phone_index_test.go
Normal file
133
internal/store/user_phone_index_test.go
Normal file
@ -0,0 +1,133 @@
|
||||
package store
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"droboticflow/internal/domain"
|
||||
"go.mongodb.org/mongo-driver/bson"
|
||||
"go.mongodb.org/mongo-driver/mongo"
|
||||
"go.mongodb.org/mongo-driver/mongo/options"
|
||||
)
|
||||
|
||||
func TestUserPhoneIndexMigrationMongo(t *testing.T) {
|
||||
if os.Getenv("ACCOUNT_PHONE_REUSE_LOCAL_MONGO") != "1" {
|
||||
t.Skip("isolated local Mongo only")
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(t.Context(), time.Minute)
|
||||
defer cancel()
|
||||
client, err := mongo.Connect(ctx, options.Client().ApplyURI("mongodb://127.0.0.1:27018/?directConnection=true"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer client.Disconnect(context.Background())
|
||||
db := client.Database(fmt.Sprintf("phone_reuse_test_%d", time.Now().UnixNano()))
|
||||
defer db.Drop(context.Background())
|
||||
col := db.Collection("users")
|
||||
if err = ensureCollectionIndexes(ctx, col, []mongo.IndexModel{uniqueIndex("id_unique", bson.D{{Key: "id", Value: 1}}), uniqueIndex("phone_unique", bson.D{{Key: "phone", Value: 1}})}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
docs := []any{
|
||||
bson.M{"id": "deleted", "phone": "13900000001", "deletedAt": "2026-10-21T00:00:00Z", "status": "disabled"},
|
||||
bson.M{"id": "missing-marker", "phone": "13900000002"},
|
||||
bson.M{"id": "null-marker", "phone": "13900000003", "deletedAt": nil},
|
||||
bson.M{"id": "empty-marker", "phone": "13900000004", "deletedAt": ""},
|
||||
bson.M{"id": "disabled", "phone": "13900000005", "status": "disabled"},
|
||||
}
|
||||
if _, err = col.InsertMany(ctx, docs); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
// A replacement-index definition conflict must leave the old constraint intact.
|
||||
if _, err = col.Indexes().CreateOne(ctx, index(liveUserPhoneIndex, bson.D{{Key: "diagnostic", Value: 1}})); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err = NewMongoStore(db).MigrateUserPhoneIndex(ctx); err == nil {
|
||||
t.Fatal("conflicting replacement index unexpectedly admitted")
|
||||
}
|
||||
if _, err = col.InsertOne(ctx, bson.M{"id": "failed-migration", "phone": "13900000001"}); !mongo.IsDuplicateKeyError(err) {
|
||||
t.Fatalf("failed migration removed legacy protection: %v", err)
|
||||
}
|
||||
if _, err = col.Indexes().DropOne(ctx, liveUserPhoneIndex); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// Startup builds the replacement without silently removing the legacy index.
|
||||
if err = ensureCollectionIndexes(ctx, col, []mongo.IndexModel{liveUserPhoneIndexModel()}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err = col.InsertOne(ctx, bson.M{"id": "before-migration", "phone": "13900000001"}); !mongo.IsDuplicateKeyError(err) {
|
||||
t.Fatalf("legacy constraint unexpectedly removed: %v", err)
|
||||
}
|
||||
s := NewMongoStore(db)
|
||||
if err = s.MigrateUserPhoneIndex(ctx); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err = s.MigrateUserPhoneIndex(ctx); err != nil {
|
||||
t.Fatalf("retry migration: %v", err)
|
||||
}
|
||||
replacement, err := s.CreateUser(ctx, domain.CreateUserInput{Name: "New", Phone: "13900000001", Role: domain.UserRoleAdmin})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, phone := range []string{"13900000001", "13900000002", "13900000003", "13900000004", "13900000005"} {
|
||||
_, err = s.CreateUser(ctx, domain.CreateUserInput{Name: "Duplicate", Phone: phone, Role: domain.UserRoleAdmin})
|
||||
if !errors.Is(err, ErrDuplicateUserPhone) {
|
||||
t.Fatalf("live/disabled phone %s not guarded: %v", phone, err)
|
||||
}
|
||||
}
|
||||
old, err := s.GetUser(ctx, "deleted")
|
||||
if err != nil || old == nil || old.Phone != "13900000001" || old.DeletedAt == "" {
|
||||
t.Fatal("audit identity lost")
|
||||
}
|
||||
old.DeletedAt = ""
|
||||
old.Status = domain.UserStatusActive
|
||||
if err = s.UpsertUser(ctx, *old); !errors.Is(err, ErrAccountDeleted) {
|
||||
t.Fatalf("resurrection admitted: %v", err)
|
||||
}
|
||||
// New store instance reads persisted live identity instead of the audit record.
|
||||
restarted := NewMongoStore(db)
|
||||
if err = ensureCollectionIndexes(ctx, col, []mongo.IndexModel{liveUserPhoneIndexModel()}); err != nil {
|
||||
t.Fatalf("restart index creation: %v", err)
|
||||
}
|
||||
found, err := restarted.FindUserByPhone(ctx, replacement.Phone)
|
||||
if err != nil || found == nil || found.ID != replacement.ID {
|
||||
t.Fatalf("restart lookup: %+v %v", found, err)
|
||||
}
|
||||
var successes, duplicates atomic.Int32
|
||||
var wg sync.WaitGroup
|
||||
for i := 0; i < 8; i++ {
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
_, err := s.CreateUser(ctx, domain.CreateUserInput{Name: "Concurrent", Phone: "13900000006", Role: domain.UserRoleAdmin})
|
||||
if err == nil {
|
||||
successes.Add(1)
|
||||
} else if errors.Is(err, ErrDuplicateUserPhone) {
|
||||
duplicates.Add(1)
|
||||
} else {
|
||||
t.Errorf("create: %v", err)
|
||||
}
|
||||
}()
|
||||
}
|
||||
wg.Wait()
|
||||
if successes.Load() != 1 || duplicates.Load() != 7 {
|
||||
t.Fatalf("duplicate guard: success=%d conflict=%d", successes.Load(), duplicates.Load())
|
||||
}
|
||||
// Multiple historical audit identities may carry the same phone.
|
||||
live, _ := s.GetUser(ctx, replacement.ID)
|
||||
expected := *live
|
||||
live.DeletedAt = "2026-10-21T01:00:00Z"
|
||||
live.Status = domain.UserStatusDisabled
|
||||
if err = s.UpdateUser(ctx, *live, expected); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err = s.CreateUser(ctx, domain.CreateUserInput{Name: "Third identity", Phone: replacement.Phone, Role: domain.UserRoleAdmin}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
@ -14,6 +14,7 @@ export function userErrorMessage(value, fallback = "操作暂时未完成") {
|
||||
const status = typeof value === "object" ? Number(value?.status) : 0;
|
||||
const source = `${code} ${text}`;
|
||||
const rules = [
|
||||
[/phone must be unique/i, "该手机号已被其他账号使用"],
|
||||
[
|
||||
/slice_materialization_required|all Capture slices must be materialized/i,
|
||||
"切片尚未完成生成,请先确认切片;已有标注会保留",
|
||||
|
||||
@ -80,3 +80,11 @@ test("pure-instruction copy stays visible instead of masking as 操作暂时未
|
||||
// Fact + appended instruction keeps today's behaviour (fact only).
|
||||
assert.equal(userErrorMessage("手机号格式不正确,请重新填写。"), "手机号格式不正确。");
|
||||
});
|
||||
|
||||
test("phone uniqueness errors identify the conflicting account field", () => {
|
||||
const error = Object.assign(new Error("Validation failed (phone: phone must be unique)"), {
|
||||
status: 400,
|
||||
issues: [{ field: "phone", message: "phone must be unique" }],
|
||||
});
|
||||
assert.equal(getActionErrorMessage(error, "保存用户失败"), "该手机号已被其他账号使用");
|
||||
});
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user