89 lines
2.5 KiB
TypeScript
89 lines
2.5 KiB
TypeScript
import { createAccountRecord, createSessionRecord, normalizeEmail, 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 isRecord(value: unknown): value is Record<string, unknown> {
|
|
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
}
|
|
|
|
function readString(source: Record<string, unknown>, key: string): string {
|
|
const value = source[key];
|
|
return typeof value === "string" ? value.trim() : "";
|
|
}
|
|
|
|
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");
|
|
|
|
if (!name || !email || !password) {
|
|
return jsonFailure("姓名、邮箱和密码不能为空");
|
|
}
|
|
|
|
if (password.length < 6) {
|
|
return jsonFailure("密码至少需要6位");
|
|
}
|
|
|
|
const normalizedEmail = normalizeEmail(email);
|
|
const created = await updateData((data) => {
|
|
const exists = data.accounts.some((account) => account.email === normalizedEmail);
|
|
if (exists) {
|
|
return null;
|
|
}
|
|
|
|
const account = createAccountRecord({
|
|
name,
|
|
email,
|
|
password,
|
|
role: "caregiver",
|
|
});
|
|
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,
|
|
status: created.account.status,
|
|
createdAt: created.account.createdAt,
|
|
updatedAt: created.account.updatedAt,
|
|
},
|
|
action: "account.register",
|
|
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,
|
|
status: created.account.status,
|
|
createdAt: created.account.createdAt,
|
|
updatedAt: created.account.updatedAt,
|
|
},
|
|
});
|
|
}
|
|
|