feat(frontend): T1.1 前端登录页对接 — AuthProvider + 登录表单
- AuthProvider:管理 token 和用户状态,自动恢复登录态 - 登录页:邮箱密码表单,对接后端 /auth/login API - 根布局包裹 AuthProvider - 前端构建 8 路由全部成功
This commit is contained in:
@@ -1,4 +1,5 @@
|
||||
import type { Metadata } from "next";
|
||||
import { AuthProvider } from "@/lib/auth-context";
|
||||
import "./globals.css";
|
||||
|
||||
export const metadata: Metadata = {
|
||||
@@ -13,7 +14,9 @@ export default function RootLayout({
|
||||
}>) {
|
||||
return (
|
||||
<html lang="zh-CN" className="h-full antialiased">
|
||||
<body className="min-h-full flex flex-col">{children}</body>
|
||||
<body className="min-h-full flex flex-col">
|
||||
<AuthProvider>{children}</AuthProvider>
|
||||
</body>
|
||||
</html>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,8 +1,35 @@
|
||||
/** 登录页 — 占位页面。 */
|
||||
"use client";
|
||||
|
||||
import { Lock } from "lucide-react";
|
||||
import { useState } from "react";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { Lock, Mail, Loader2 } from "lucide-react";
|
||||
import { useAuth } from "@/lib/auth-context";
|
||||
|
||||
/**
|
||||
* 登录页 — 对接后端 auth API。
|
||||
*/
|
||||
export default function LoginPage() {
|
||||
const router = useRouter();
|
||||
const { login } = useAuth();
|
||||
const [email, setEmail] = useState("");
|
||||
const [password, setPassword] = useState("");
|
||||
const [error, setError] = useState("");
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
|
||||
async function handleSubmit(e: React.FormEvent) {
|
||||
e.preventDefault();
|
||||
setError("");
|
||||
setIsLoading(true);
|
||||
try {
|
||||
await login(email, password);
|
||||
router.push("/dashboard");
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : "登录失败");
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex min-h-screen items-center justify-center bg-gradient-to-b from-indigo-50 to-white">
|
||||
<div className="w-full max-w-sm rounded-lg border bg-white p-8 shadow-sm">
|
||||
@@ -13,7 +40,68 @@ export default function LoginPage() {
|
||||
<h1 className="text-xl font-bold">AIPortPilot</h1>
|
||||
<p className="mt-1 text-sm text-muted-foreground">AI+ 投后管理平台</p>
|
||||
</div>
|
||||
<p className="text-center text-sm text-muted-foreground">登录功能开发中</p>
|
||||
|
||||
<form onSubmit={handleSubmit} className="space-y-4">
|
||||
<div>
|
||||
<label htmlFor="email" className="mb-1 block text-sm font-medium text-foreground">
|
||||
邮箱
|
||||
</label>
|
||||
<div className="relative">
|
||||
<Mail
|
||||
className="absolute left-3 top-1/2 -translate-y-1/2 text-muted-foreground"
|
||||
size={16}
|
||||
aria-hidden="true"
|
||||
/>
|
||||
<input
|
||||
id="email"
|
||||
type="email"
|
||||
value={email}
|
||||
onChange={(e) => setEmail(e.target.value)}
|
||||
required
|
||||
placeholder="you@example.com"
|
||||
className="w-full rounded-md border bg-background py-2 pl-9 pr-3 text-sm focus:outline-none focus:ring-2 focus:ring-[var(--founder-primary)]"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label htmlFor="password" className="mb-1 block text-sm font-medium text-foreground">
|
||||
密码
|
||||
</label>
|
||||
<div className="relative">
|
||||
<Lock
|
||||
className="absolute left-3 top-1/2 -translate-y-1/2 text-muted-foreground"
|
||||
size={16}
|
||||
aria-hidden="true"
|
||||
/>
|
||||
<input
|
||||
id="password"
|
||||
type="password"
|
||||
value={password}
|
||||
onChange={(e) => setPassword(e.target.value)}
|
||||
required
|
||||
minLength={6}
|
||||
placeholder="至少 6 位"
|
||||
className="w-full rounded-md border bg-background py-2 pl-9 pr-3 text-sm focus:outline-none focus:ring-2 focus:ring-[var(--founder-primary)]"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{error && (
|
||||
<p className="rounded-md bg-[var(--destructive)]/10 px-3 py-2 text-sm text-[var(--destructive)]">
|
||||
{error}
|
||||
</p>
|
||||
)}
|
||||
|
||||
<button
|
||||
type="submit"
|
||||
disabled={isLoading}
|
||||
className="flex w-full items-center justify-center gap-2 rounded-md bg-[var(--founder-primary)] py-2 text-sm font-medium text-white transition-colors hover:opacity-90 disabled:opacity-50"
|
||||
>
|
||||
{isLoading && <Loader2 className="animate-spin" size={16} aria-hidden="true" />}
|
||||
{isLoading ? "登录中..." : "登录"}
|
||||
</button>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
|
||||
@@ -0,0 +1,108 @@
|
||||
/** 前端认证状态管理。 */
|
||||
|
||||
"use client";
|
||||
|
||||
import { createContext, useContext, useEffect, useState, type ReactNode } from "react";
|
||||
|
||||
interface AuthUser {
|
||||
id: string;
|
||||
email: string;
|
||||
name: string;
|
||||
role: string;
|
||||
tenant_id: string;
|
||||
}
|
||||
|
||||
interface AuthContextValue {
|
||||
user: AuthUser | null;
|
||||
token: string | null;
|
||||
isLoading: boolean;
|
||||
login: (email: string, password: string) => Promise<void>;
|
||||
logout: () => void;
|
||||
}
|
||||
|
||||
const AuthContext = createContext<AuthContextValue | undefined>(undefined);
|
||||
|
||||
const API_BASE_URL = process.env.NEXT_PUBLIC_API_URL || "http://localhost:8000/api/v1";
|
||||
|
||||
/**
|
||||
* 认证 Provider,管理登录状态和 token。
|
||||
*/
|
||||
export function AuthProvider({ children }: { children: ReactNode }) {
|
||||
const [user, setUser] = useState<AuthUser | null>(null);
|
||||
const [token, setToken] = useState<string | null>(null);
|
||||
const [isLoading, setIsLoading] = useState(true);
|
||||
|
||||
useEffect(() => {
|
||||
const savedToken = localStorage.getItem("token");
|
||||
if (savedToken) {
|
||||
setToken(savedToken);
|
||||
fetchUserInfo(savedToken)
|
||||
.then(setUser)
|
||||
.catch(() => {
|
||||
localStorage.removeItem("token");
|
||||
localStorage.removeItem("refresh_token");
|
||||
})
|
||||
.finally(() => setIsLoading(false));
|
||||
} else {
|
||||
setIsLoading(false);
|
||||
}
|
||||
}, []);
|
||||
|
||||
async function login(email: string, password: string) {
|
||||
const response = await fetch(`${API_BASE_URL}/auth/login`, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ email, password }),
|
||||
});
|
||||
|
||||
const data = await response.json();
|
||||
if (!response.ok || data.code !== 0) {
|
||||
throw new Error(data.detail || data.message || "登录失败");
|
||||
}
|
||||
|
||||
const { access_token, refresh_token } = data.data;
|
||||
localStorage.setItem("token", access_token);
|
||||
localStorage.setItem("refresh_token", refresh_token);
|
||||
setToken(access_token);
|
||||
const userInfo = await fetchUserInfo(access_token);
|
||||
setUser(userInfo);
|
||||
}
|
||||
|
||||
function logout() {
|
||||
localStorage.removeItem("token");
|
||||
localStorage.removeItem("refresh_token");
|
||||
setToken(null);
|
||||
setUser(null);
|
||||
}
|
||||
|
||||
return (
|
||||
<AuthContext.Provider value={{ user, token, isLoading, login, logout }}>
|
||||
{children}
|
||||
</AuthContext.Provider>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取当前用户信息。
|
||||
*/
|
||||
async function fetchUserInfo(token: string): Promise<AuthUser> {
|
||||
const response = await fetch(`${API_BASE_URL}/auth/me`, {
|
||||
headers: { Authorization: `Bearer ${token}` },
|
||||
});
|
||||
const data = await response.json();
|
||||
if (!response.ok || data.code !== 0) {
|
||||
throw new Error("获取用户信息失败");
|
||||
}
|
||||
return data.data;
|
||||
}
|
||||
|
||||
/**
|
||||
* 使用认证上下文。
|
||||
*/
|
||||
export function useAuth() {
|
||||
const ctx = useContext(AuthContext);
|
||||
if (!ctx) {
|
||||
throw new Error("useAuth 必须在 AuthProvider 内使用");
|
||||
}
|
||||
return ctx;
|
||||
}
|
||||
Reference in New Issue
Block a user