feat(csms): add setup routes and pages for initial user creation
This commit is contained in:
@@ -13,6 +13,7 @@ import chargePointRoutes from './routes/charge-points.ts'
|
||||
import transactionRoutes from './routes/transactions.ts'
|
||||
import idTagRoutes from './routes/id-tags.ts'
|
||||
import userRoutes from './routes/users.ts'
|
||||
import setupRoutes from './routes/setup.ts'
|
||||
|
||||
import type { HonoEnv } from './types/hono.ts'
|
||||
|
||||
@@ -54,6 +55,7 @@ app.route('/api/charge-points', chargePointRoutes)
|
||||
app.route('/api/transactions', transactionRoutes)
|
||||
app.route('/api/id-tags', idTagRoutes)
|
||||
app.route('/api/users', userRoutes)
|
||||
app.route('/api/setup', setupRoutes)
|
||||
|
||||
app.get('/api', (c) => {
|
||||
const user = c.get('user')
|
||||
|
||||
56
apps/csms/src/routes/setup.ts
Normal file
56
apps/csms/src/routes/setup.ts
Normal file
@@ -0,0 +1,56 @@
|
||||
import { Hono } from "hono";
|
||||
import { count, eq } from "drizzle-orm";
|
||||
import { useDrizzle } from "@/lib/db.js";
|
||||
import { user } from "@/db/schema.js";
|
||||
import { zValidator } from "@hono/zod-validator";
|
||||
import { z } from "zod";
|
||||
import { auth } from "@/lib/auth.js";
|
||||
|
||||
const app = new Hono();
|
||||
|
||||
/** GET /api/setup — 检查系统是否已初始化(存在用户) */
|
||||
app.get("/", async (c) => {
|
||||
const db = useDrizzle();
|
||||
const [{ value }] = await db.select({ value: count() }).from(user);
|
||||
return c.json({ initialized: value > 0 });
|
||||
});
|
||||
|
||||
const setupSchema = z.object({
|
||||
name: z.string().min(1).max(100),
|
||||
email: z.string().email(),
|
||||
username: z
|
||||
.string()
|
||||
.min(3)
|
||||
.max(50)
|
||||
.regex(/^[a-zA-Z0-9_]+$/, "用户名只能包含字母、数字和下划线"),
|
||||
password: z.string().min(8),
|
||||
});
|
||||
|
||||
/** POST /api/setup — 仅在无用户时创建根管理员账号 */
|
||||
app.post("/", zValidator("json", setupSchema), async (c) => {
|
||||
const db = useDrizzle();
|
||||
const [{ value }] = await db.select({ value: count() }).from(user);
|
||||
|
||||
if (value > 0) {
|
||||
return c.json({ error: "系统已初始化,无法重复创建根管理员" }, 403);
|
||||
}
|
||||
|
||||
const { name, email, username, password } = c.req.valid("json");
|
||||
|
||||
// 通过 better-auth 内部 API 注册账号
|
||||
const signUpRes = await auth.api.signUpEmail({
|
||||
body: { name, email, password, username },
|
||||
asResponse: false,
|
||||
});
|
||||
|
||||
if (!signUpRes?.user?.id) {
|
||||
return c.json({ error: "账号创建失败" }, 500);
|
||||
}
|
||||
|
||||
// 将角色提升为 admin
|
||||
await db.update(user).set({ role: "admin" }).where(eq(user.id, signUpRes.user.id));
|
||||
|
||||
return c.json({ success: true, userId: signUpRes.user.id });
|
||||
});
|
||||
|
||||
export default app;
|
||||
@@ -138,9 +138,9 @@ export default function UsersPage() {
|
||||
</Modal.Header>
|
||||
<Modal.Body className="space-y-3">
|
||||
<TextField fullWidth>
|
||||
<Label className="text-sm font-medium">姓名</Label>
|
||||
<Label className="text-sm font-medium">显示名称</Label>
|
||||
<Input
|
||||
placeholder="用户姓名"
|
||||
placeholder="对外显示的名称"
|
||||
value={createForm.name}
|
||||
onChange={(e) => setCreateForm({ ...createForm, name: e.target.value })}
|
||||
/>
|
||||
@@ -155,10 +155,9 @@ export default function UsersPage() {
|
||||
/>
|
||||
</TextField>
|
||||
<TextField fullWidth>
|
||||
<Label className="text-sm font-medium">用户名(可选)</Label>
|
||||
<Label className="text-sm font-medium">登录名</Label>
|
||||
<Input
|
||||
className="font-mono"
|
||||
placeholder="username"
|
||||
placeholder="创建账号的登录名"
|
||||
value={createForm.username}
|
||||
onChange={(e) => setCreateForm({ ...createForm, username: e.target.value })}
|
||||
/>
|
||||
@@ -166,8 +165,9 @@ export default function UsersPage() {
|
||||
<TextField fullWidth>
|
||||
<Label className="text-sm font-medium">密码</Label>
|
||||
<Input
|
||||
autoComplete="new-password"
|
||||
type="password"
|
||||
placeholder="••••••••"
|
||||
placeholder="创建账号的密码"
|
||||
value={createForm.password}
|
||||
onChange={(e) => setCreateForm({ ...createForm, password: e.target.value })}
|
||||
/>
|
||||
@@ -223,7 +223,7 @@ export default function UsersPage() {
|
||||
<Table.Header>
|
||||
<Table.Column isRowHeader>用户</Table.Column>
|
||||
<Table.Column>邮箱</Table.Column>
|
||||
<Table.Column>用户名</Table.Column>
|
||||
<Table.Column>登录名</Table.Column>
|
||||
<Table.Column>角色</Table.Column>
|
||||
<Table.Column>状态</Table.Column>
|
||||
<Table.Column>注册时间</Table.Column>
|
||||
@@ -245,7 +245,7 @@ export default function UsersPage() {
|
||||
<Table.Cell className="font-mono text-sm">{u.username ?? "—"}</Table.Cell>
|
||||
<Table.Cell>
|
||||
<Chip
|
||||
color={u.role === "admin" ? "success" : "warning"}
|
||||
color={u.role === "admin" ? "warning" : "success"}
|
||||
size="sm"
|
||||
variant="soft"
|
||||
>
|
||||
@@ -292,10 +292,9 @@ export default function UsersPage() {
|
||||
/>
|
||||
</TextField>
|
||||
<TextField fullWidth>
|
||||
<Label className="text-sm font-medium">用户名</Label>
|
||||
<Label className="text-sm font-medium">登录名</Label>
|
||||
<Input
|
||||
className="font-mono"
|
||||
placeholder="username"
|
||||
placeholder="用户登录名"
|
||||
value={editForm.username}
|
||||
onChange={(e) =>
|
||||
setEditForm({ ...editForm, username: e.target.value })
|
||||
|
||||
@@ -1,13 +1,15 @@
|
||||
"use client";
|
||||
|
||||
import { useState } from "react";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { useRouter, useSearchParams } from "next/navigation";
|
||||
import { Alert, Button, Card, CloseButton, Input, Label, TextField } from "@heroui/react";
|
||||
import { Thunderbolt } from "@gravity-ui/icons";
|
||||
import { authClient } from "@/lib/auth-client";
|
||||
|
||||
export default function LoginPage() {
|
||||
const router = useRouter();
|
||||
const searchParams = useSearchParams();
|
||||
const justSetup = searchParams.get("setup") === "1";
|
||||
const [username, setUsername] = useState("");
|
||||
const [password, setPassword] = useState("");
|
||||
const [error, setError] = useState("");
|
||||
@@ -52,6 +54,15 @@ export default function LoginPage() {
|
||||
<Card className="w-full max-w-sm">
|
||||
<Card.Content>
|
||||
<form onSubmit={handleSubmit} className="space-y-4">
|
||||
{justSetup && (
|
||||
<Alert status="success">
|
||||
<Alert.Indicator />
|
||||
<Alert.Content>
|
||||
<Alert.Title>初始化完成</Alert.Title>
|
||||
<Alert.Description>根管理员账号已创建,请登录。</Alert.Description>
|
||||
</Alert.Content>
|
||||
</Alert>
|
||||
)}
|
||||
<TextField fullWidth>
|
||||
<Label className="text-sm font-medium">用户名</Label>
|
||||
<Input
|
||||
|
||||
157
apps/web/app/setup/page.tsx
Normal file
157
apps/web/app/setup/page.tsx
Normal file
@@ -0,0 +1,157 @@
|
||||
"use client";
|
||||
|
||||
import { useState } from "react";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { Alert, Button, Card, CloseButton, Input, Label, TextField } from "@heroui/react";
|
||||
import { Thunderbolt } from "@gravity-ui/icons";
|
||||
|
||||
const CSMS_URL = process.env.NEXT_PUBLIC_CSMS_URL ?? "http://localhost:3001";
|
||||
|
||||
export default function SetupPage() {
|
||||
const router = useRouter();
|
||||
const [form, setForm] = useState({
|
||||
name: "",
|
||||
email: "",
|
||||
username: "",
|
||||
password: "",
|
||||
confirmPassword: "",
|
||||
});
|
||||
const [error, setError] = useState("");
|
||||
const [loading, setLoading] = useState(false);
|
||||
|
||||
const handleChange = (field: keyof typeof form) => (e: React.ChangeEvent<HTMLInputElement>) => {
|
||||
setForm((prev) => ({ ...prev, [field]: e.target.value }));
|
||||
};
|
||||
|
||||
const handleSubmit = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
setError("");
|
||||
|
||||
if (form.password !== form.confirmPassword) {
|
||||
setError("两次输入的密码不一致");
|
||||
return;
|
||||
}
|
||||
if (form.password.length < 8) {
|
||||
setError("密码长度至少 8 位");
|
||||
return;
|
||||
}
|
||||
|
||||
setLoading(true);
|
||||
try {
|
||||
const res = await fetch(`${CSMS_URL}/api/setup`, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
credentials: "include",
|
||||
body: JSON.stringify({
|
||||
name: form.name,
|
||||
email: form.email,
|
||||
username: form.username,
|
||||
password: form.password,
|
||||
}),
|
||||
});
|
||||
|
||||
if (!res.ok) {
|
||||
const data = await res.json().catch(() => ({}));
|
||||
setError((data as { error?: string }).error ?? "初始化失败,请重试");
|
||||
return;
|
||||
}
|
||||
|
||||
// 初始化成功,跳转登录页
|
||||
router.push("/login?setup=1");
|
||||
} catch {
|
||||
setError("网络错误,请稍后重试");
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="flex min-h-dvh flex-col items-center justify-center bg-background px-4">
|
||||
{/* Brand */}
|
||||
<div className="mb-8 flex flex-col items-center gap-3">
|
||||
<div className="flex size-14 items-center justify-center rounded-2xl bg-accent shadow-lg">
|
||||
<Thunderbolt className="size-7 text-accent-foreground" />
|
||||
</div>
|
||||
<div className="text-center">
|
||||
<h1 className="text-2xl font-bold tracking-tight text-foreground">Helios EVCS</h1>
|
||||
<p className="mt-1 text-sm text-muted">首次启动 · 创建根管理员账号</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<Card className="w-full max-w-sm">
|
||||
<Card.Content>
|
||||
<form onSubmit={handleSubmit} className="space-y-4">
|
||||
<TextField fullWidth>
|
||||
<Label className="text-sm font-medium">显示名称</Label>
|
||||
<Input
|
||||
required
|
||||
autoComplete="name"
|
||||
placeholder="管理员"
|
||||
value={form.name}
|
||||
onChange={handleChange("name")}
|
||||
/>
|
||||
</TextField>
|
||||
<TextField fullWidth>
|
||||
<Label className="text-sm font-medium">邮箱</Label>
|
||||
<Input
|
||||
required
|
||||
type="email"
|
||||
autoComplete="email"
|
||||
placeholder="admin@example.com"
|
||||
value={form.email}
|
||||
onChange={handleChange("email")}
|
||||
/>
|
||||
</TextField>
|
||||
<TextField fullWidth>
|
||||
<Label className="text-sm font-medium">用户名</Label>
|
||||
<Input
|
||||
required
|
||||
autoComplete="username"
|
||||
placeholder="admin"
|
||||
value={form.username}
|
||||
onChange={handleChange("username")}
|
||||
/>
|
||||
</TextField>
|
||||
<TextField fullWidth>
|
||||
<Label className="text-sm font-medium">密码</Label>
|
||||
<Input
|
||||
required
|
||||
type="password"
|
||||
autoComplete="new-password"
|
||||
placeholder="至少 8 位"
|
||||
value={form.password}
|
||||
onChange={handleChange("password")}
|
||||
/>
|
||||
</TextField>
|
||||
<TextField fullWidth>
|
||||
<Label className="text-sm font-medium">确认密码</Label>
|
||||
<Input
|
||||
required
|
||||
type="password"
|
||||
autoComplete="new-password"
|
||||
placeholder="再次输入密码"
|
||||
value={form.confirmPassword}
|
||||
onChange={handleChange("confirmPassword")}
|
||||
/>
|
||||
</TextField>
|
||||
{error && (
|
||||
<Alert status="danger">
|
||||
<Alert.Indicator />
|
||||
<Alert.Content>
|
||||
<Alert.Title>初始化失败</Alert.Title>
|
||||
<Alert.Description>{error}</Alert.Description>
|
||||
</Alert.Content>
|
||||
<CloseButton onPress={() => setError("")} />
|
||||
</Alert>
|
||||
)}
|
||||
<Button className="mt-2 w-full" isDisabled={loading} type="submit">
|
||||
{loading ? "创建中…" : "创建根管理员账号"}
|
||||
</Button>
|
||||
</form>
|
||||
</Card.Content>
|
||||
</Card>
|
||||
|
||||
<p className="mt-6 text-xs text-muted/60">此页面仅在首次启动时可访问</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,14 +1,62 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
|
||||
const CSMS_INTERNAL_URL =
|
||||
process.env.CSMS_INTERNAL_URL ??
|
||||
process.env.NEXT_PUBLIC_CSMS_URL ??
|
||||
"http://localhost:3001";
|
||||
|
||||
/** 检查 CSMS 是否已完成初始化(有用户存在)。使用 cookie 缓存结果,避免每次请求都查询。 */
|
||||
async function isInitialized(request: NextRequest): Promise<{ initialized: boolean; fromCache: boolean }> {
|
||||
// 读缓存 cookie
|
||||
const cached = request.cookies.get("helios_setup_done");
|
||||
if (cached?.value === "1") {
|
||||
return { initialized: true, fromCache: true };
|
||||
}
|
||||
|
||||
try {
|
||||
const res = await fetch(`${CSMS_INTERNAL_URL}/api/setup`, {
|
||||
method: "GET",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
// 短超时,避免阻塞
|
||||
signal: AbortSignal.timeout(3000),
|
||||
});
|
||||
if (!res.ok) return { initialized: true, fromCache: false }; // 出错时放行,不阻止访问
|
||||
const data = (await res.json()) as { initialized: boolean };
|
||||
return { initialized: data.initialized, fromCache: false };
|
||||
} catch {
|
||||
// 无法连接 CSMS 时放行,不强制跳转
|
||||
return { initialized: true, fromCache: false };
|
||||
}
|
||||
}
|
||||
|
||||
export async function middleware(request: NextRequest) {
|
||||
const { pathname } = request.nextUrl;
|
||||
|
||||
// 只保护 /dashboard 路由
|
||||
if (!pathname.startsWith("/dashboard")) {
|
||||
return NextResponse.next();
|
||||
// /setup 页面:已初始化则跳转登录
|
||||
if (pathname === "/setup") {
|
||||
const { initialized, fromCache } = await isInitialized(request);
|
||||
if (initialized) {
|
||||
return NextResponse.redirect(new URL("/login", request.url));
|
||||
}
|
||||
const res = NextResponse.next();
|
||||
if (!fromCache) {
|
||||
// 未初始化,确保缓存 cookie 不存在(若之前意外设置了)
|
||||
res.cookies.delete("helios_setup_done");
|
||||
}
|
||||
return res;
|
||||
}
|
||||
|
||||
// /dashboard 路由:检查 session,未登录跳转 /login
|
||||
if (pathname.startsWith("/dashboard")) {
|
||||
const { initialized, fromCache } = await isInitialized(request);
|
||||
|
||||
// 未初始化,先去 setup
|
||||
if (!initialized) {
|
||||
const res = NextResponse.redirect(new URL("/setup", request.url));
|
||||
if (!fromCache) res.cookies.delete("helios_setup_done");
|
||||
return res;
|
||||
}
|
||||
|
||||
// 检查 better-auth session cookie(cookie 前缀是 helios_auth)
|
||||
const sessionCookie =
|
||||
request.cookies.get("helios_auth.session_token") ??
|
||||
request.cookies.get("__Secure-helios_auth.session_token");
|
||||
@@ -16,12 +64,32 @@ export async function middleware(request: NextRequest) {
|
||||
if (!sessionCookie) {
|
||||
const loginUrl = new URL("/login", request.url);
|
||||
loginUrl.searchParams.set("from", pathname);
|
||||
return NextResponse.redirect(loginUrl);
|
||||
const res = NextResponse.redirect(loginUrl);
|
||||
if (!fromCache) res.cookies.set("helios_setup_done", "1", { path: "/", httpOnly: true, sameSite: "lax" });
|
||||
return res;
|
||||
}
|
||||
|
||||
const res = NextResponse.next();
|
||||
if (!fromCache) res.cookies.set("helios_setup_done", "1", { path: "/", httpOnly: true, sameSite: "lax" });
|
||||
return res;
|
||||
}
|
||||
|
||||
// /login 路由:未初始化则跳转 /setup
|
||||
if (pathname === "/login") {
|
||||
const { initialized, fromCache } = await isInitialized(request);
|
||||
if (!initialized) {
|
||||
const res = NextResponse.redirect(new URL("/setup", request.url));
|
||||
if (!fromCache) res.cookies.delete("helios_setup_done");
|
||||
return res;
|
||||
}
|
||||
const res = NextResponse.next();
|
||||
if (!fromCache) res.cookies.set("helios_setup_done", "1", { path: "/", httpOnly: true, sameSite: "lax" });
|
||||
return res;
|
||||
}
|
||||
|
||||
return NextResponse.next();
|
||||
}
|
||||
|
||||
export const config = {
|
||||
matcher: ["/dashboard/:path*"],
|
||||
matcher: ["/setup", "/login", "/dashboard/:path*"],
|
||||
};
|
||||
|
||||
Reference in New Issue
Block a user