fix: use real settings data boundaries
This commit is contained in:
@@ -17,14 +17,8 @@ function readString(source: Record<string, unknown>, key: string): string {
|
||||
return typeof value === "string" ? value.trim() : "";
|
||||
}
|
||||
|
||||
function createSlug(name: string): string {
|
||||
const base = name
|
||||
.trim()
|
||||
.toLowerCase()
|
||||
.replace(/[^a-z0-9]+/g, "-")
|
||||
.replace(/^-|-$/g, "");
|
||||
|
||||
return base.length > 0 ? base : `org-${Date.now()}`;
|
||||
function isValidSlug(value: string): boolean {
|
||||
return /^[a-z0-9][a-z0-9-]{1,47}$/.test(value) && !value.endsWith("-");
|
||||
}
|
||||
|
||||
export async function GET(): Promise<Response> {
|
||||
@@ -76,31 +70,47 @@ export async function POST(request: Request): Promise<Response> {
|
||||
if (!name) {
|
||||
return jsonFailure("机构名称不能为空");
|
||||
}
|
||||
|
||||
const database = getDatabase();
|
||||
const rows = await database
|
||||
.insert(organizations)
|
||||
.values({
|
||||
name,
|
||||
slug: readString(body, "slug") || createSlug(name),
|
||||
status: "active",
|
||||
})
|
||||
.returning();
|
||||
const organization = rows[0];
|
||||
if (!organization) {
|
||||
return jsonFailure("机构创建失败", 500);
|
||||
const slug = readString(body, "slug").toLowerCase();
|
||||
if (!slug) {
|
||||
return jsonFailure("机构标识不能为空");
|
||||
}
|
||||
if (!isValidSlug(slug)) {
|
||||
return jsonFailure("机构标识仅支持小写字母、数字和连字符,长度 2-48 位,且不能以连字符结尾");
|
||||
}
|
||||
|
||||
await seedOrganizationRoles(organization.id);
|
||||
await recordAuditLog({
|
||||
actor: auth.context.account,
|
||||
organizationId: organization.id,
|
||||
action: "organization.create",
|
||||
targetType: "organization",
|
||||
targetId: organization.id,
|
||||
result: "success",
|
||||
reason: `创建机构:${organization.name}`,
|
||||
});
|
||||
const database = getDatabase();
|
||||
try {
|
||||
const rows = await database
|
||||
.insert(organizations)
|
||||
.values({
|
||||
name,
|
||||
slug,
|
||||
status: "active",
|
||||
})
|
||||
.returning();
|
||||
const organization = rows[0];
|
||||
if (!organization) {
|
||||
return jsonFailure("机构创建失败", 500);
|
||||
}
|
||||
|
||||
return jsonSuccess("机构已创建", { organization }, 201);
|
||||
await seedOrganizationRoles(organization.id);
|
||||
await recordAuditLog({
|
||||
actor: auth.context.account,
|
||||
organizationId: organization.id,
|
||||
action: "organization.create",
|
||||
targetType: "organization",
|
||||
targetId: organization.id,
|
||||
result: "success",
|
||||
reason: `创建机构:${organization.name}`,
|
||||
});
|
||||
|
||||
return jsonSuccess("机构已创建", { organization }, 201);
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : "";
|
||||
if (message.includes("organizations_slug_unique")) {
|
||||
return jsonFailure("机构标识已存在", 409);
|
||||
}
|
||||
|
||||
return jsonFailure("机构创建失败", 500);
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user