droboticflow/internal/api/account_hierarchy_test.go
eust-w d4c768475b ✨ Switch login to phone-based lookup (ticket 03)
- handleAuthLogin now authenticates via store.FindUserByPhone instead of
  FindUserByEmail; the login/bootstrap-super-admin request payload field
  is now `phone`. Old email addresses are no longer valid login credentials.
- bootstrap-super-admin now validates phone format (isValidChinaMobilePhone)
  instead of net/mail.ParseAddress; net/mail is fully removed from
  internal/api.
- Same-class gap fix: handleAdminOrganizationUsersCreate (the legacy
  per-organization admin endpoint, not touched by ticket 02) still created
  users by email only, which would have left them unable to log in under
  the new phone-only login. Switched it to phone validation/uniqueness too,
  and removed the now-dead normalizeUserInput/validateUserEmailAvailable
  helpers.
- Frontend: authApi.login, UserContext's login signature, and
  UserBootstrapPanel's submit handler now send `phone` instead of `email`
  (the form/labels were already phone-based from ticket 04).
- Updated ~20 Go test files whose fixtures/helpers logged in via
  user.Email; adminCreateUser/loginSession/bootstrapSuperAdminSession now
  work in terms of phone (deterministically derived from existing
  email-shaped test identities via testPhoneFromSeed, to avoid rewriting
  every call site). Added internal/api/auth_phone_login_test.go covering
  phone login success/failure and old-email rejection.

go test ./internal/api/... and npm run test:frontend match their
pre-ticket baselines exactly (75 Go failures / 599 frontend tests with
586 pass, 13 fail) by failing test name, not just count.
2026-09-22 14:04:59 +08:00

131 lines
5.8 KiB
Go

package api
import (
"encoding/json"
"net/http"
"testing"
"droboticflow/internal/domain"
"droboticflow/internal/store"
)
func TestAccountHierarchySupplierLifecycleAndSingleRole(t *testing.T) {
t.Setenv("DROBOTICFLOW_REQUIRE_SESSION_AUTH", "true")
ds := store.NewMemoryStore()
h := NewHandler(ds, nil)
root := bootstrapSuperAdminSession(t, h)
org := adminCreateOrganization(t, h, root, "Hierarchy", "hierarchy")
admin := adminCreateUser(t, h, root, org.ID, "Admin", "hier-admin@example.com", domain.UserRoleAdmin, "test-password")
if admin.SupplierID != "" {
t.Fatal("administrator bound to supplier")
}
ac := loginSession(t, h, admin.Phone, "test-password")
create := func(name string) domain.SupplierRecord {
t.Helper()
body, _ := json.Marshal(map[string]string{"name": name})
r := serveJSONWithCookie(h, "POST", "/api/suppliers", body, ac)
if r.Code != 201 {
t.Fatalf("create supplier %d %s", r.Code, r.Body.String())
}
var s domain.SupplierRecord
_ = json.Unmarshal(r.Body.Bytes(), &s)
return s
}
supplier := create("Supplier A")
if r := serveJSONWithCookie(h, "POST", "/api/suppliers", []byte(`{"name":" Supplier A "}`), ac); r.Code != 409 {
t.Fatal("duplicate supplier allowed")
}
r := serveJSONWithCookie(h, "PUT", "/api/suppliers/"+supplier.ID, []byte(`{"name":"Renamed"}`), ac)
if r.Code != 200 {
t.Fatalf("rename %s", r.Body.String())
}
user := adminCreateUser(t, h, root, org.ID, "Worker", "hier-worker@example.com", domain.UserRoleAnnotator, "test-password", supplier.ID)
manager := adminCreateUser(t, h, root, org.ID, "Manager", "hier-manager@example.com", domain.UserRoleSupplierManager, "test-password", supplier.ID)
mc := loginSession(t, h, manager.Phone, "test-password")
for _, method := range []string{"PUT", "DELETE"} {
r = serveJSONWithCookie(h, method, "/api/suppliers/"+supplier.ID, []byte(`{"name":"Denied"}`), mc)
if r.Code != 403 {
t.Fatalf("manager supplier mutation %d", r.Code)
}
}
r = serveJSONWithCookie(h, "DELETE", "/api/suppliers/"+supplier.ID, nil, ac)
if r.Code != 409 || !jsonContains(r.Body.String(), "账号") {
t.Fatalf("used supplier deletion %s", r.Body.String())
}
def, _ := ds.EnsureDefaultSupplier(t.Context(), org.ID)
for _, method := range []string{"PUT", "DELETE"} {
r = serveJSONWithCookie(h, method, "/api/suppliers/"+def.ID, []byte(`{"name":"Changed"}`), ac)
if r.Code != 409 {
t.Fatal("default supplier mutated")
}
}
empty := create("Empty")
r = serveJSONWithCookie(h, "DELETE", "/api/suppliers/"+empty.ID, nil, ac)
if r.Code != 204 {
t.Fatalf("empty delete %s", r.Body.String())
}
r = serveJSONWithCookie(h, "GET", "/api/suppliers", nil, ac)
if jsonContains(r.Body.String(), empty.ID) {
t.Fatal("deleted supplier still selectable")
}
r = serveJSONWithCookie(h, "POST", "/api/users", []byte(`{"name":"Extra","email":"extra@example.com","role":"annotator","password":"test-password","supplierId":"`+supplier.ID+`","defaultProjectRoles":["quality_reviewer"]}`), ac)
if r.Code != 400 {
t.Fatal("default role allowed")
}
project, _ := ds.CreateProject(t.Context(), domain.CreateProjectInput{OrganizationID: org.ID, Name: "Single role"})
r = serveJSONWithCookie(h, "POST", "/api/projects/"+project.ID+"/members", []byte(`{"userId":"`+user.ID+`"}`), ac)
if r.Code != 201 {
t.Fatalf("inherit role %s", r.Body.String())
}
var member domain.ProjectMemberRecord
_ = json.Unmarshal(r.Body.Bytes(), &member)
if len(member.Roles) != 1 || member.Roles[0] != domain.AnnotationRoleAnnotator {
t.Fatal("wrong inherited role")
}
r = serveJSONWithCookie(h, "PATCH", "/api/projects/"+project.ID+"/members/"+member.ID, []byte(`{"roles":["annotator","quality_reviewer"]}`), ac)
if r.Code != 400 {
t.Fatal("multiple project roles allowed")
}
// Simulate existing historical multi-role records without migrating them.
member.Roles = []domain.AnnotationAssignmentRole{domain.AnnotationRoleAnnotator, domain.AnnotationRoleQualityReviewer}
_ = ds.UpsertProjectMember(t.Context(), member)
s := &server{store: ds}
members, err := s.annotationMembershipsForUser(t.Context(), org.ID, project.ID, user.ID)
if err != nil || len(members) != 1 || members[0].Role != domain.AnnotationRoleAnnotator {
t.Fatalf("legacy additional permission granted: %#v %v", members, err)
}
r = serveJSONWithCookie(h, "GET", "/api/users/hierarchy-audit", nil, ac)
if r.Code != 200 || !jsonContains(r.Body.String(), "历史项目角色与账号角色不一致") {
t.Fatalf("audit missing %s", r.Body.String())
}
old, _ := ds.GetProjectMember(t.Context(), member.ID)
if len(old.Roles) != 2 {
t.Fatal("audit changed history")
}
r = serveJSONWithCookie(h, "GET", "/api/users/hierarchy-audit", nil, mc)
if r.Code != 403 {
t.Fatal("manager read global audit")
}
_ = ds.UpsertHumanItem(t.Context(), domain.HumanItemRecord{ID: "pending-hierarchy", OrganizationID: org.ID, ProjectID: project.ID, SupplierID: supplier.ID, AssignedUserID: user.ID, Status: domain.HumanItemInProgress, Version: 1})
r = serveJSONWithCookie(h, "PUT", "/api/users/"+user.ID, []byte(`{"role":"quality_reviewer"}`), ac)
if r.Code != 409 {
t.Fatal("changed role with pending work")
}
item, _ := ds.GetHumanItem(t.Context(), "pending-hierarchy")
item.Status = domain.HumanItemAccepted
_ = ds.UpsertHumanItem(t.Context(), *item)
r = serveJSONWithCookie(h, "PUT", "/api/users/"+user.ID, []byte(`{"role":"quality_reviewer"}`), ac)
if r.Code != 200 {
t.Fatalf("idle role update %s", r.Body.String())
}
members, _ = s.annotationMembershipsForUser(t.Context(), org.ID, project.ID, user.ID)
if len(members) != 1 || members[0].Role != domain.AnnotationRoleQualityReviewer {
t.Fatal("project retained prior production permission")
}
// No raw password fields in read-only report.
if jsonContains(r.Body.String(), "passwordHash") {
t.Fatal("password leak")
}
_ = http.StatusOK
}