Add user authentication and role management

This commit is contained in:
巫凤萍
2026-08-07 11:06:20 +08:00
parent 1f910c975d
commit c926a6a874
25 changed files with 2370 additions and 132 deletions

View File

@@ -0,0 +1,47 @@
import {
createSession,
createSessionCookie,
ensureInitialSuperAdmin,
normalizeUsername,
verifyPassword,
} from "../../../../lib/user-auth";
import { getRawDb } from "../../../../lib/mvp-db";
export const runtime = "edge";
export async function POST(request: Request) {
try {
await ensureInitialSuperAdmin();
const body = (await request.json()) as { username?: string; password?: string };
const username = normalizeUsername(body.username);
const password = String(body.password ?? "");
const user = await getRawDb()
.prepare(
`SELECT id, username, role, password_hash, password_salt, password_iterations
FROM users WHERE username = ? LIMIT 1`,
)
.bind(username)
.first<{
id: string;
username: string;
role: string;
password_hash: string;
password_salt: string;
password_iterations: number;
}>();
if (!user || !(await verifyPassword(password, user))) {
return Response.json({ error: "账号或密码错误" }, { status: 401 });
}
const token = await createSession(user.id);
const secure = new URL(request.url).protocol === "https:";
return Response.json(
{ user: { id: user.id, username: user.username, role: user.role } },
{ headers: { "Set-Cookie": createSessionCookie(token, secure) } },
);
} catch (error) {
return Response.json(
{ error: error instanceof Error ? error.message : "登录失败" },
{ status: 500 },
);
}
}