feat: first-time setup flow — no .env required for deployment

- Add GET /auth/status endpoint (returns needsSetup when no admin exists)
- Add POST /auth/setup endpoint (public first-admin registration)
- Add IsAdminExists + SetupInitialAdmin methods to AuthService
- Frontend: detect needsSetup on load, show setup page with admin registration
- Frontend: fall back to login page when setup is already complete
- Docker compose: env_file already optional (required: false), no changes needed
- Bootstrap: auto-detect BOOTSTRAP_CLUSTERS without separate enable flag
This commit is contained in:
Ivan087
2026-05-21 13:49:36 +08:00
parent 0144e9cab7
commit 0094519f52
5 changed files with 269 additions and 28 deletions

View File

@ -219,6 +219,10 @@ export type NodeMetricsResponse = GeneratedNodeMetricsResponse;
export const login = postAuthLogin;
export const register = postAuthRegister;
export const refreshAuth = postAuthRefresh;
export const fetchAuthStatus = () =>
AXIOS_INSTANCE.get<{ needsSetup: boolean; hasUsers: boolean }>("/auth/status").then((r) => r.data);
export const setupInitialAdmin = (data: { username: string; password: string; email?: string }) =>
AXIOS_INSTANCE.post<{ accessToken: string; refreshToken: string }>("/auth/setup", data).then((r) => r.data);
export const listUsers = () => customAxiosInstance<UserResponse[]>({ url: "/users", method: "GET" });
export const createUser = (data: AdminCreateUserRequest) =>
customAxiosInstance<UserResponse>({ url: "/users", method: "POST", data });

View File

@ -1,9 +1,9 @@
import React, { useState } from "react";
import React, { useState, useEffect } from "react";
import { useNavigate } from "react-router-dom";
import { LogIn, Loader2, ShieldCheck } from "lucide-react";
import { LogIn, Loader2, ShieldCheck, UserPlus } from "lucide-react";
import { useToast } from "@/shared";
import { getErrorMessage } from "@/shared/utils/handleApiError";
import { login as apiLogin, type AuthResponse } from "@/api";
import { login as apiLogin, fetchAuthStatus, setupInitialAdmin, type AuthResponse } from "@/api";
type Props = {
onLogin: (response: AuthResponse) => void;
@ -13,12 +13,76 @@ const AuthPage: React.FC<Props> = ({ onLogin }) => {
const navigate = useNavigate();
const { success: toastSuccess, error: toastError, info: toastInfo } = useToast();
// Auth status
const [needsSetup, setNeedsSetup] = useState<boolean | null>(null);
const [checkingStatus, setCheckingStatus] = useState(true);
// Login form
const [loginUsername, setLoginUsername] = useState("");
const [loginPassword, setLoginPassword] = useState("");
const [loginLoading, setLoginLoading] = useState(false);
const [loginError, setLoginError] = useState<string | null>(null);
// Setup form
const [setupUsername, setSetupUsername] = useState("");
const [setupPassword, setSetupPassword] = useState("");
const [setupEmail, setSetupEmail] = useState("");
const [setupLoading, setSetupLoading] = useState(false);
const [setupError, setSetupError] = useState<string | null>(null);
// Check if setup is needed on mount
useEffect(() => {
let cancelled = false;
fetchAuthStatus()
.then((status) => {
if (!cancelled) {
setNeedsSetup(status.needsSetup);
setCheckingStatus(false);
}
})
.catch(() => {
if (!cancelled) {
setNeedsSetup(false); // fall back to login on error
setCheckingStatus(false);
}
});
return () => { cancelled = true; };
}, []);
// Handle setup (first admin registration)
const handleSetup = async (e: React.FormEvent) => {
e.preventDefault();
if (!setupUsername || !setupPassword) return;
setSetupLoading(true);
setSetupError(null);
toastInfo("Creating admin account...", { title: "Setup", durationMs: 1200 });
try {
await setupInitialAdmin({
username: setupUsername,
password: setupPassword,
email: setupEmail || undefined,
});
// Login with the returned tokens
const loginResponse = await apiLogin({
username: setupUsername,
password: setupPassword,
});
toastSuccess("Admin account created. Welcome!");
onLogin(loginResponse);
navigate("/home", { replace: true });
} catch (err: unknown) {
const msg = getErrorMessage(err, "Setup failed. Please try again later.");
setSetupError(msg);
toastError(msg);
} finally {
setSetupLoading(false);
}
};
// Handle login
const handleLogin = async (e: React.FormEvent) => {
e.preventDefault();
@ -30,8 +94,6 @@ const AuthPage: React.FC<Props> = ({ onLogin }) => {
try {
const response = await apiLogin({ username: loginUsername, password: loginPassword });
// JWT 格式: { access_token, refresh_token, username, ... }
toastSuccess(`Welcome, ${response.username}!`);
onLogin(response);
navigate("/home", { replace: true });
@ -40,7 +102,6 @@ const AuthPage: React.FC<Props> = ({ onLogin }) => {
const msg = raw?.message?.includes("Failed to fetch")
? "Network or CORS error: Please check backend CORS or use Vite proxy in development."
: getErrorMessage(err, "Login failed. Please try again later.");
setLoginError(msg);
toastError(msg);
} finally {
@ -48,25 +109,36 @@ const AuthPage: React.FC<Props> = ({ onLogin }) => {
}
};
return (
<div className="relative min-h-screen bg-slate-50 text-slate-900 flex items-center justify-center px-4 sm:px-6">
<div className="pointer-events-none absolute inset-0 bg-app-gradient opacity-90" aria-hidden="true" />
<div className="relative w-full max-w-md p-6 sm:p-7 bg-white/95 border border-slate-200 rounded-lg shadow-2xl backdrop-blur-xl">
<div className="animate-fadeIn">
if (checkingStatus) {
return (
<div className="relative min-h-screen bg-slate-50 flex items-center justify-center">
<Loader2 className="w-8 h-8 text-blue-500 animate-spin" />
</div>
);
}
// Setup view — first admin registration
if (needsSetup) {
return (
<div className="relative min-h-screen bg-slate-50 text-slate-900 flex items-center justify-center px-4 sm:px-6">
<div className="pointer-events-none absolute inset-0 bg-app-gradient opacity-90" aria-hidden="true" />
<div className="relative w-full max-w-md p-6 sm:p-7 bg-white/95 border border-slate-200 rounded-lg shadow-2xl backdrop-blur-xl">
<div className="animate-fadeIn">
<header className="mb-6 text-center">
<ShieldCheck className="w-11 h-11 text-blue-600 mx-auto mb-3" />
<h1 className="text-2xl font-semibold text-slate-900">OCDP Console</h1>
<p className="text-slate-600 text-sm mt-1">Sign in with an account created by an administrator</p>
<ShieldCheck className="w-11 h-11 text-emerald-600 mx-auto mb-3" />
<h1 className="text-2xl font-semibold text-slate-900">OCDP Initial Setup</h1>
<p className="text-slate-600 text-sm mt-1">Create the first administrator account to get started.</p>
</header>
<form onSubmit={handleLogin} className="space-y-4">
<form onSubmit={handleSetup} className="space-y-4">
<div>
<label className="block text-sm text-slate-600">Username</label>
<label className="block text-sm text-slate-600">Admin Username</label>
<input
value={loginUsername}
onChange={(e) => setLoginUsername(e.target.value)}
className="mt-1 w-full bg-white border border-slate-200 rounded-lg p-2 text-slate-900 focus:ring-2 focus:ring-blue-500 focus:border-blue-600 focus:outline-none transition-shadow"
value={setupUsername}
onChange={(e) => setSetupUsername(e.target.value)}
className="mt-1 w-full bg-white border border-slate-200 rounded-lg p-2 text-slate-900 focus:ring-2 focus:ring-emerald-500 focus:border-emerald-600 focus:outline-none transition-shadow"
autoComplete="username"
autoFocus
required
/>
</div>
@ -75,26 +147,92 @@ const AuthPage: React.FC<Props> = ({ onLogin }) => {
<label className="block text-sm text-slate-600">Password</label>
<input
type="password"
value={loginPassword}
onChange={(e) => setLoginPassword(e.target.value)}
className="mt-1 w-full bg-white border border-slate-200 rounded-lg p-2 text-slate-900 focus:ring-2 focus:ring-blue-500 focus:border-blue-600 focus:outline-none transition-shadow"
autoComplete="current-password"
value={setupPassword}
onChange={(e) => setSetupPassword(e.target.value)}
className="mt-1 w-full bg-white border border-slate-200 rounded-lg p-2 text-slate-900 focus:ring-2 focus:ring-emerald-500 focus:border-emerald-600 focus:outline-none transition-shadow"
autoComplete="new-password"
required
/>
</div>
<div>
<label className="block text-sm text-slate-600">Email (optional)</label>
<input
type="email"
value={setupEmail}
onChange={(e) => setSetupEmail(e.target.value)}
className="mt-1 w-full bg-white border border-slate-200 rounded-lg p-2 text-slate-900 focus:ring-2 focus:ring-emerald-500 focus:border-emerald-600 focus:outline-none transition-shadow"
autoComplete="email"
placeholder="admin@example.com"
/>
</div>
<button
type="submit"
disabled={loginLoading}
disabled={setupLoading}
className={`w-full disabled:opacity-60 font-semibold py-2.5 rounded-lg flex items-center justify-center gap-2 transition-colors duration-150
${loginLoading ? "bg-blue-500 cursor-wait text-white" : "bg-blue-600 text-white hover:bg-blue-700"}`}
${setupLoading ? "bg-emerald-500 cursor-wait text-white" : "bg-emerald-600 text-white hover:bg-emerald-700"}`}
>
{loginLoading ? <Loader2 className="w-4 h-4 animate-spin" /> : <LogIn className="w-4 h-4" />}
{loginLoading ? "Logging in..." : "Login"}
{setupLoading ? <Loader2 className="w-4 h-4 animate-spin" /> : <UserPlus className="w-4 h-4" />}
{setupLoading ? "Creating..." : "Create Admin Account"}
</button>
{loginError && <p className="text-red-400 text-center text-sm">{loginError}</p>}
{setupError && <p className="text-red-400 text-center text-sm">{setupError}</p>}
</form>
</div>
</div>
</div>
);
}
// Regular login view
return (
<div className="relative min-h-screen bg-slate-50 text-slate-900 flex items-center justify-center px-4 sm:px-6">
<div className="pointer-events-none absolute inset-0 bg-app-gradient opacity-90" aria-hidden="true" />
<div className="relative w-full max-w-md p-6 sm:p-7 bg-white/95 border border-slate-200 rounded-lg shadow-2xl backdrop-blur-xl">
<div className="animate-fadeIn">
<header className="mb-6 text-center">
<ShieldCheck className="w-11 h-11 text-blue-600 mx-auto mb-3" />
<h1 className="text-2xl font-semibold text-slate-900">OCDP Console</h1>
<p className="text-slate-600 text-sm mt-1">Sign in with an account created by an administrator</p>
</header>
<form onSubmit={handleLogin} className="space-y-4">
<div>
<label className="block text-sm text-slate-600">Username</label>
<input
value={loginUsername}
onChange={(e) => setLoginUsername(e.target.value)}
className="mt-1 w-full bg-white border border-slate-200 rounded-lg p-2 text-slate-900 focus:ring-2 focus:ring-blue-500 focus:border-blue-600 focus:outline-none transition-shadow"
autoComplete="username"
required
/>
</div>
<div>
<label className="block text-sm text-slate-600">Password</label>
<input
type="password"
value={loginPassword}
onChange={(e) => setLoginPassword(e.target.value)}
className="mt-1 w-full bg-white border border-slate-200 rounded-lg p-2 text-slate-900 focus:ring-2 focus:ring-blue-500 focus:border-blue-600 focus:outline-none transition-shadow"
autoComplete="current-password"
required
/>
</div>
<button
type="submit"
disabled={loginLoading}
className={`w-full disabled:opacity-60 font-semibold py-2.5 rounded-lg flex items-center justify-center gap-2 transition-colors duration-150
${loginLoading ? "bg-blue-500 cursor-wait text-white" : "bg-blue-600 text-white hover:bg-blue-700"}`}
>
{loginLoading ? <Loader2 className="w-4 h-4 animate-spin" /> : <LogIn className="w-4 h-4" />}
{loginLoading ? "Logging in..." : "Login"}
</button>
{loginError && <p className="text-red-400 text-center text-sm">{loginError}</p>}
</form>
</div>
</div>
</div>