Add user authentication and role management
This commit is contained in:
47
app/api/auth/login/route.ts
Normal file
47
app/api/auth/login/route.ts
Normal 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 },
|
||||
);
|
||||
}
|
||||
}
|
||||
17
app/api/auth/logout/route.ts
Normal file
17
app/api/auth/logout/route.ts
Normal file
@@ -0,0 +1,17 @@
|
||||
import {
|
||||
clearSessionCookie,
|
||||
deleteSession,
|
||||
sessionCookieFromHeader,
|
||||
} from "../../../../lib/user-auth";
|
||||
|
||||
export const runtime = "edge";
|
||||
|
||||
export async function POST(request: Request) {
|
||||
const token = sessionCookieFromHeader(request.headers.get("cookie"));
|
||||
await deleteSession(token);
|
||||
const secure = new URL(request.url).protocol === "https:";
|
||||
return Response.json(
|
||||
{ loggedOut: true },
|
||||
{ headers: { "Set-Cookie": clearSessionCookie(secure) } },
|
||||
);
|
||||
}
|
||||
Reference in New Issue
Block a user