1
0
forked from baron/baron-sso

Implement tenant import and RP auto login policies

This commit is contained in:
2026-04-30 15:45:34 +09:00
parent 24807eab0f
commit f7e4d43b16
76 changed files with 5307 additions and 441 deletions

View File

@@ -0,0 +1,156 @@
import { expect, test } from "@playwright/test";
test.describe("Tenant Allowed Domains", () => {
test.beforeEach(async ({ page }) => {
await page.addInitScript(() => {
window.localStorage.setItem("locale", "ko");
window.localStorage.setItem("admin_session", "fake-token");
window.localStorage.setItem("RoleSwitcher-Collapsed", "true");
(
window as Window & typeof globalThis & { _IS_TEST_MODE?: boolean }
)._IS_TEST_MODE = true;
const authority = "http://localhost:5000/oidc";
const client_id = "adminfront";
const key = `oidc.user:${authority}:${client_id}`;
window.localStorage.setItem(
key,
JSON.stringify({
access_token: "fake-token",
token_type: "Bearer",
profile: { sub: "admin-user", name: "Admin", role: "super_admin" },
expires_at: Math.floor(Date.now() / 1000) + 36000,
}),
);
});
await page.route("**/oidc/**", async (route) => {
await route.fulfill({ json: { issuer: "http://localhost:5000/oidc" } });
});
});
test("adds samaneng.com to the current tenant after duplicate warning confirmation", async ({
page,
}) => {
let savedPayload:
| {
domains?: string[];
forceDomainConflicts?: string[];
}
| undefined;
await page.route("**/api/v1/**", async (route) => {
const url = route.request().url();
const method = route.request().method();
const headers = { "Access-Control-Allow-Origin": "*" };
if (url.includes("/user/me")) {
return route.fulfill({
json: {
id: "admin-user",
name: "Admin",
role: "super_admin",
manageableTenants: [],
},
headers,
});
}
if (url.includes("/admin/tenants/current") && method === "GET") {
return route.fulfill({
json: {
id: "current",
name: "현재 테넌트",
slug: "current",
type: "COMPANY",
description: "",
status: "active",
domains: [],
memberCount: 0,
createdAt: "",
updatedAt: "",
},
headers,
});
}
if (url.includes("/admin/tenants/current") && method === "PUT") {
savedPayload = route.request().postDataJSON();
return route.fulfill({
json: {
id: "current",
name: "현재 테넌트",
slug: "current",
type: "COMPANY",
description: "",
status: "active",
domains: savedPayload?.domains ?? [],
memberCount: 0,
createdAt: "",
updatedAt: "",
},
headers,
});
}
if (url.includes("/admin/tenants")) {
return route.fulfill({
json: {
items: [
{
id: "current",
name: "현재 테넌트",
slug: "current",
type: "COMPANY",
description: "",
status: "active",
domains: [],
memberCount: 0,
createdAt: "",
updatedAt: "",
},
{
id: "existing",
name: "한맥가족",
slug: "hanmac-family",
type: "COMPANY",
description: "",
status: "active",
domains: ["samaneng.com"],
memberCount: 0,
createdAt: "",
updatedAt: "",
},
],
total: 2,
limit: 1000,
offset: 0,
},
headers,
});
}
return route.fulfill({ json: {}, headers });
});
await page.goto("/tenants/current");
await page.locator("#tenant-domains").fill("samaneng.com");
await page.keyboard.press("Space");
await expect(
page.getByText(
"samaneng.com 도메인은 한맥가족 테넌트에 이미 설정되어 있습니다. 그래도 현재 테넌트에도 추가하시겠습니까?",
),
).toBeVisible();
await page.getByRole("button", { name: "계속 진행" }).click();
await expect(page.getByText("samaneng.com")).toBeVisible();
await page.getByRole("button", { name: "저장" }).click();
await expect.poll(() => savedPayload).toMatchObject({
domains: ["samaneng.com"],
forceDomainConflicts: ["samaneng.com"],
});
});
});

View File

@@ -0,0 +1,124 @@
import { expect, test } from "@playwright/test";
test.describe("Tenant Schema Management", () => {
test.beforeEach(async ({ page }) => {
await page.addInitScript(() => {
window.localStorage.setItem("locale", "ko");
window.localStorage.setItem("admin_session", "fake-token");
window.localStorage.setItem("RoleSwitcher-Collapsed", "true");
(
window as Window & typeof globalThis & { _IS_TEST_MODE?: boolean }
)._IS_TEST_MODE = true;
const authority = "http://localhost:5000/oidc";
const client_id = "adminfront";
const key = `oidc.user:${authority}:${client_id}`;
const authData = {
access_token: "fake-token",
token_type: "Bearer",
profile: { sub: "admin-user", name: "Admin", role: "super_admin" },
expires_at: Math.floor(Date.now() / 1000) + 36000,
};
window.localStorage.setItem(key, JSON.stringify(authData));
});
await page.route("**/oidc/**", async (route) => {
await route.fulfill({ json: { issuer: "http://localhost:5000/oidc" } });
});
});
test("should force indexed when schema field is used as login ID", async ({
page,
}) => {
let savedConfig: Record<string, unknown> | undefined;
await page.route("**/api/v1/**", async (route) => {
const url = route.request().url();
const method = route.request().method();
const headers = { "Access-Control-Allow-Origin": "*" };
if (url.includes("/user/me")) {
return route.fulfill({
json: {
id: "admin-user",
name: "Admin",
role: "super_admin",
manageableTenants: [],
},
headers,
});
}
if (url.includes("/admin/tenants/t-1") && method === "GET") {
return route.fulfill({
json: {
id: "t-1",
name: "Test Tenant",
slug: "test-tenant",
type: "COMPANY",
status: "active",
config: { userSchema: [] },
},
headers,
});
}
if (url.includes("/admin/tenants/t-1") && method === "PUT") {
const payload = route.request().postDataJSON() as {
config?: Record<string, unknown>;
};
savedConfig = payload.config;
return route.fulfill({
json: {
id: "t-1",
name: "Test Tenant",
slug: "test-tenant",
type: "COMPANY",
status: "active",
config: savedConfig,
},
headers,
});
}
return route.fulfill({ json: { items: [], total: 0 }, headers });
});
await page.goto("/tenants/t-1/schema");
await expect(
page.getByText(/사용자 스키마 확장|User Schema Extension/),
).toBeVisible();
await page.getByRole("button", { name: /필드 추가/ }).click();
await page
.getByPlaceholder(/예: employee_id|e\.g\. employee_id/)
.fill("emp_no");
await page.getByPlaceholder("예: 사번").fill("사번");
const indexedCheckbox = page.getByLabel("검색 인덱스 필요");
await expect(indexedCheckbox).not.toBeChecked();
await expect(indexedCheckbox).toBeEnabled();
await page.getByLabel("로그인 ID로 사용").check();
await expect(indexedCheckbox).toBeChecked();
await expect(indexedCheckbox).toBeDisabled();
await page
.getByRole("button", { name: /변경사항 저장|스키마 저장|Save/ })
.click();
await expect
.poll(() => savedConfig)
.toMatchObject({
userSchema: [
{
key: "emp_no",
label: "사번",
type: "text",
indexed: true,
isLoginId: true,
},
],
});
});
});

View File

@@ -121,6 +121,7 @@ test.describe("Tenants Management", () => {
page,
}) => {
let exportRequested = false;
let exportUrl = "";
let importRequested = false;
let importBody = "";
@@ -131,6 +132,7 @@ test.describe("Tenants Management", () => {
if (url.includes("/export")) {
exportRequested = true;
exportUrl = url;
return route.fulfill({
body: "tenant_id,name,type,parent_tenant_id,slug,memo,email_domain\n",
contentType: "text/csv",
@@ -191,6 +193,7 @@ test.describe("Tenants Management", () => {
await page.getByTestId("tenant-export-btn").click();
await download;
expect(exportRequested).toBe(true);
expect(exportUrl).toContain("includeIds=false");
await page.getByTestId("tenant-import-input").setInputFiles({
name: "tenants.csv",
@@ -213,6 +216,98 @@ test.describe("Tenants Management", () => {
expect(importBody).toContain("tenant-alpha-id");
});
test("should resolve tenant CSV conflicts by choosing create and remapping parent ids", async ({
page,
}) => {
let importBody = "";
await page.route("**/api/v1/admin/tenants**", async (route) => {
const url = route.request().url();
const method = route.request().method();
const headers = { "Access-Control-Allow-Origin": "*" };
if (url.includes("/import")) {
importBody = route.request().postData() ?? "";
return route.fulfill({
json: { created: 2, updated: 0, failed: 0, errors: [] },
headers,
});
}
if (method === "GET") {
return route.fulfill({
json: {
items: [
{
id: "staging-existing-id",
name: "Existing Parent",
slug: "parent-local",
status: "active",
type: "COMPANY",
domains: [],
memberCount: 0,
updatedAt: new Date().toISOString(),
},
],
total: 1,
limit: 1000,
offset: 0,
},
headers,
});
}
return route.continue();
});
await page.goto("/tenants");
await expect(page.locator("h2").last()).toContainText(
/테넌트 목록|Tenants/i,
{ timeout: 20000 },
);
await page.getByTestId("tenant-import-input").setInputFiles({
name: "tenants.csv",
mimeType: "text/csv",
buffer: Buffer.from(
[
"tenant_id,name,type,parent_tenant_id,slug,memo,email_domain",
"local-parent-id,Parent Tenant,COMPANY,,parent-local,,",
"local-child-id,Child Tenant,USER_GROUP,local-parent-id,child-local,,",
].join("\n"),
),
});
await expect(page.getByRole("dialog")).toContainText("CSV 가져오기 확인");
await page
.getByTestId("tenant-import-match-select-2")
.selectOption("__create__");
await page
.getByTestId("tenant-import-create-slug-2")
.fill("parent-created");
await page
.getByTestId("tenant-import-match-select-3")
.selectOption("__create__");
await page
.getByTestId("tenant-import-create-slug-3")
.fill("child-created");
await page.getByTestId("tenant-import-confirm-btn").click();
await expect(page.getByTestId("tenant-import-result")).toContainText(
/생성 2|Created 2/i,
);
expect(importBody).not.toContain("local-parent-id");
expect(importBody).not.toContain("local-child-id");
const parentMatch = importBody.match(
/([0-9a-f-]{36}),Parent Tenant,COMPANY,,parent-created/,
);
expect(parentMatch?.[1]).toBeTruthy();
expect(importBody).toContain(
`,Child Tenant,USER_GROUP,${parentMatch?.[1]},child-created`,
);
});
test("should show validation error on empty name", async ({ page }) => {
await page.goto("/tenants/new");
await expect(page.locator("h2").last()).toContainText(/추가|Create/i, {

View File

@@ -404,9 +404,11 @@ test.describe("User Management", () => {
page,
}) => {
let authorizationHeader: string | undefined;
let exportUrl = "";
await page.route(/\/admin\/users\/export(\?.*)?$/, async (route) => {
authorizationHeader = route.request().headers().authorization;
exportUrl = route.request().url();
return route.fulfill({
status: 200,
headers: {
@@ -425,6 +427,7 @@ test.describe("User Management", () => {
expect(download.suggestedFilename()).toBe("users.csv");
expect(authorizationHeader).toBe("Bearer fake-token");
expect(exportUrl).toContain("includeIds=false");
});
test("should show contact info in one row, hide roles, and toggle user status", async ({

View File

@@ -112,4 +112,78 @@ test.describe("Users Bulk Upload", () => {
const uploadBtn = page.getByTestId("bulk-start-btn");
await expect(uploadBtn).toBeDisabled();
});
test("should create missing tenant before user bulk import", async ({
page,
}) => {
const requests: string[] = [];
let bulkPayload = "";
await page.route("**/api/v1/admin/tenants", async (route) => {
const method = route.request().method();
requests.push(`${method} ${route.request().url()}`);
if (method === "GET") {
return route.fulfill({
json: { items: [], total: 0, limit: 100, offset: 0 },
headers: { "Access-Control-Allow-Origin": "*" },
});
}
if (method === "POST") {
return route.fulfill({
status: 201,
json: {
id: "staging-missing-tenant-id",
name: "Missing Tenant",
slug: "missing-slug",
type: "COMPANY",
description: "Imported memo",
status: "active",
domains: ["missing.example.com"],
memberCount: 0,
createdAt: new Date().toISOString(),
updatedAt: new Date().toISOString(),
},
headers: { "Access-Control-Allow-Origin": "*" },
});
}
return route.continue();
});
await page.route("**/api/v1/admin/users/bulk", async (route) => {
bulkPayload = route.request().postData() ?? "";
return route.fulfill({
json: {
results: [{ email: "new@test.com", success: true, userId: "u-1" }],
},
headers: { "Access-Control-Allow-Origin": "*" },
});
});
await page.goto("/users");
await expect(page.getByTestId("page-title")).toContainText(
/사용자|Users/i,
{ timeout: 20000 },
);
await page.getByTestId("bulk-import-btn").click();
await page.locator('input[type="file"]').setInputFiles({
name: "users.csv",
mimeType: "text/csv",
buffer: Buffer.from(
"email,name,tenant_id,tenant_slug,tenant_name,tenant_type,tenant_memo,email_domain\nnew@test.com,New User,local-tenant-id,missing-slug,Missing Tenant,COMPANY,Imported memo,missing.example.com\n",
),
});
await expect(page.getByTestId("user-import-tenant-resolution")).toContainText(
/신규 생성|Create new/i,
);
await page.getByTestId("bulk-start-btn").click();
await expect(page.getByText("new@test.com")).toBeVisible();
expect(requests.some((request) => request.startsWith("POST "))).toBe(true);
expect(bulkPayload).toContain('"tenantSlug":"missing-slug"');
});
});

View File

@@ -230,4 +230,5 @@ test.describe("User Schema Dynamic Form", () => {
.first();
await expect(errorMsg).toBeVisible();
});
});