fix(login): add register

This commit is contained in:
2026-02-09 19:52:32 +08:00
parent b57d04f172
commit 8c033066af
6 changed files with 268 additions and 150 deletions

View File

@@ -1,78 +1,104 @@
"use client";
import * as React from "react";
import Link from "next/link";
import { Button } from "@/components/ui/button";
import { LoginForm } from "@/components/auth/login-form";
import { RegisterForm } from "@/components/auth/register-form";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import {
Card,
CardContent,
CardDescription,
CardFooter,
CardHeader,
CardTitle,
} from "@/components/ui/card";
import { Checkbox } from "@/components/ui/checkbox";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
const LoginForm = (props: {
const LoginFormCard = (props: {
clientId: string;
tenantId: string;
callback: string;
initialEmail: string;
}) => {
const [email, setEmail] = React.useState(props.initialEmail);
const [password, setPassword] = React.useState("");
const [tab, setTab] = React.useState<"login" | "register">("login");
const [captcha, setCaptcha] = React.useState("");
const [rememberMe, setRememberMe] = React.useState(
Boolean(props.initialEmail),
);
const [submitting, setSubmitting] = React.useState(false);
const [error, setError] = React.useState<string | null>(null);
const [captchaKey, setCaptchaKey] = React.useState(() => String(Date.now()));
const [loginExternalError, setLoginExternalError] = React.useState<
string | null
>(null);
const [loginPrefill, setLoginPrefill] = React.useState<{
email: string;
password: string;
} | null>(null);
const clientId = props.clientId;
const tenantId = props.tenantId;
const callback = props.callback;
async function onSubmit(e: React.FormEvent) {
e.preventDefault();
setError(null);
setSubmitting(true);
try {
const res = await fetch("/api/auth/login", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
clientId,
tenantId,
callback,
email,
password,
captcha,
rememberMe,
}),
});
const json = (await res.json()) as {
redirectTo?: string;
message?: string;
};
if (!res.ok || !json.redirectTo) {
throw new Error(json.message || "登录失败");
}
console.log(`json.redirectTo`, json.redirectTo);
window.location.href = json.redirectTo;
} catch (err) {
setError(err instanceof Error ? err.message : "登录失败");
setCaptcha("");
setCaptchaKey(String(Date.now()));
} finally {
setSubmitting(false);
}
function refreshCaptcha() {
setCaptchaKey(String(Date.now()));
}
const missingParams = !clientId || !tenantId || !callback;
async function loginTokenAndStore(payload: {
email: string;
password: string;
}) {
const tokenRes = await fetch("/api/auth/login-token", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
tenantId: props.tenantId,
email: payload.email,
password: payload.password,
captcha,
}),
});
const tokenJson = (await tokenRes.json()) as {
access_token?: string;
refresh_token?: string;
token_type?: string;
expires_in?: number;
message?: string;
};
if (!tokenRes.ok || !tokenJson.access_token || !tokenJson.refresh_token) {
throw new Error(tokenJson.message || "登录失败");
}
try {
sessionStorage.setItem("iam_access_token", tokenJson.access_token);
sessionStorage.setItem("iam_refresh_token", tokenJson.refresh_token);
if (tokenJson.token_type) {
sessionStorage.setItem("iam_token_type", tokenJson.token_type);
}
if (typeof tokenJson.expires_in === "number") {
sessionStorage.setItem("iam_expires_in", String(tokenJson.expires_in));
}
sessionStorage.setItem("iam_token_issued_at", String(Date.now()));
} catch {}
}
async function loginAndRedirect(payload: {
email: string;
password: string;
}) {
await loginTokenAndStore(payload);
const res = await fetch("/api/auth/login", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
clientId: props.clientId,
tenantId: props.tenantId,
callback: props.callback,
email: payload.email,
password: payload.password,
captcha,
rememberMe: true,
}),
});
const json = (await res.json()) as {
redirectTo?: string;
message?: string;
};
if (!res.ok || !json.redirectTo) {
throw new Error(json.message || "登录失败");
}
window.location.href = json.redirectTo;
}
return (
<Card className="w-full max-w-md">
@@ -80,98 +106,62 @@ const LoginForm = (props: {
<CardTitle></CardTitle>
<CardDescription>使 IAM 访</CardDescription>
</CardHeader>
<form onSubmit={onSubmit}>
<CardContent className="space-y-4">
{missingParams ? (
<div className="text-sm text-destructive">
clientIdtenantId callback
</div>
) : null}
{error ? (
<div className="text-sm text-destructive">{error}</div>
) : null}
<CardContent>
<Tabs
value={tab}
onValueChange={(v) => setTab(v as "login" | "register")}
className="w-full"
>
<TabsList className="grid w-full grid-cols-2">
<TabsTrigger value="login"></TabsTrigger>
<TabsTrigger value="register"></TabsTrigger>
</TabsList>
<div className="space-y-2">
<Label htmlFor="email"></Label>
<Input
id="email"
autoComplete="username"
value={email}
onChange={(e) => setEmail(e.target.value)}
placeholder="user@example.com"
disabled={submitting}
required
<TabsContent value="login">
<LoginForm
clientId={props.clientId}
tenantId={props.tenantId}
callback={props.callback}
initialEmail={loginPrefill?.email ?? props.initialEmail}
prefillPassword={loginPrefill?.password}
externalError={loginExternalError}
onClearExternalError={() => setLoginExternalError(null)}
captcha={captcha}
onCaptchaChange={setCaptcha}
captchaKey={captchaKey}
onRefreshCaptcha={refreshCaptcha}
/>
</div>
</TabsContent>
<div className="space-y-2">
<Label htmlFor="password"></Label>
<Input
id="password"
type="password"
autoComplete="current-password"
value={password}
onChange={(e) => setPassword(e.target.value)}
disabled={submitting}
required
<TabsContent value="register">
<RegisterForm
tenantId={props.tenantId}
captcha={captcha}
onCaptchaChange={setCaptcha}
captchaKey={captchaKey}
onRefreshCaptcha={refreshCaptcha}
onRegisterSuccessPrefillLogin={(p) => {
setLoginPrefill(p);
}}
onLoginAfterRegister={async (p) => {
try {
await loginAndRedirect(p);
} catch (err) {
const msg = err instanceof Error ? err.message : "登录失败";
setLoginExternalError(
`注册成功,但登录失败:${msg}。请在“登录”页修正验证码后继续。`,
);
setTab("login");
setCaptcha("");
refreshCaptcha();
}
}}
/>
</div>
<div className="space-y-2">
<Label htmlFor="captcha"></Label>
<div className="flex gap-2">
<Input
id="captcha"
inputMode="numeric"
value={captcha}
onChange={(e) => setCaptcha(e.target.value)}
disabled={submitting}
required
/>
<button
type="button"
className="shrink-0 rounded-md border border-input bg-background px-2"
onClick={() => setCaptchaKey(String(Date.now()))}
aria-label="刷新验证码"
>
<img
alt="captcha"
src={`/api/captcha?key=${encodeURIComponent(captchaKey)}`}
width={120}
height={40}
/>
</button>
</div>
</div>
<div className="flex items-center justify-between">
<label className="flex items-center gap-2 text-sm">
<Checkbox
checked={rememberMe}
onCheckedChange={(v) => setRememberMe(Boolean(v))}
/>
</label>
<Link
className="text-sm underline underline-offset-4"
href={`/forgot-password?tenantId=${encodeURIComponent(tenantId)}`}
>
</Link>
</div>
</CardContent>
<CardFooter className="flex gap-2">
<Button
type="submit"
className="w-full"
disabled={submitting || missingParams}
>
{submitting ? "登录中..." : "登录"}
</Button>
</CardFooter>
</form>
</TabsContent>
</Tabs>
</CardContent>
</Card>
);
};
export default LoginForm;
export default LoginFormCard;

View File

@@ -1,8 +1,8 @@
import * as React from "react"
import * as React from "react";
import { cn } from "@/lib/utils"
import { cn } from "@/lib/utils";
export interface InputProps extends React.InputHTMLAttributes<HTMLInputElement> {}
export type InputProps = React.InputHTMLAttributes<HTMLInputElement>;
const Input = React.forwardRef<HTMLInputElement, InputProps>(
({ className, type, ...props }, ref) => {
@@ -16,10 +16,9 @@ const Input = React.forwardRef<HTMLInputElement, InputProps>(
ref={ref}
{...props}
/>
)
);
},
)
Input.displayName = "Input"
export { Input }
);
Input.displayName = "Input";
export { Input };