Add login gate, calculation history, and AI markdown download.

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
dekun
2026-06-13 09:39:38 +08:00
parent abf78cbbb5
commit 462bec2739
23 changed files with 878 additions and 74 deletions
+80
View File
@@ -0,0 +1,80 @@
"use client";
import {
createContext,
useCallback,
useContext,
useEffect,
useMemo,
useState,
} from "react";
interface AuthState {
loading: boolean;
authEnabled: boolean;
loggedIn: boolean;
username?: string;
refresh: () => Promise<void>;
logout: () => Promise<void>;
}
const AuthContext = createContext<AuthState | null>(null);
export function AuthProvider({ children }: { children: React.ReactNode }) {
const [loading, setLoading] = useState(true);
const [authEnabled, setAuthEnabled] = useState(false);
const [loggedIn, setLoggedIn] = useState(true);
const [username, setUsername] = useState<string>();
const refresh = useCallback(async () => {
try {
const res = await fetch("/api/auth/me", { cache: "no-store" });
const data = await res.json();
setAuthEnabled(!!data.authEnabled);
setLoggedIn(!!data.loggedIn);
setUsername(data.username);
} catch {
setAuthEnabled(false);
setLoggedIn(true);
} finally {
setLoading(false);
}
}, []);
useEffect(() => {
refresh();
}, [refresh]);
const logout = useCallback(async () => {
await fetch("/api/auth/logout", { method: "POST" });
await refresh();
window.location.href = "/";
}, [refresh]);
const value = useMemo(
() => ({ loading, authEnabled, loggedIn, username, refresh, logout }),
[loading, authEnabled, loggedIn, username, refresh, logout],
);
return <AuthContext.Provider value={value}>{children}</AuthContext.Provider>;
}
export function useAuth() {
const ctx = useContext(AuthContext);
if (!ctx) {
throw new Error("useAuth must be used within AuthProvider");
}
return ctx;
}
export function useRequireAuthForPath(path: string): boolean {
const { authEnabled, loggedIn } = useAuth();
if (!authEnabled) {
return true;
}
const protectedPaths = ["/liuyao", "/bazi", "/combined", "/history"];
if (!protectedPaths.some((p) => path === p || path.startsWith(`${p}/`))) {
return true;
}
return loggedIn;
}
+76
View File
@@ -0,0 +1,76 @@
"use client";
import { useState } from "react";
import { useRouter, useSearchParams } from "next/navigation";
import { Button } from "@/components/ui/button";
import { useAuth } from "@/components/auth/auth-provider";
export default function LoginForm() {
const router = useRouter();
const searchParams = useSearchParams();
const { refresh } = useAuth();
const [username, setUsername] = useState("");
const [password, setPassword] = useState("");
const [error, setError] = useState("");
const [loading, setLoading] = useState(false);
async function handleSubmit(e: React.FormEvent) {
e.preventDefault();
setError("");
setLoading(true);
try {
const res = await fetch("/api/auth/login", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ username, password }),
});
const data = await res.json();
if (!res.ok) {
setError(data.error ?? "登录失败");
return;
}
await refresh();
const next = searchParams.get("next") || "/liuyao";
router.push(next);
router.refresh();
} catch {
setError("网络错误,请稍后重试");
} finally {
setLoading(false);
}
}
return (
<form onSubmit={handleSubmit} className="mx-auto w-full max-w-sm space-y-4">
<div className="space-y-2">
<label className="text-sm font-medium"></label>
<input
type="text"
autoComplete="username"
className="w-full rounded-md border bg-background px-3 py-2 text-sm"
value={username}
onChange={(e) => setUsername(e.target.value)}
required
/>
</div>
<div className="space-y-2">
<label className="text-sm font-medium"></label>
<input
type="password"
autoComplete="current-password"
className="w-full rounded-md border bg-background px-3 py-2 text-sm"
value={password}
onChange={(e) => setPassword(e.target.value)}
required
/>
</div>
{error && <p className="text-sm text-destructive">{error}</p>}
<Button type="submit" className="w-full" disabled={loading}>
{loading ? "登录中…" : "登录"}
</Button>
<p className="text-center text-xs text-muted-foreground">
使
</p>
</form>
);
}