feat: add full-stack API persistence and RBAC

This commit is contained in:
2026-07-01 06:28:18 -07:00
parent aafd9caaac
commit 914f74c5cc
18 changed files with 1148 additions and 0 deletions

View File

@@ -0,0 +1,90 @@
import { createAccountRecord, createSessionRecord, setSessionCookie } from "@/modules/core/server/auth";
import { jsonFailure, jsonSuccess, readJsonBody } from "@/modules/core/server/api";
import { recordAuditLog } from "@/modules/core/server/audit";
import { updateData } from "@/modules/core/server/store";
function readString(source: Record<string, unknown>, key: string): string {
const value = source[key];
return typeof value === "string" ? value.trim() : "";
}
function isRecord(value: unknown): value is Record<string, unknown> {
return typeof value === "object" && value !== null && !Array.isArray(value);
}
export async function POST(request: Request): Promise<Response> {
const body = await readJsonBody(request);
if (!isRecord(body)) {
return jsonFailure("请求数据格式无效");
}
const name = readString(body, "name");
const email = readString(body, "email");
const password = readString(body, "password");
const organization = readString(body, "organization");
if (!name || !email || !password || !organization) {
return jsonFailure("机构、姓名、邮箱和密码不能为空");
}
if (password.length < 6) {
return jsonFailure("密码至少需要6位");
}
const created = await updateData((data) => {
if (data.accounts.length > 0) {
return null;
}
const account = createAccountRecord({
name,
email,
password,
role: "admin",
organization,
});
const session = createSessionRecord(account.id);
data.accounts.push(account);
data.sessions.push(session);
return { account, session };
});
if (!created) {
return jsonFailure("系统已完成初始化", 409);
}
await setSessionCookie(created.session.id);
await recordAuditLog({
actor: {
id: created.account.id,
name: created.account.name,
email: created.account.email,
role: created.account.role,
organization: created.account.organization,
status: created.account.status,
createdAt: created.account.createdAt,
updatedAt: created.account.updatedAt,
},
action: "account.setup",
targetType: "account",
targetId: created.account.id,
result: "success",
reason: "初始化管理员账号",
});
return jsonSuccess("初始化完成", {
account: {
id: created.account.id,
name: created.account.name,
email: created.account.email,
role: created.account.role,
organization: created.account.organization,
status: created.account.status,
createdAt: created.account.createdAt,
updatedAt: created.account.updatedAt,
},
});
}