fix(login): add register
This commit is contained in:
6
.eslintrc.json
Normal file
6
.eslintrc.json
Normal file
@@ -0,0 +1,6 @@
|
|||||||
|
{
|
||||||
|
"extends": [
|
||||||
|
"next/core-web-vitals",
|
||||||
|
"next/typescript"
|
||||||
|
]
|
||||||
|
}
|
||||||
46
src/app/api/auth/login-token/route.ts
Normal file
46
src/app/api/auth/login-token/route.ts
Normal file
@@ -0,0 +1,46 @@
|
|||||||
|
import { NextRequest, NextResponse } from "next/server";
|
||||||
|
|
||||||
|
import { IamApiError, iamLogin } from "@/lib/iam";
|
||||||
|
import { verifyCaptchaCookie } from "@/lib/captcha";
|
||||||
|
|
||||||
|
export const runtime = "nodejs";
|
||||||
|
|
||||||
|
type Body = {
|
||||||
|
tenantId?: string;
|
||||||
|
email?: string;
|
||||||
|
password?: string;
|
||||||
|
captcha?: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
export async function POST(req: NextRequest) {
|
||||||
|
const body = (await req.json()) as Body;
|
||||||
|
|
||||||
|
const tenantId = body.tenantId?.trim() ?? "";
|
||||||
|
const email = body.email?.trim() ?? "";
|
||||||
|
const password = body.password ?? "";
|
||||||
|
const captcha = body.captcha?.trim() ?? "";
|
||||||
|
|
||||||
|
if (!tenantId || !email || !password) {
|
||||||
|
return NextResponse.json(
|
||||||
|
{ message: "missing required fields" },
|
||||||
|
{ status: 400 },
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const captchaCookie = req.cookies.get("iam_captcha")?.value;
|
||||||
|
if (!verifyCaptchaCookie(captchaCookie, captcha)) {
|
||||||
|
return NextResponse.json({ message: "invalid captcha" }, { status: 400 });
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const tokens = await iamLogin({ tenantId, email, password });
|
||||||
|
return NextResponse.json(tokens, {
|
||||||
|
status: 200,
|
||||||
|
headers: { "Cache-Control": "no-store" },
|
||||||
|
});
|
||||||
|
} catch (err) {
|
||||||
|
const status = err instanceof IamApiError ? err.status : 500;
|
||||||
|
const message = err instanceof Error ? err.message : "登录失败";
|
||||||
|
return NextResponse.json({ message }, { status });
|
||||||
|
}
|
||||||
|
}
|
||||||
38
src/app/api/auth/register/route.ts
Normal file
38
src/app/api/auth/register/route.ts
Normal file
@@ -0,0 +1,38 @@
|
|||||||
|
import { NextRequest, NextResponse } from "next/server";
|
||||||
|
|
||||||
|
import { IamApiError, iamRegister } from "@/lib/iam";
|
||||||
|
|
||||||
|
export const runtime = "nodejs";
|
||||||
|
|
||||||
|
type Body = {
|
||||||
|
tenantId?: string;
|
||||||
|
email?: string;
|
||||||
|
password?: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
export async function POST(req: NextRequest) {
|
||||||
|
const body = (await req.json()) as Body;
|
||||||
|
|
||||||
|
const tenantId = body.tenantId?.trim() ?? "";
|
||||||
|
const email = body.email?.trim() ?? "";
|
||||||
|
const password = body.password ?? "";
|
||||||
|
|
||||||
|
if (!tenantId || !email || !password) {
|
||||||
|
return NextResponse.json(
|
||||||
|
{ message: "missing required fields" },
|
||||||
|
{ status: 400 },
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const user = await iamRegister({ tenantId, email, password });
|
||||||
|
return NextResponse.json(
|
||||||
|
{ id: user.id, email: user.email },
|
||||||
|
{ status: 201, headers: { "Cache-Control": "no-store" } },
|
||||||
|
);
|
||||||
|
} catch (err) {
|
||||||
|
const status = err instanceof IamApiError ? err.status : 500;
|
||||||
|
const message = err instanceof Error ? err.message : "注册失败";
|
||||||
|
return NextResponse.json({ message }, { status });
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,78 +1,104 @@
|
|||||||
"use client";
|
"use client";
|
||||||
|
|
||||||
import * as React from "react";
|
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 {
|
import {
|
||||||
Card,
|
Card,
|
||||||
CardContent,
|
CardContent,
|
||||||
CardDescription,
|
CardDescription,
|
||||||
CardFooter,
|
|
||||||
CardHeader,
|
CardHeader,
|
||||||
CardTitle,
|
CardTitle,
|
||||||
} from "@/components/ui/card";
|
} 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;
|
clientId: string;
|
||||||
tenantId: string;
|
tenantId: string;
|
||||||
callback: string;
|
callback: string;
|
||||||
initialEmail: string;
|
initialEmail: string;
|
||||||
}) => {
|
}) => {
|
||||||
const [email, setEmail] = React.useState(props.initialEmail);
|
const [tab, setTab] = React.useState<"login" | "register">("login");
|
||||||
const [password, setPassword] = React.useState("");
|
|
||||||
const [captcha, setCaptcha] = React.useState("");
|
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 [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;
|
function refreshCaptcha() {
|
||||||
const tenantId = props.tenantId;
|
setCaptchaKey(String(Date.now()));
|
||||||
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);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
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 (
|
return (
|
||||||
<Card className="w-full max-w-md">
|
<Card className="w-full max-w-md">
|
||||||
@@ -80,98 +106,62 @@ const LoginForm = (props: {
|
|||||||
<CardTitle>统一登录</CardTitle>
|
<CardTitle>统一登录</CardTitle>
|
||||||
<CardDescription>使用 IAM 账号登录以访问业务系统</CardDescription>
|
<CardDescription>使用 IAM 账号登录以访问业务系统</CardDescription>
|
||||||
</CardHeader>
|
</CardHeader>
|
||||||
<form onSubmit={onSubmit}>
|
<CardContent>
|
||||||
<CardContent className="space-y-4">
|
<Tabs
|
||||||
{missingParams ? (
|
value={tab}
|
||||||
<div className="text-sm text-destructive">
|
onValueChange={(v) => setTab(v as "login" | "register")}
|
||||||
缺少 clientId、tenantId 或 callback 参数,无法继续登录
|
className="w-full"
|
||||||
</div>
|
>
|
||||||
) : null}
|
<TabsList className="grid w-full grid-cols-2">
|
||||||
{error ? (
|
<TabsTrigger value="login">登录</TabsTrigger>
|
||||||
<div className="text-sm text-destructive">{error}</div>
|
<TabsTrigger value="register">注册</TabsTrigger>
|
||||||
) : null}
|
</TabsList>
|
||||||
|
|
||||||
<div className="space-y-2">
|
<TabsContent value="login">
|
||||||
<Label htmlFor="email">用户名</Label>
|
<LoginForm
|
||||||
<Input
|
clientId={props.clientId}
|
||||||
id="email"
|
tenantId={props.tenantId}
|
||||||
autoComplete="username"
|
callback={props.callback}
|
||||||
value={email}
|
initialEmail={loginPrefill?.email ?? props.initialEmail}
|
||||||
onChange={(e) => setEmail(e.target.value)}
|
prefillPassword={loginPrefill?.password}
|
||||||
placeholder="user@example.com"
|
externalError={loginExternalError}
|
||||||
disabled={submitting}
|
onClearExternalError={() => setLoginExternalError(null)}
|
||||||
required
|
captcha={captcha}
|
||||||
|
onCaptchaChange={setCaptcha}
|
||||||
|
captchaKey={captchaKey}
|
||||||
|
onRefreshCaptcha={refreshCaptcha}
|
||||||
/>
|
/>
|
||||||
</div>
|
</TabsContent>
|
||||||
|
|
||||||
<div className="space-y-2">
|
<TabsContent value="register">
|
||||||
<Label htmlFor="password">密码</Label>
|
<RegisterForm
|
||||||
<Input
|
tenantId={props.tenantId}
|
||||||
id="password"
|
captcha={captcha}
|
||||||
type="password"
|
onCaptchaChange={setCaptcha}
|
||||||
autoComplete="current-password"
|
captchaKey={captchaKey}
|
||||||
value={password}
|
onRefreshCaptcha={refreshCaptcha}
|
||||||
onChange={(e) => setPassword(e.target.value)}
|
onRegisterSuccessPrefillLogin={(p) => {
|
||||||
disabled={submitting}
|
setLoginPrefill(p);
|
||||||
required
|
}}
|
||||||
|
onLoginAfterRegister={async (p) => {
|
||||||
|
try {
|
||||||
|
await loginAndRedirect(p);
|
||||||
|
} catch (err) {
|
||||||
|
const msg = err instanceof Error ? err.message : "登录失败";
|
||||||
|
setLoginExternalError(
|
||||||
|
`注册成功,但登录失败:${msg}。请在“登录”页修正验证码后继续。`,
|
||||||
|
);
|
||||||
|
setTab("login");
|
||||||
|
setCaptcha("");
|
||||||
|
refreshCaptcha();
|
||||||
|
}
|
||||||
|
}}
|
||||||
/>
|
/>
|
||||||
</div>
|
</TabsContent>
|
||||||
|
</Tabs>
|
||||||
<div className="space-y-2">
|
</CardContent>
|
||||||
<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>
|
|
||||||
</Card>
|
</Card>
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|
||||||
export default LoginForm;
|
export default LoginFormCard;
|
||||||
|
|||||||
@@ -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>(
|
const Input = React.forwardRef<HTMLInputElement, InputProps>(
|
||||||
({ className, type, ...props }, ref) => {
|
({ className, type, ...props }, ref) => {
|
||||||
@@ -16,10 +16,9 @@ const Input = React.forwardRef<HTMLInputElement, InputProps>(
|
|||||||
ref={ref}
|
ref={ref}
|
||||||
{...props}
|
{...props}
|
||||||
/>
|
/>
|
||||||
)
|
);
|
||||||
},
|
},
|
||||||
)
|
);
|
||||||
Input.displayName = "Input"
|
Input.displayName = "Input";
|
||||||
|
|
||||||
export { Input }
|
|
||||||
|
|
||||||
|
export { Input };
|
||||||
|
|||||||
@@ -8,6 +8,16 @@ type AppResponse<T> = {
|
|||||||
details?: unknown;
|
details?: unknown;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
export class IamApiError extends Error {
|
||||||
|
status: number;
|
||||||
|
code?: number;
|
||||||
|
constructor(message: string, status: number, code?: number) {
|
||||||
|
super(message);
|
||||||
|
this.status = status;
|
||||||
|
this.code = code;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
export type IamLoginResponse = {
|
export type IamLoginResponse = {
|
||||||
access_token: string;
|
access_token: string;
|
||||||
refresh_token: string;
|
refresh_token: string;
|
||||||
@@ -20,6 +30,11 @@ export type IamLoginCodeResponse = {
|
|||||||
expiresAt: number;
|
expiresAt: number;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
export type IamRegisterResponse = {
|
||||||
|
id: string;
|
||||||
|
email: string;
|
||||||
|
};
|
||||||
|
|
||||||
export async function iamLogin(params: {
|
export async function iamLogin(params: {
|
||||||
tenantId: string;
|
tenantId: string;
|
||||||
email: string;
|
email: string;
|
||||||
@@ -39,7 +54,31 @@ export async function iamLogin(params: {
|
|||||||
|
|
||||||
const body = (await res.json()) as AppResponse<IamLoginResponse>;
|
const body = (await res.json()) as AppResponse<IamLoginResponse>;
|
||||||
if (!res.ok || body.code !== 0) {
|
if (!res.ok || body.code !== 0) {
|
||||||
throw new Error(body.message || "Login failed");
|
throw new IamApiError(body.message || "Login failed", res.status, body.code);
|
||||||
|
}
|
||||||
|
return body.data;
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function iamRegister(params: {
|
||||||
|
tenantId: string;
|
||||||
|
email: string;
|
||||||
|
password: string;
|
||||||
|
}): Promise<IamRegisterResponse> {
|
||||||
|
const base = mustGetEnv("IAM_SERVICE_BASE_URL").replace(/\/$/, "");
|
||||||
|
const url = `${base}/api/v1/auth/register`;
|
||||||
|
const res = await fetch(url, {
|
||||||
|
method: "POST",
|
||||||
|
headers: {
|
||||||
|
"Content-Type": "application/json",
|
||||||
|
"X-Tenant-ID": params.tenantId,
|
||||||
|
},
|
||||||
|
body: JSON.stringify({ email: params.email, password: params.password }),
|
||||||
|
cache: "no-store",
|
||||||
|
});
|
||||||
|
|
||||||
|
const body = (await res.json()) as AppResponse<IamRegisterResponse>;
|
||||||
|
if (!res.ok || body.code !== 0) {
|
||||||
|
throw new IamApiError(body.message || "Register failed", res.status, body.code);
|
||||||
}
|
}
|
||||||
return body.data;
|
return body.data;
|
||||||
}
|
}
|
||||||
@@ -71,7 +110,7 @@ export async function iamLoginCode(params: {
|
|||||||
const body = (await res.json()) as AppResponse<IamLoginCodeResponse>;
|
const body = (await res.json()) as AppResponse<IamLoginCodeResponse>;
|
||||||
|
|
||||||
if (!res.ok || body.code !== 0) {
|
if (!res.ok || body.code !== 0) {
|
||||||
throw new Error(body.message || "Login failed");
|
throw new IamApiError(body.message || "Login failed", res.status, body.code);
|
||||||
}
|
}
|
||||||
return body.data;
|
return body.data;
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user