feat: add full-stack API persistence and RBAC
This commit is contained in:
62
app/api/auth/login/route.ts
Normal file
62
app/api/auth/login/route.ts
Normal file
@@ -0,0 +1,62 @@
|
||||
import { createSessionRecord, normalizeEmail, setSessionCookie, toPublicAccount, verifyPassword } 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 email = normalizeEmail(readString(body, "email"));
|
||||
const password = readString(body, "password");
|
||||
|
||||
if (!email || !password) {
|
||||
return jsonFailure("邮箱和密码不能为空");
|
||||
}
|
||||
|
||||
const result = await updateData((data) => {
|
||||
const account = data.accounts.find((item) => item.email === email);
|
||||
if (!account || account.status !== "active" || !verifyPassword(password, account)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const session = createSessionRecord(account.id);
|
||||
data.sessions.push(session);
|
||||
return { account, session };
|
||||
});
|
||||
|
||||
if (!result) {
|
||||
await recordAuditLog({
|
||||
action: "auth.login",
|
||||
targetType: "account",
|
||||
result: "failure",
|
||||
reason: `登录失败:${email}`,
|
||||
});
|
||||
return jsonFailure("账号或密码错误", 401);
|
||||
}
|
||||
|
||||
await setSessionCookie(result.session.id);
|
||||
const account = toPublicAccount(result.account);
|
||||
await recordAuditLog({
|
||||
actor: account,
|
||||
action: "auth.login",
|
||||
targetType: "account",
|
||||
targetId: account.id,
|
||||
result: "success",
|
||||
reason: "登录成功",
|
||||
});
|
||||
|
||||
return jsonSuccess("登录成功", { account });
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user