mirror of
https://github.com/Rain-kl/OpenFlare.git
synced 2026-10-05 07:26:36 +08:00
prettier
This commit is contained in:
@@ -1,67 +1,71 @@
|
||||
"use client"
|
||||
'use client';
|
||||
|
||||
import type {ReactNode} from "react"
|
||||
import {motion} from "motion/react"
|
||||
import {WavesIcon} from "lucide-react"
|
||||
import type { ReactNode } from 'react';
|
||||
import { motion } from 'motion/react';
|
||||
import { WavesIcon } from 'lucide-react';
|
||||
|
||||
import {cn} from "@/lib/utils"
|
||||
import { cn } from '@/lib/utils';
|
||||
|
||||
interface AuthShellProps {
|
||||
children: ReactNode
|
||||
wide?: boolean
|
||||
children: ReactNode;
|
||||
wide?: boolean;
|
||||
}
|
||||
|
||||
export function AuthShell({children, wide = false}: AuthShellProps) {
|
||||
export function AuthShell({ children, wide = false }: AuthShellProps) {
|
||||
return (
|
||||
<main className="relative flex min-h-screen w-full items-center justify-center overflow-x-hidden bg-background px-4 py-6 sm:px-8 sm:py-8 [@media(max-height:700px)]:py-3">
|
||||
<main className='relative flex min-h-screen w-full items-center justify-center overflow-x-hidden bg-background px-4 py-6 sm:px-8 sm:py-8 [@media(max-height:700px)]:py-3'>
|
||||
<div
|
||||
aria-hidden="true"
|
||||
className="pointer-events-none absolute inset-0 bg-[linear-gradient(to_right,var(--border)_1px,transparent_1px),linear-gradient(to_bottom,var(--border)_1px,transparent_1px)] bg-[size:56px_56px] opacity-45 [mask-image:linear-gradient(to_bottom,transparent,black_12%,black_88%,transparent)]"
|
||||
aria-hidden='true'
|
||||
className='pointer-events-none absolute inset-0 bg-[linear-gradient(to_right,var(--border)_1px,transparent_1px),linear-gradient(to_bottom,var(--border)_1px,transparent_1px)] bg-[size:56px_56px] opacity-45 [mask-image:linear-gradient(to_bottom,transparent,black_12%,black_88%,transparent)]'
|
||||
/>
|
||||
<div
|
||||
aria-hidden="true"
|
||||
className="pointer-events-none absolute inset-y-0 left-1/2 w-px -translate-x-1/2 bg-border/70"
|
||||
aria-hidden='true'
|
||||
className='pointer-events-none absolute inset-y-0 left-1/2 w-px -translate-x-1/2 bg-border/70'
|
||||
/>
|
||||
<motion.section
|
||||
initial={{opacity: 0, y: 18}}
|
||||
animate={{opacity: 1, y: 0}}
|
||||
transition={{duration: 0.45, ease: "easeOut"}}
|
||||
initial={{ opacity: 0, y: 18 }}
|
||||
animate={{ opacity: 1, y: 0 }}
|
||||
transition={{ duration: 0.45, ease: 'easeOut' }}
|
||||
className={cn(
|
||||
"relative w-full border-x border-dashed border-border/80 bg-background/95 px-6 py-8 backdrop-blur-sm sm:px-10 sm:py-10 [@media(max-height:700px)]:py-5",
|
||||
wide ? "max-w-2xl" : "max-w-xl",
|
||||
'relative w-full border-x border-dashed border-border/80 bg-background/95 px-6 py-8 backdrop-blur-sm sm:px-10 sm:py-10 [@media(max-height:700px)]:py-5',
|
||||
wide ? 'max-w-2xl' : 'max-w-xl',
|
||||
)}
|
||||
>
|
||||
{children}
|
||||
</motion.section>
|
||||
</main>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
interface AuthHeadingProps {
|
||||
title: string
|
||||
description: string
|
||||
siteName?: string
|
||||
title: string;
|
||||
description: string;
|
||||
siteName?: string;
|
||||
}
|
||||
|
||||
export function AuthHeading({
|
||||
title,
|
||||
description,
|
||||
siteName = "Wavelet",
|
||||
siteName = 'Wavelet',
|
||||
}: AuthHeadingProps) {
|
||||
return (
|
||||
<header className="flex flex-col gap-6 [@media(max-height:700px)]:gap-3">
|
||||
<div className="flex items-center gap-3">
|
||||
<span className="flex size-9 items-center justify-center rounded-full bg-foreground text-background [@media(max-height:700px)]:size-8">
|
||||
<WavesIcon aria-hidden="true" />
|
||||
<header className='flex flex-col gap-6 [@media(max-height:700px)]:gap-3'>
|
||||
<div className='flex items-center gap-3'>
|
||||
<span className='flex size-9 items-center justify-center rounded-full bg-foreground text-background [@media(max-height:700px)]:size-8'>
|
||||
<WavesIcon aria-hidden='true' />
|
||||
</span>
|
||||
<span className='font-semibold tracking-tight [@media(min-height:761px)]:text-lg'>
|
||||
{siteName}
|
||||
</span>
|
||||
<span className="font-semibold tracking-tight [@media(min-height:761px)]:text-lg">{siteName}</span>
|
||||
</div>
|
||||
<div className="flex flex-col gap-1.5 [@media(max-height:700px)]:gap-1">
|
||||
<h1 className="text-2xl font-semibold tracking-tight text-foreground sm:text-3xl [@media(min-height:900px)]:sm:text-4xl">
|
||||
<div className='flex flex-col gap-1.5 [@media(max-height:700px)]:gap-1'>
|
||||
<h1 className='text-2xl font-semibold tracking-tight text-foreground sm:text-3xl [@media(min-height:900px)]:sm:text-4xl'>
|
||||
{title}
|
||||
</h1>
|
||||
<p className="text-sm text-muted-foreground [@media(min-height:900px)]:text-base">{description}</p>
|
||||
<p className='text-sm text-muted-foreground [@media(min-height:900px)]:text-base'>
|
||||
{description}
|
||||
</p>
|
||||
</div>
|
||||
</header>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,20 +1,26 @@
|
||||
'use client'
|
||||
'use client';
|
||||
|
||||
import {useEffect, useRef, useState} from 'react'
|
||||
import {CheckCircle2, Loader2, ShieldAlert, ShieldCheck, ShieldQuestion} from 'lucide-react'
|
||||
import {getCapToken} from '@/lib/cap-solver'
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
import {
|
||||
CheckCircle2,
|
||||
Loader2,
|
||||
ShieldAlert,
|
||||
ShieldCheck,
|
||||
ShieldQuestion,
|
||||
} from 'lucide-react';
|
||||
import { getCapToken } from '@/lib/cap-solver';
|
||||
|
||||
type CapStatus = 'idle' | 'solving' | 'solved' | 'error'
|
||||
type CapStatus = 'idle' | 'solving' | 'solved' | 'error';
|
||||
|
||||
interface CapWidgetProps {
|
||||
/** Called with the one-time token once the challenge is solved */
|
||||
onToken: (token: string) => void
|
||||
onToken: (token: string) => void;
|
||||
/** Called when the challenge fails or encounters an error */
|
||||
onError?: (err: Error) => void
|
||||
onError?: (err: Error) => void;
|
||||
/** Whether to auto-start solving when the component mounts. Defaults to true. */
|
||||
autoStart?: boolean
|
||||
autoStart?: boolean;
|
||||
/** PoW scope sent to the backend */
|
||||
scope?: string
|
||||
scope?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -23,88 +29,95 @@ interface CapWidgetProps {
|
||||
* autoStart=true(默认):挂载后立即在后台运行 PoW 求解,完成后回调 onToken。
|
||||
* autoStart=false:显示「点击开始验证」按钮,用户手动触发后才开始求解。
|
||||
*/
|
||||
export function CapWidget({ onToken, onError, autoStart = true, scope = 'login' }: CapWidgetProps) {
|
||||
const [status, setStatus] = useState<CapStatus>('idle')
|
||||
const [errorMsg, setErrorMsg] = useState('')
|
||||
const solving = useRef(false)
|
||||
export function CapWidget({
|
||||
onToken,
|
||||
onError,
|
||||
autoStart = true,
|
||||
scope = 'login',
|
||||
}: CapWidgetProps) {
|
||||
const [status, setStatus] = useState<CapStatus>('idle');
|
||||
const [errorMsg, setErrorMsg] = useState('');
|
||||
const solving = useRef(false);
|
||||
|
||||
const solve = async () => {
|
||||
if (solving.current) return
|
||||
solving.current = true
|
||||
setStatus('solving')
|
||||
setErrorMsg('')
|
||||
if (solving.current) return;
|
||||
solving.current = true;
|
||||
setStatus('solving');
|
||||
setErrorMsg('');
|
||||
try {
|
||||
const token = await getCapToken(scope)
|
||||
setStatus('solved')
|
||||
onToken(token)
|
||||
const token = await getCapToken(scope);
|
||||
setStatus('solved');
|
||||
onToken(token);
|
||||
} catch (err) {
|
||||
const error = err instanceof Error ? err : new Error(String(err))
|
||||
setStatus('error')
|
||||
setErrorMsg(error.message)
|
||||
onError?.(error)
|
||||
const error = err instanceof Error ? err : new Error(String(err));
|
||||
setStatus('error');
|
||||
setErrorMsg(error.message);
|
||||
onError?.(error);
|
||||
} finally {
|
||||
solving.current = false
|
||||
solving.current = false;
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
// Auto-start on mount (only when autoStart is enabled)
|
||||
useEffect(() => {
|
||||
if (autoStart) {
|
||||
void solve()
|
||||
void solve();
|
||||
}
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [])
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<div className="flex items-center gap-2 rounded-lg border border-border/60 bg-muted/30 px-3 py-2 text-sm">
|
||||
<div className='flex items-center gap-2 rounded-lg border border-border/60 bg-muted/30 px-3 py-2 text-sm'>
|
||||
{/* idle + autoStart=false: 手动触发按钮 */}
|
||||
{status === 'idle' && !autoStart && (
|
||||
<button
|
||||
type="button"
|
||||
className="flex w-full items-center gap-2 text-left"
|
||||
type='button'
|
||||
className='flex w-full items-center gap-2 text-left'
|
||||
onClick={() => void solve()}
|
||||
>
|
||||
<ShieldQuestion className="size-4 shrink-0 text-muted-foreground" />
|
||||
<span className="flex-1 text-muted-foreground">点击开始人机验证</span>
|
||||
<ShieldQuestion className='size-4 shrink-0 text-muted-foreground' />
|
||||
<span className='flex-1 text-muted-foreground'>点击开始人机验证</span>
|
||||
</button>
|
||||
)}
|
||||
|
||||
{/* idle + autoStart=true: 等待自动开始(极短暂状态) */}
|
||||
{status === 'idle' && autoStart && (
|
||||
<>
|
||||
<ShieldAlert className="size-4 shrink-0 text-muted-foreground" />
|
||||
<span className="text-muted-foreground">等待人机验证…</span>
|
||||
<ShieldAlert className='size-4 shrink-0 text-muted-foreground' />
|
||||
<span className='text-muted-foreground'>等待人机验证…</span>
|
||||
</>
|
||||
)}
|
||||
|
||||
{status === 'solving' && (
|
||||
<>
|
||||
<Loader2 className="size-4 shrink-0 animate-spin text-primary" />
|
||||
<span className="text-muted-foreground">正在完成人机验证…</span>
|
||||
<Loader2 className='size-4 shrink-0 animate-spin text-primary' />
|
||||
<span className='text-muted-foreground'>正在完成人机验证…</span>
|
||||
</>
|
||||
)}
|
||||
|
||||
{status === 'solved' && (
|
||||
<>
|
||||
<CheckCircle2 className="size-4 shrink-0 text-green-500" />
|
||||
<span className="text-green-600 dark:text-green-400">人机验证通过</span>
|
||||
<ShieldCheck className="ml-auto size-4 shrink-0 text-green-500" />
|
||||
<CheckCircle2 className='size-4 shrink-0 text-green-500' />
|
||||
<span className='text-green-600 dark:text-green-400'>
|
||||
人机验证通过
|
||||
</span>
|
||||
<ShieldCheck className='ml-auto size-4 shrink-0 text-green-500' />
|
||||
</>
|
||||
)}
|
||||
|
||||
{status === 'error' && (
|
||||
<button
|
||||
type="button"
|
||||
className="flex w-full items-center gap-2 text-left"
|
||||
type='button'
|
||||
className='flex w-full items-center gap-2 text-left'
|
||||
onClick={() => void solve()}
|
||||
>
|
||||
<ShieldAlert className="size-4 shrink-0 text-destructive" />
|
||||
<span className="flex-1 text-destructive">
|
||||
<ShieldAlert className='size-4 shrink-0 text-destructive' />
|
||||
<span className='flex-1 text-destructive'>
|
||||
{errorMsg || '人机验证失败'}
|
||||
</span>
|
||||
<span className="text-xs text-muted-foreground underline">重试</span>
|
||||
<span className='text-xs text-muted-foreground underline'>重试</span>
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,213 +1,235 @@
|
||||
"use client"
|
||||
'use client';
|
||||
|
||||
import {useEffect, useRef, useState} from "react"
|
||||
import {useMutation, useQuery} from "@tanstack/react-query"
|
||||
import {useSearchParams} from "next/navigation"
|
||||
import {EyeIcon, EyeOffIcon} from "lucide-react"
|
||||
import {toast} from "sonner"
|
||||
import Link from "next/link"
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
import { useMutation, useQuery } from '@tanstack/react-query';
|
||||
import { useSearchParams } from 'next/navigation';
|
||||
import { EyeIcon, EyeOffIcon } from 'lucide-react';
|
||||
import { toast } from 'sonner';
|
||||
import Link from 'next/link';
|
||||
|
||||
import {useAuth} from "@/components/providers/auth-provider"
|
||||
import {Button} from "@/components/ui/button"
|
||||
import {Input} from "@/components/ui/input"
|
||||
import {Separator} from "@/components/ui/separator"
|
||||
import {Spinner} from "@/components/ui/spinner"
|
||||
import {Field, FieldGroup, FieldLabel} from "@/components/ui/field"
|
||||
import {CapWidget} from "@/components/auth/cap-widget"
|
||||
import {AuthHeading} from "@/components/auth/auth-shell"
|
||||
import {OTPForm} from "./otp-form"
|
||||
import {AuthService} from "@/lib/services/auth"
|
||||
import {ConfigService} from "@/lib/services/config"
|
||||
import type {LoginRequest} from "@/lib/services/auth/types"
|
||||
import {safeRedirectTarget} from "@/lib/utils"
|
||||
import { useAuth } from '@/components/providers/auth-provider';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Separator } from '@/components/ui/separator';
|
||||
import { Spinner } from '@/components/ui/spinner';
|
||||
import { Field, FieldGroup, FieldLabel } from '@/components/ui/field';
|
||||
import { CapWidget } from '@/components/auth/cap-widget';
|
||||
import { AuthHeading } from '@/components/auth/auth-shell';
|
||||
import { OTPForm } from './otp-form';
|
||||
import { AuthService } from '@/lib/services/auth';
|
||||
import { ConfigService } from '@/lib/services/config';
|
||||
import type { LoginRequest } from '@/lib/services/auth/types';
|
||||
import { safeRedirectTarget } from '@/lib/utils';
|
||||
|
||||
function persistRedirectTarget(searchParams: ReturnType<typeof useSearchParams>) {
|
||||
const callbackUrl = searchParams.get("callbackUrl")
|
||||
if (callbackUrl && typeof window !== "undefined") {
|
||||
sessionStorage.setItem("redirect_after_login", safeRedirectTarget(callbackUrl))
|
||||
function persistRedirectTarget(
|
||||
searchParams: ReturnType<typeof useSearchParams>,
|
||||
) {
|
||||
const callbackUrl = searchParams.get('callbackUrl');
|
||||
if (callbackUrl && typeof window !== 'undefined') {
|
||||
sessionStorage.setItem(
|
||||
'redirect_after_login',
|
||||
safeRedirectTarget(callbackUrl),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
function configBool(value: string | undefined, fallback: boolean) {
|
||||
if (value === undefined) return fallback
|
||||
return value === "true"
|
||||
if (value === undefined) return fallback;
|
||||
return value === 'true';
|
||||
}
|
||||
|
||||
export function LoginForm({ onOTPStateChange }: { onOTPStateChange?: (show: boolean) => void }) {
|
||||
const searchParams = useSearchParams()
|
||||
const { setUser } = useAuth()
|
||||
const [username, setUsername] = useState("")
|
||||
const [password, setPassword] = useState("")
|
||||
const [showPassword, setShowPassword] = useState(false)
|
||||
const [code, setCode] = useState("")
|
||||
const [showLoginCodeInput, setShowLoginCodeInput] = useState(false)
|
||||
const [loginCooldown, setLoginCooldown] = useState(0)
|
||||
const [errorMessage, setErrorMessage] = useState("")
|
||||
const [loginCodeTip, setLoginCodeTip] = useState<React.ReactNode>(null)
|
||||
export function LoginForm({
|
||||
onOTPStateChange,
|
||||
}: {
|
||||
onOTPStateChange?: (show: boolean) => void;
|
||||
}) {
|
||||
const searchParams = useSearchParams();
|
||||
const { setUser } = useAuth();
|
||||
const [username, setUsername] = useState('');
|
||||
const [password, setPassword] = useState('');
|
||||
const [showPassword, setShowPassword] = useState(false);
|
||||
const [code, setCode] = useState('');
|
||||
const [showLoginCodeInput, setShowLoginCodeInput] = useState(false);
|
||||
const [loginCooldown, setLoginCooldown] = useState(0);
|
||||
const [errorMessage, setErrorMessage] = useState('');
|
||||
const [loginCodeTip, setLoginCodeTip] = useState<React.ReactNode>(null);
|
||||
|
||||
useEffect(() => {
|
||||
onOTPStateChange?.(showLoginCodeInput)
|
||||
}, [showLoginCodeInput, onOTPStateChange])
|
||||
onOTPStateChange?.(showLoginCodeInput);
|
||||
}, [showLoginCodeInput, onOTPStateChange]);
|
||||
|
||||
useEffect(() => {
|
||||
if (loginCooldown > 0) {
|
||||
const timer = setTimeout(() => setLoginCooldown(loginCooldown - 1), 1000)
|
||||
return () => clearTimeout(timer)
|
||||
const timer = setTimeout(() => setLoginCooldown(loginCooldown - 1), 1000);
|
||||
return () => clearTimeout(timer);
|
||||
}
|
||||
}, [loginCooldown])
|
||||
}, [loginCooldown]);
|
||||
|
||||
// Cap token management — ref to hold latest token without triggering re-render
|
||||
const capTokenRef = useRef<string | null>(null)
|
||||
const [capReady, setCapReady] = useState(false)
|
||||
const [capError, setCapError] = useState(false)
|
||||
const [capResetKey, setCapResetKey] = useState(0)
|
||||
const capTokenRef = useRef<string | null>(null);
|
||||
const [capReady, setCapReady] = useState(false);
|
||||
const [capError, setCapError] = useState(false);
|
||||
const [capResetKey, setCapResetKey] = useState(0);
|
||||
|
||||
const publicConfigQuery = useQuery({
|
||||
queryKey: ["public-config"],
|
||||
queryKey: ['public-config'],
|
||||
queryFn: () => ConfigService.getPublicConfig(),
|
||||
})
|
||||
});
|
||||
|
||||
const authSourcesQuery = useQuery({
|
||||
queryKey: ["auth-sources"],
|
||||
queryKey: ['auth-sources'],
|
||||
queryFn: () => AuthService.getAuthSources(),
|
||||
})
|
||||
});
|
||||
|
||||
const capEnabled = configBool(publicConfigQuery.data?.cap_login_enabled, false)
|
||||
const capAutoSolve = configBool(publicConfigQuery.data?.cap_auto_solve, true)
|
||||
const capEnabled = configBool(
|
||||
publicConfigQuery.data?.cap_login_enabled,
|
||||
false,
|
||||
);
|
||||
const capAutoSolve = configBool(publicConfigQuery.data?.cap_auto_solve, true);
|
||||
|
||||
const loginMutation = useMutation({
|
||||
mutationFn: (req: LoginRequest) => {
|
||||
const headers: Record<string, string> = {}
|
||||
const headers: Record<string, string> = {};
|
||||
if (capEnabled && capTokenRef.current) {
|
||||
headers["X-Cap-Token"] = capTokenRef.current
|
||||
headers['X-Cap-Token'] = capTokenRef.current;
|
||||
// Consume the token — next login attempt will need a new one
|
||||
capTokenRef.current = null
|
||||
setCapReady(false)
|
||||
capTokenRef.current = null;
|
||||
setCapReady(false);
|
||||
}
|
||||
return AuthService.login(req, Object.keys(headers).length ? headers : undefined)
|
||||
return AuthService.login(
|
||||
req,
|
||||
Object.keys(headers).length ? headers : undefined,
|
||||
);
|
||||
},
|
||||
onSuccess: (user) => {
|
||||
setUser(user)
|
||||
toast.success("登录成功")
|
||||
setUser(user);
|
||||
toast.success('登录成功');
|
||||
},
|
||||
onError: (error: Error) => {
|
||||
const errorMsg = error.message || ""
|
||||
if (errorMsg.startsWith("need_email_code:")) {
|
||||
const emailMasked = errorMsg.substring("need_email_code:".length)
|
||||
const errorMsg = error.message || '';
|
||||
if (errorMsg.startsWith('need_email_code:')) {
|
||||
const emailMasked = errorMsg.substring('need_email_code:'.length);
|
||||
setLoginCodeTip(
|
||||
<>
|
||||
已向您的安全邮箱 <span className="font-medium text-foreground">{emailMasked}</span> 发送了登录验证码。
|
||||
</>
|
||||
)
|
||||
setShowLoginCodeInput(true)
|
||||
setLoginCooldown(60)
|
||||
toast.success("登录验证码已发送至您的邮箱,请注意查收")
|
||||
已向您的安全邮箱{' '}
|
||||
<span className='font-medium text-foreground'>{emailMasked}</span>{' '}
|
||||
发送了登录验证码。
|
||||
</>,
|
||||
);
|
||||
setShowLoginCodeInput(true);
|
||||
setLoginCooldown(60);
|
||||
toast.success('登录验证码已发送至您的邮箱,请注意查收');
|
||||
if (capEnabled) {
|
||||
capTokenRef.current = null
|
||||
setCapReady(false)
|
||||
setCapResetKey((key) => key + 1)
|
||||
capTokenRef.current = null;
|
||||
setCapReady(false);
|
||||
setCapResetKey((key) => key + 1);
|
||||
}
|
||||
return
|
||||
return;
|
||||
}
|
||||
|
||||
if (errorMsg.startsWith("smtp_invalid:")) {
|
||||
const tip = errorMsg.substring("smtp_invalid:".length)
|
||||
setLoginCodeTip("请输入您的登录验证码。")
|
||||
setShowLoginCodeInput(true)
|
||||
setLoginCooldown(0)
|
||||
toast.warning(tip)
|
||||
if (errorMsg.startsWith('smtp_invalid:')) {
|
||||
const tip = errorMsg.substring('smtp_invalid:'.length);
|
||||
setLoginCodeTip('请输入您的登录验证码。');
|
||||
setShowLoginCodeInput(true);
|
||||
setLoginCooldown(0);
|
||||
toast.warning(tip);
|
||||
if (capEnabled) {
|
||||
capTokenRef.current = null
|
||||
setCapReady(false)
|
||||
setCapResetKey((key) => key + 1)
|
||||
capTokenRef.current = null;
|
||||
setCapReady(false);
|
||||
setCapResetKey((key) => key + 1);
|
||||
}
|
||||
return
|
||||
return;
|
||||
}
|
||||
|
||||
setErrorMessage(errorMsg || "登录失败,请重试")
|
||||
setErrorMessage(errorMsg || '登录失败,请重试');
|
||||
if (capEnabled) {
|
||||
capTokenRef.current = null
|
||||
setCapReady(false)
|
||||
setCapResetKey((key) => key + 1)
|
||||
capTokenRef.current = null;
|
||||
setCapReady(false);
|
||||
setCapResetKey((key) => key + 1);
|
||||
}
|
||||
},
|
||||
})
|
||||
});
|
||||
|
||||
const handlePasswordLogin = () => {
|
||||
setErrorMessage("")
|
||||
const trimmedUsername = username.trim()
|
||||
setErrorMessage('');
|
||||
const trimmedUsername = username.trim();
|
||||
if (!trimmedUsername || !password) {
|
||||
toast.error("邮箱/用户名或密码未填写完整", {
|
||||
description: "请先输入邮箱/用户名和密码后再登录",
|
||||
})
|
||||
return
|
||||
toast.error('邮箱/用户名或密码未填写完整', {
|
||||
description: '请先输入邮箱/用户名和密码后再登录',
|
||||
});
|
||||
return;
|
||||
}
|
||||
if (capEnabled && !capReady) {
|
||||
toast.error(
|
||||
capAutoSolve
|
||||
? "人机验证尚未完成,请稍候…"
|
||||
: "请先点击「开始验证」完成人机验证",
|
||||
)
|
||||
return
|
||||
? '人机验证尚未完成,请稍候…'
|
||||
: '请先点击「开始验证」完成人机验证',
|
||||
);
|
||||
return;
|
||||
}
|
||||
loginMutation.mutate({
|
||||
username: trimmedUsername,
|
||||
password,
|
||||
code: showLoginCodeInput ? code.trim() : undefined,
|
||||
})
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
const handleResendLoginCode = () => {
|
||||
setCode("")
|
||||
setCode('');
|
||||
loginMutation.mutate({
|
||||
username: username.trim(),
|
||||
password,
|
||||
})
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
const handleOAuthLogin = async (sourceName: string) => {
|
||||
try {
|
||||
setErrorMessage("")
|
||||
persistRedirectTarget(searchParams)
|
||||
const { authorize_url } = await AuthService.getAuthorizeUrl(sourceName)
|
||||
window.location.href = authorize_url
|
||||
setErrorMessage('');
|
||||
persistRedirectTarget(searchParams);
|
||||
const { authorize_url } = await AuthService.getAuthorizeUrl(sourceName);
|
||||
window.location.href = authorize_url;
|
||||
} catch (error) {
|
||||
toast.error(error instanceof Error ? error.message : "第三方登录失败")
|
||||
toast.error(error instanceof Error ? error.message : '第三方登录失败');
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
const handleCapToken = (token: string) => {
|
||||
capTokenRef.current = token
|
||||
setCapReady(true)
|
||||
setCapError(false)
|
||||
}
|
||||
capTokenRef.current = token;
|
||||
setCapReady(true);
|
||||
setCapError(false);
|
||||
};
|
||||
|
||||
const handleCapError = () => {
|
||||
capTokenRef.current = null
|
||||
setCapReady(false)
|
||||
setCapError(true)
|
||||
}
|
||||
capTokenRef.current = null;
|
||||
setCapReady(false);
|
||||
setCapError(true);
|
||||
};
|
||||
|
||||
const registrationEnabled =
|
||||
configBool(publicConfigQuery.data?.registration_enabled, true) &&
|
||||
configBool(publicConfigQuery.data?.password_register_enabled, true)
|
||||
configBool(publicConfigQuery.data?.password_register_enabled, true);
|
||||
|
||||
const passwordLoginEnabled = configBool(publicConfigQuery.data?.password_login_enabled, true)
|
||||
const oidcLoginEnabled = configBool(publicConfigQuery.data?.oidc_login_enabled, true)
|
||||
const authSources = oidcLoginEnabled ? (authSourcesQuery.data ?? []) : []
|
||||
const passwordLoginEnabled = configBool(
|
||||
publicConfigQuery.data?.password_login_enabled,
|
||||
true,
|
||||
);
|
||||
const oidcLoginEnabled = configBool(
|
||||
publicConfigQuery.data?.oidc_login_enabled,
|
||||
true,
|
||||
);
|
||||
const authSources = oidcLoginEnabled ? (authSourcesQuery.data ?? []) : [];
|
||||
|
||||
const loginDisabled =
|
||||
!passwordLoginEnabled ||
|
||||
loginMutation.isPending ||
|
||||
(capEnabled && capAutoSolve && !capReady && !capError)
|
||||
(capEnabled && capAutoSolve && !capReady && !capError);
|
||||
|
||||
if (publicConfigQuery.isPending) {
|
||||
return (
|
||||
<div className="flex items-center justify-center py-24">
|
||||
<div className='flex items-center justify-center py-24'>
|
||||
<Spinner />
|
||||
</div>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
if (showLoginCodeInput) {
|
||||
@@ -221,54 +243,54 @@ export function LoginForm({ onOTPStateChange }: { onOTPStateChange?: (show: bool
|
||||
onResend={handleResendLoginCode}
|
||||
onSubmit={handlePasswordLogin}
|
||||
/>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-6 [@media(max-height:700px)]:gap-4">
|
||||
<div className='flex flex-col gap-6 [@media(max-height:700px)]:gap-4'>
|
||||
<AuthHeading
|
||||
siteName={publicConfigQuery.data?.site_name}
|
||||
title="登录到您的账号"
|
||||
description="欢迎回来,请输入您的账号信息继续。"
|
||||
title='登录到您的账号'
|
||||
description='欢迎回来,请输入您的账号信息继续。'
|
||||
/>
|
||||
|
||||
<div className="flex flex-col gap-5 [@media(max-height:700px)]:gap-3">
|
||||
<FieldGroup className="gap-4 [@media(max-height:700px)]:gap-3">
|
||||
<Field className="gap-1.5">
|
||||
<FieldLabel htmlFor="username">
|
||||
邮箱或用户名 <span className="text-destructive">*</span>
|
||||
<div className='flex flex-col gap-5 [@media(max-height:700px)]:gap-3'>
|
||||
<FieldGroup className='gap-4 [@media(max-height:700px)]:gap-3'>
|
||||
<Field className='gap-1.5'>
|
||||
<FieldLabel htmlFor='username'>
|
||||
邮箱或用户名 <span className='text-destructive'>*</span>
|
||||
</FieldLabel>
|
||||
<Input
|
||||
id="username"
|
||||
id='username'
|
||||
value={username}
|
||||
onChange={(e) => setUsername(e.target.value)}
|
||||
placeholder="输入邮箱或用户名"
|
||||
autoComplete="username"
|
||||
className="h-10 text-sm [@media(max-height:700px)]:h-9"
|
||||
onKeyDown={(e) => e.key === "Enter" && handlePasswordLogin()}
|
||||
placeholder='输入邮箱或用户名'
|
||||
autoComplete='username'
|
||||
className='h-10 text-sm [@media(max-height:700px)]:h-9'
|
||||
onKeyDown={(e) => e.key === 'Enter' && handlePasswordLogin()}
|
||||
/>
|
||||
</Field>
|
||||
<Field className="gap-1.5">
|
||||
<FieldLabel htmlFor="password">
|
||||
密码 <span className="text-destructive">*</span>
|
||||
<Field className='gap-1.5'>
|
||||
<FieldLabel htmlFor='password'>
|
||||
密码 <span className='text-destructive'>*</span>
|
||||
</FieldLabel>
|
||||
<div className="relative">
|
||||
<div className='relative'>
|
||||
<Input
|
||||
id="password"
|
||||
id='password'
|
||||
value={password}
|
||||
onChange={(e) => setPassword(e.target.value)}
|
||||
type={showPassword ? "text" : "password"}
|
||||
placeholder="输入您的密码"
|
||||
autoComplete="current-password"
|
||||
className="h-10 pr-11 text-sm [@media(max-height:700px)]:h-9"
|
||||
onKeyDown={(e) => e.key === "Enter" && handlePasswordLogin()}
|
||||
type={showPassword ? 'text' : 'password'}
|
||||
placeholder='输入您的密码'
|
||||
autoComplete='current-password'
|
||||
className='h-10 pr-11 text-sm [@media(max-height:700px)]:h-9'
|
||||
onKeyDown={(e) => e.key === 'Enter' && handlePasswordLogin()}
|
||||
/>
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="icon-sm"
|
||||
aria-label={showPassword ? "隐藏密码" : "显示密码"}
|
||||
className="absolute right-1.5 top-1/2 -translate-y-1/2 text-muted-foreground"
|
||||
type='button'
|
||||
variant='ghost'
|
||||
size='icon-sm'
|
||||
aria-label={showPassword ? '隐藏密码' : '显示密码'}
|
||||
className='absolute right-1.5 top-1/2 -translate-y-1/2 text-muted-foreground'
|
||||
onClick={() => setShowPassword((visible) => !visible)}
|
||||
>
|
||||
{showPassword ? <EyeOffIcon /> : <EyeIcon />}
|
||||
@@ -288,15 +310,15 @@ export function LoginForm({ onOTPStateChange }: { onOTPStateChange?: (show: bool
|
||||
)}
|
||||
|
||||
{errorMessage ? (
|
||||
<div className="rounded-lg border border-destructive/30 bg-destructive/5 px-3 py-2 text-sm text-destructive">
|
||||
<div className='rounded-lg border border-destructive/30 bg-destructive/5 px-3 py-2 text-sm text-destructive'>
|
||||
{errorMessage}
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
<Button
|
||||
type="button"
|
||||
className="h-10 w-full [@media(max-height:700px)]:h-9"
|
||||
variant="auth"
|
||||
type='button'
|
||||
className='h-10 w-full [@media(max-height:700px)]:h-9'
|
||||
variant='auth'
|
||||
onClick={handlePasswordLogin}
|
||||
disabled={loginDisabled}
|
||||
>
|
||||
@@ -306,25 +328,25 @@ export function LoginForm({ onOTPStateChange }: { onOTPStateChange?: (show: bool
|
||||
登录中...
|
||||
</>
|
||||
) : (
|
||||
"登录"
|
||||
'登录'
|
||||
)}
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{authSources.length > 0 ? (
|
||||
<div className="flex flex-col gap-3">
|
||||
<div className="flex items-center gap-3">
|
||||
<Separator className="flex-1" />
|
||||
<span className="text-xs text-muted-foreground">或者使用</span>
|
||||
<Separator className="flex-1" />
|
||||
<div className='flex flex-col gap-3'>
|
||||
<div className='flex items-center gap-3'>
|
||||
<Separator className='flex-1' />
|
||||
<span className='text-xs text-muted-foreground'>或者使用</span>
|
||||
<Separator className='flex-1' />
|
||||
</div>
|
||||
<div className="grid gap-2">
|
||||
<div className='grid gap-2'>
|
||||
{authSources.map((source) => (
|
||||
<Button
|
||||
key={source.id}
|
||||
type="button"
|
||||
variant="outline"
|
||||
className="h-10 [@media(max-height:700px)]:h-9"
|
||||
type='button'
|
||||
variant='outline'
|
||||
className='h-10 [@media(max-height:700px)]:h-9'
|
||||
onClick={() => void handleOAuthLogin(source.name)}
|
||||
>
|
||||
{source.display_name || source.name} 登录
|
||||
@@ -335,13 +357,16 @@ export function LoginForm({ onOTPStateChange }: { onOTPStateChange?: (show: bool
|
||||
) : null}
|
||||
|
||||
{registrationEnabled && (
|
||||
<div className="text-center text-sm text-muted-foreground">
|
||||
还没有账号?{" "}
|
||||
<Link href="/register" className="font-medium text-foreground underline underline-offset-4">
|
||||
<div className='text-center text-sm text-muted-foreground'>
|
||||
还没有账号?{' '}
|
||||
<Link
|
||||
href='/register'
|
||||
className='font-medium text-foreground underline underline-offset-4'
|
||||
>
|
||||
立即注册
|
||||
</Link>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,18 +1,17 @@
|
||||
"use client"
|
||||
'use client';
|
||||
|
||||
import {useCallback, useEffect, useRef, useState} from "react"
|
||||
import {AnimatePresence, motion} from "motion/react"
|
||||
import {useRouter, useSearchParams} from "next/navigation"
|
||||
import {toast} from "sonner"
|
||||
import {Spinner} from "@/components/ui/spinner"
|
||||
import {LoginForm} from "@/components/auth/login-form"
|
||||
import {AuthShell} from "@/components/auth/auth-shell"
|
||||
import {Check} from "lucide-react"
|
||||
|
||||
import {AuthService} from "@/lib/services/auth"
|
||||
import {useAuth} from "@/components/providers/auth-provider"
|
||||
import {safeRedirectTarget} from "@/lib/utils"
|
||||
import { useCallback, useEffect, useRef, useState } from 'react';
|
||||
import { AnimatePresence, motion } from 'motion/react';
|
||||
import { useRouter, useSearchParams } from 'next/navigation';
|
||||
import { toast } from 'sonner';
|
||||
import { Spinner } from '@/components/ui/spinner';
|
||||
import { LoginForm } from '@/components/auth/login-form';
|
||||
import { AuthShell } from '@/components/auth/auth-shell';
|
||||
import { Check } from 'lucide-react';
|
||||
|
||||
import { AuthService } from '@/lib/services/auth';
|
||||
import { useAuth } from '@/components/providers/auth-provider';
|
||||
import { safeRedirectTarget } from '@/lib/utils';
|
||||
|
||||
/**
|
||||
* 登录页面组件
|
||||
@@ -25,151 +24,169 @@ import {safeRedirectTarget} from "@/lib/utils"
|
||||
* @returns {React.ReactNode} 登录页面组件
|
||||
*/
|
||||
export function LoginPage() {
|
||||
const router = useRouter()
|
||||
const searchParams = useSearchParams()
|
||||
const { user, loading, setUser } = useAuth()
|
||||
const [showOTP, setShowOTP] = useState(false)
|
||||
const router = useRouter();
|
||||
const searchParams = useSearchParams();
|
||||
const { user, loading, setUser } = useAuth();
|
||||
const [showOTP, setShowOTP] = useState(false);
|
||||
|
||||
/* 处理OAuth回调 */
|
||||
const isOAuthCallback = !!(searchParams.get('state') && searchParams.get('code'))
|
||||
const [isProcessingCallback, setIsProcessingCallback] = useState(isOAuthCallback)
|
||||
const isCheckingSession = !isOAuthCallback && loading
|
||||
const isOAuthCallback = !!(
|
||||
searchParams.get('state') && searchParams.get('code')
|
||||
);
|
||||
const [isProcessingCallback, setIsProcessingCallback] =
|
||||
useState(isOAuthCallback);
|
||||
const isCheckingSession = !isOAuthCallback && loading;
|
||||
|
||||
const [loginSuccess, setLoginSuccess] = useState(false)
|
||||
const redirectedRef = useRef(false)
|
||||
const callbackProcessedRef = useRef(false)
|
||||
const [loginSuccess, setLoginSuccess] = useState(false);
|
||||
const redirectedRef = useRef(false);
|
||||
const callbackProcessedRef = useRef(false);
|
||||
|
||||
const resolveRedirectTarget = useCallback(() => {
|
||||
const callbackUrl = searchParams.get('callbackUrl')
|
||||
const storedRedirect = sessionStorage.getItem('redirect_after_login')
|
||||
const target = callbackUrl || storedRedirect || '/home'
|
||||
const callbackUrl = searchParams.get('callbackUrl');
|
||||
const storedRedirect = sessionStorage.getItem('redirect_after_login');
|
||||
const target = callbackUrl || storedRedirect || '/home';
|
||||
|
||||
if (storedRedirect) {
|
||||
sessionStorage.removeItem('redirect_after_login')
|
||||
sessionStorage.removeItem('redirect_after_login');
|
||||
}
|
||||
|
||||
return safeRedirectTarget(target)
|
||||
}, [searchParams])
|
||||
return safeRedirectTarget(target);
|
||||
}, [searchParams]);
|
||||
|
||||
const resolveRedirectTargetRef = useRef(resolveRedirectTarget)
|
||||
const resolveRedirectTargetRef = useRef(resolveRedirectTarget);
|
||||
useEffect(() => {
|
||||
resolveRedirectTargetRef.current = resolveRedirectTarget
|
||||
}, [resolveRedirectTarget])
|
||||
|
||||
resolveRedirectTargetRef.current = resolveRedirectTarget;
|
||||
}, [resolveRedirectTarget]);
|
||||
|
||||
/* 登录页兜底:已登录用户直接跳转 */
|
||||
useEffect(() => {
|
||||
const state = searchParams.get('state')
|
||||
const code = searchParams.get('code')
|
||||
const state = searchParams.get('state');
|
||||
const code = searchParams.get('code');
|
||||
|
||||
if ((state && code) || loading || !user) {
|
||||
return
|
||||
return;
|
||||
}
|
||||
|
||||
if (!redirectedRef.current) {
|
||||
redirectedRef.current = true
|
||||
router.replace(resolveRedirectTargetRef.current())
|
||||
redirectedRef.current = true;
|
||||
router.replace(resolveRedirectTargetRef.current());
|
||||
}
|
||||
}, [loading, router, searchParams, user])
|
||||
}, [loading, router, searchParams, user]);
|
||||
|
||||
/* 回调逻辑 */
|
||||
useEffect(() => {
|
||||
const handleOAuthCallback = async () => {
|
||||
const state = searchParams.get('state')
|
||||
const code = searchParams.get('code')
|
||||
const state = searchParams.get('state');
|
||||
const code = searchParams.get('code');
|
||||
|
||||
if (state && code) {
|
||||
if (callbackProcessedRef.current) return
|
||||
callbackProcessedRef.current = true
|
||||
if (callbackProcessedRef.current) return;
|
||||
callbackProcessedRef.current = true;
|
||||
|
||||
setIsProcessingCallback(true)
|
||||
setIsProcessingCallback(true);
|
||||
try {
|
||||
const result = await AuthService.handleCallback({ state, code })
|
||||
if (result.status === "need_bind") {
|
||||
toast.info("您的第三方账号未绑定本地账号,系统已关闭注册。请登录已有本地账号进行绑定。")
|
||||
setIsProcessingCallback(false)
|
||||
router.replace('/login')
|
||||
return
|
||||
const result = await AuthService.handleCallback({ state, code });
|
||||
if (result.status === 'need_bind') {
|
||||
toast.info(
|
||||
'您的第三方账号未绑定本地账号,系统已关闭注册。请登录已有本地账号进行绑定。',
|
||||
);
|
||||
setIsProcessingCallback(false);
|
||||
router.replace('/login');
|
||||
return;
|
||||
}
|
||||
if (result.user) {
|
||||
setUser(result.user)
|
||||
setUser(result.user);
|
||||
}
|
||||
setLoginSuccess(true)
|
||||
toast.success(result.status === "bound" ? "绑定成功" : "登录成功")
|
||||
setLoginSuccess(true);
|
||||
toast.success(result.status === 'bound' ? '绑定成功' : '登录成功');
|
||||
|
||||
setTimeout(() => {
|
||||
if (!redirectedRef.current) {
|
||||
redirectedRef.current = true
|
||||
router.replace(resolveRedirectTargetRef.current())
|
||||
redirectedRef.current = true;
|
||||
router.replace(resolveRedirectTargetRef.current());
|
||||
}
|
||||
}, 1500)
|
||||
}, 1500);
|
||||
} catch (error) {
|
||||
console.error('OAuth callback error:', error)
|
||||
toast.error(error instanceof Error ? error.message : "登录失败,请重试")
|
||||
setIsProcessingCallback(false)
|
||||
router.replace('/login')
|
||||
console.error('OAuth callback error:', error);
|
||||
toast.error(
|
||||
error instanceof Error ? error.message : '登录失败,请重试',
|
||||
);
|
||||
setIsProcessingCallback(false);
|
||||
router.replace('/login');
|
||||
}
|
||||
}
|
||||
}
|
||||
handleOAuthCallback()
|
||||
}, [router, searchParams, setUser])
|
||||
};
|
||||
handleOAuthCallback();
|
||||
}, [router, searchParams, setUser]);
|
||||
|
||||
return (
|
||||
<AuthShell wide={showOTP}>
|
||||
<div className="w-full">
|
||||
<AnimatePresence mode="wait">
|
||||
<div className='w-full'>
|
||||
<AnimatePresence mode='wait'>
|
||||
{isProcessingCallback || isCheckingSession ? (
|
||||
<motion.div
|
||||
key={isProcessingCallback ? "processing" : "session-check"}
|
||||
key={isProcessingCallback ? 'processing' : 'session-check'}
|
||||
initial={{ opacity: 0 }}
|
||||
animate={{ opacity: 1 }}
|
||||
exit={{ opacity: 0 }}
|
||||
className="w-full"
|
||||
className='w-full'
|
||||
>
|
||||
{isCheckingSession ? (
|
||||
<div className="flex flex-col items-center justify-center gap-4 py-16">
|
||||
<div className="relative">
|
||||
<Spinner className="size-8" />
|
||||
<div className='flex flex-col items-center justify-center gap-4 py-16'>
|
||||
<div className='relative'>
|
||||
<Spinner className='size-8' />
|
||||
</div>
|
||||
<div className="flex flex-col gap-2 text-center">
|
||||
<h3 className="font-semibold tracking-tight text-foreground">正在检查登录状态</h3>
|
||||
<p className="text-xs text-muted-foreground">请稍候,我们正在确认当前会话...</p>
|
||||
<div className='flex flex-col gap-2 text-center'>
|
||||
<h3 className='font-semibold tracking-tight text-foreground'>
|
||||
正在检查登录状态
|
||||
</h3>
|
||||
<p className='text-xs text-muted-foreground'>
|
||||
请稍候,我们正在确认当前会话...
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
) : loginSuccess ? (
|
||||
<div className="flex flex-col items-center justify-center gap-4 py-16">
|
||||
<div className='flex flex-col items-center justify-center gap-4 py-16'>
|
||||
<motion.div
|
||||
initial={{ scale: 0.5, opacity: 0 }}
|
||||
animate={{ scale: 1, opacity: 1 }}
|
||||
transition={{ type: "spring", stiffness: 300, damping: 20 }}
|
||||
className="flex size-8 items-center justify-center rounded-full bg-primary/10 text-primary ring-1 ring-primary/20"
|
||||
transition={{ type: 'spring', stiffness: 300, damping: 20 }}
|
||||
className='flex size-8 items-center justify-center rounded-full bg-primary/10 text-primary ring-1 ring-primary/20'
|
||||
>
|
||||
<Check className="size-6" strokeWidth={3} />
|
||||
<Check className='size-6' strokeWidth={3} />
|
||||
</motion.div>
|
||||
<div className="flex flex-col gap-2 text-center">
|
||||
<h3 className="font-semibold tracking-tight text-foreground">登录成功</h3>
|
||||
<p className="text-xs text-muted-foreground">正在跳转至控制台...</p>
|
||||
<div className='flex flex-col gap-2 text-center'>
|
||||
<h3 className='font-semibold tracking-tight text-foreground'>
|
||||
登录成功
|
||||
</h3>
|
||||
<p className='text-xs text-muted-foreground'>
|
||||
正在跳转至控制台...
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<div className="flex flex-col items-center justify-center gap-4 py-16">
|
||||
<div className="relative">
|
||||
<Spinner className="size-8" />
|
||||
<div className='flex flex-col items-center justify-center gap-4 py-16'>
|
||||
<div className='relative'>
|
||||
<Spinner className='size-8' />
|
||||
</div>
|
||||
<div className="flex flex-col gap-2 text-center">
|
||||
<h3 className="font-semibold tracking-tight text-foreground">正在验证凭据</h3>
|
||||
<p className="text-xs text-muted-foreground">请稍候,我们正在为您建立安全会话...</p>
|
||||
<div className='flex flex-col gap-2 text-center'>
|
||||
<h3 className='font-semibold tracking-tight text-foreground'>
|
||||
正在验证凭据
|
||||
</h3>
|
||||
<p className='text-xs text-muted-foreground'>
|
||||
请稍候,我们正在为您建立安全会话...
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</motion.div>
|
||||
) : (
|
||||
<motion.div
|
||||
key="login-form-wrapper"
|
||||
key='login-form-wrapper'
|
||||
initial={{ opacity: 0 }}
|
||||
animate={{ opacity: 1 }}
|
||||
transition={{ duration: 0.4 }}
|
||||
className="w-full"
|
||||
className='w-full'
|
||||
>
|
||||
<LoginForm onOTPStateChange={setShowOTP} />
|
||||
</motion.div>
|
||||
@@ -177,5 +194,5 @@ export function LoginPage() {
|
||||
</AnimatePresence>
|
||||
</div>
|
||||
</AuthShell>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,22 +1,27 @@
|
||||
"use client"
|
||||
'use client';
|
||||
|
||||
import * as React from "react"
|
||||
import {RefreshCwIcon} from "lucide-react"
|
||||
import * as React from 'react';
|
||||
import { RefreshCwIcon } from 'lucide-react';
|
||||
|
||||
import {Button} from "@/components/ui/button"
|
||||
import {Field, FieldLabel} from "@/components/ui/field"
|
||||
import {InputOTP, InputOTPGroup, InputOTPSeparator, InputOTPSlot,} from "@/components/ui/input-otp"
|
||||
import {AuthHeading} from "@/components/auth/auth-shell"
|
||||
import {cn} from "@/lib/utils"
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Field, FieldLabel } from '@/components/ui/field';
|
||||
import {
|
||||
InputOTP,
|
||||
InputOTPGroup,
|
||||
InputOTPSeparator,
|
||||
InputOTPSlot,
|
||||
} from '@/components/ui/input-otp';
|
||||
import { AuthHeading } from '@/components/auth/auth-shell';
|
||||
import { cn } from '@/lib/utils';
|
||||
|
||||
interface OTPFormProps {
|
||||
code: string
|
||||
setCode: (val: string) => void
|
||||
loginCodeTip: React.ReactNode
|
||||
loginCooldown: number
|
||||
isPending: boolean
|
||||
onResend: () => void
|
||||
onSubmit: () => void
|
||||
code: string;
|
||||
setCode: (val: string) => void;
|
||||
loginCodeTip: React.ReactNode;
|
||||
loginCooldown: number;
|
||||
isPending: boolean;
|
||||
onResend: () => void;
|
||||
onSubmit: () => void;
|
||||
}
|
||||
|
||||
export function OTPForm({
|
||||
@@ -29,49 +34,54 @@ export function OTPForm({
|
||||
onSubmit,
|
||||
}: OTPFormProps) {
|
||||
return (
|
||||
<div className="flex flex-col gap-6 [@media(max-height:700px)]:gap-4">
|
||||
<div className='flex flex-col gap-6 [@media(max-height:700px)]:gap-4'>
|
||||
<AuthHeading
|
||||
title="验证您的登录"
|
||||
description="输入发送到安全邮箱的 6 位验证码。"
|
||||
title='验证您的登录'
|
||||
description='输入发送到安全邮箱的 6 位验证码。'
|
||||
/>
|
||||
{loginCodeTip ? (
|
||||
<p className="text-sm leading-6 text-muted-foreground">{loginCodeTip}</p>
|
||||
<p className='text-sm leading-6 text-muted-foreground'>
|
||||
{loginCodeTip}
|
||||
</p>
|
||||
) : null}
|
||||
<div className="flex flex-col gap-5 [@media(max-height:700px)]:gap-3">
|
||||
<Field className="gap-3">
|
||||
<div className="flex items-center justify-between">
|
||||
<FieldLabel htmlFor="otp-verification" className="text-sm font-medium">
|
||||
<div className='flex flex-col gap-5 [@media(max-height:700px)]:gap-3'>
|
||||
<Field className='gap-3'>
|
||||
<div className='flex items-center justify-between'>
|
||||
<FieldLabel
|
||||
htmlFor='otp-verification'
|
||||
className='text-sm font-medium'
|
||||
>
|
||||
验证码
|
||||
</FieldLabel>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
type="button"
|
||||
variant='outline'
|
||||
size='sm'
|
||||
type='button'
|
||||
onClick={onResend}
|
||||
disabled={loginCooldown > 0 || isPending}
|
||||
className="h-8 text-xs"
|
||||
className='h-8 text-xs'
|
||||
>
|
||||
<RefreshCwIcon className={cn(isPending && "animate-spin")} />
|
||||
{loginCooldown > 0 ? `${loginCooldown}秒后重发` : "重新发送"}
|
||||
<RefreshCwIcon className={cn(isPending && 'animate-spin')} />
|
||||
{loginCooldown > 0 ? `${loginCooldown}秒后重发` : '重新发送'}
|
||||
</Button>
|
||||
</div>
|
||||
<div className="flex justify-start">
|
||||
<div className='flex justify-start'>
|
||||
<InputOTP
|
||||
maxLength={6}
|
||||
id="otp-verification"
|
||||
id='otp-verification'
|
||||
required
|
||||
value={code}
|
||||
onChange={setCode}
|
||||
onComplete={onSubmit}
|
||||
disabled={isPending}
|
||||
>
|
||||
<InputOTPGroup className="*:data-[slot=input-otp-slot]:h-12 *:data-[slot=input-otp-slot]:w-11 *:data-[slot=input-otp-slot]:text-xl">
|
||||
<InputOTPGroup className='*:data-[slot=input-otp-slot]:h-12 *:data-[slot=input-otp-slot]:w-11 *:data-[slot=input-otp-slot]:text-xl'>
|
||||
<InputOTPSlot index={0} />
|
||||
<InputOTPSlot index={1} />
|
||||
<InputOTPSlot index={2} />
|
||||
</InputOTPGroup>
|
||||
<InputOTPSeparator className="mx-2" />
|
||||
<InputOTPGroup className="*:data-[slot=input-otp-slot]:h-12 *:data-[slot=input-otp-slot]:w-11 *:data-[slot=input-otp-slot]:text-xl">
|
||||
<InputOTPSeparator className='mx-2' />
|
||||
<InputOTPGroup className='*:data-[slot=input-otp-slot]:h-12 *:data-[slot=input-otp-slot]:w-11 *:data-[slot=input-otp-slot]:text-xl'>
|
||||
<InputOTPSlot index={3} />
|
||||
<InputOTPSlot index={4} />
|
||||
<InputOTPSlot index={5} />
|
||||
@@ -80,24 +90,24 @@ export function OTPForm({
|
||||
</div>
|
||||
</Field>
|
||||
<Button
|
||||
type="button"
|
||||
className="h-10 w-full [@media(max-height:700px)]:h-9"
|
||||
variant="auth"
|
||||
type='button'
|
||||
className='h-10 w-full [@media(max-height:700px)]:h-9'
|
||||
variant='auth'
|
||||
onClick={onSubmit}
|
||||
disabled={isPending || code.length < 6}
|
||||
>
|
||||
{isPending ? "验证中..." : "验证"}
|
||||
{isPending ? '验证中...' : '验证'}
|
||||
</Button>
|
||||
<div className="text-center text-sm text-muted-foreground">
|
||||
遇到登录问题?{" "}
|
||||
<div className='text-center text-sm text-muted-foreground'>
|
||||
遇到登录问题?{' '}
|
||||
<a
|
||||
href="#"
|
||||
className="underline underline-offset-4 transition-colors hover:text-primary"
|
||||
href='#'
|
||||
className='underline underline-offset-4 transition-colors hover:text-primary'
|
||||
>
|
||||
联系客服
|
||||
</a>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,225 +1,250 @@
|
||||
"use client"
|
||||
'use client';
|
||||
|
||||
import {useEffect, useMemo, useRef, useState} from "react"
|
||||
import {useMutation, useQuery} from "@tanstack/react-query"
|
||||
import {useRouter, useSearchParams} from "next/navigation"
|
||||
import {toast} from "sonner"
|
||||
import Link from "next/link"
|
||||
import { useEffect, useMemo, useRef, useState } from 'react';
|
||||
import { useMutation, useQuery } from '@tanstack/react-query';
|
||||
import { useRouter, useSearchParams } from 'next/navigation';
|
||||
import { toast } from 'sonner';
|
||||
import Link from 'next/link';
|
||||
|
||||
import {useAuth} from "@/components/providers/auth-provider"
|
||||
import {Button} from "@/components/ui/button"
|
||||
import {Input} from "@/components/ui/input"
|
||||
import {Spinner} from "@/components/ui/spinner"
|
||||
import {Field, FieldGroup, FieldLabel} from "@/components/ui/field"
|
||||
import {AuthHeading} from "@/components/auth/auth-shell"
|
||||
import {CapWidget} from "@/components/auth/cap-widget"
|
||||
import {AuthService} from "@/lib/services/auth"
|
||||
import {ConfigService} from "@/lib/services/config"
|
||||
import type {RegisterRequest} from "@/lib/services/auth/types"
|
||||
import {safeRedirectTarget} from "@/lib/utils"
|
||||
import { useAuth } from '@/components/providers/auth-provider';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Spinner } from '@/components/ui/spinner';
|
||||
import { Field, FieldGroup, FieldLabel } from '@/components/ui/field';
|
||||
import { AuthHeading } from '@/components/auth/auth-shell';
|
||||
import { CapWidget } from '@/components/auth/cap-widget';
|
||||
import { AuthService } from '@/lib/services/auth';
|
||||
import { ConfigService } from '@/lib/services/config';
|
||||
import type { RegisterRequest } from '@/lib/services/auth/types';
|
||||
import { safeRedirectTarget } from '@/lib/utils';
|
||||
|
||||
function getRedirectTarget(searchParams: ReturnType<typeof useSearchParams>) {
|
||||
const callbackUrl = searchParams.get("callbackUrl")
|
||||
const callbackUrl = searchParams.get('callbackUrl');
|
||||
const storedRedirect =
|
||||
typeof window === "undefined"
|
||||
typeof window === 'undefined'
|
||||
? null
|
||||
: sessionStorage.getItem("redirect_after_login")
|
||||
return safeRedirectTarget(callbackUrl || storedRedirect || "/home")
|
||||
: sessionStorage.getItem('redirect_after_login');
|
||||
return safeRedirectTarget(callbackUrl || storedRedirect || '/home');
|
||||
}
|
||||
|
||||
|
||||
function configBool(value: string | undefined, fallback: boolean) {
|
||||
if (value === undefined) return fallback
|
||||
return value === "true"
|
||||
if (value === undefined) return fallback;
|
||||
return value === 'true';
|
||||
}
|
||||
|
||||
export function RegisterForm() {
|
||||
const router = useRouter()
|
||||
const searchParams = useSearchParams()
|
||||
const { setUser } = useAuth()
|
||||
const [username, setUsername] = useState("")
|
||||
const [password, setPassword] = useState("")
|
||||
const [nickname, setNickname] = useState("")
|
||||
const [email, setEmail] = useState("")
|
||||
const [code, setCode] = useState("")
|
||||
const [registerCooldown, setRegisterCooldown] = useState(0)
|
||||
const [errorMessage, setErrorMessage] = useState("")
|
||||
const router = useRouter();
|
||||
const searchParams = useSearchParams();
|
||||
const { setUser } = useAuth();
|
||||
const [username, setUsername] = useState('');
|
||||
const [password, setPassword] = useState('');
|
||||
const [nickname, setNickname] = useState('');
|
||||
const [email, setEmail] = useState('');
|
||||
const [code, setCode] = useState('');
|
||||
const [registerCooldown, setRegisterCooldown] = useState(0);
|
||||
const [errorMessage, setErrorMessage] = useState('');
|
||||
|
||||
useEffect(() => {
|
||||
if (registerCooldown > 0) {
|
||||
const timer = setTimeout(() => setRegisterCooldown(registerCooldown - 1), 1000)
|
||||
return () => clearTimeout(timer)
|
||||
const timer = setTimeout(
|
||||
() => setRegisterCooldown(registerCooldown - 1),
|
||||
1000,
|
||||
);
|
||||
return () => clearTimeout(timer);
|
||||
}
|
||||
}, [registerCooldown])
|
||||
}, [registerCooldown]);
|
||||
|
||||
const publicConfigQuery = useQuery({
|
||||
queryKey: ["public-config"],
|
||||
queryKey: ['public-config'],
|
||||
queryFn: () => ConfigService.getPublicConfig(),
|
||||
})
|
||||
});
|
||||
|
||||
const redirectTarget = useMemo(
|
||||
() => getRedirectTarget(searchParams),
|
||||
[searchParams],
|
||||
)
|
||||
);
|
||||
|
||||
const registrationEnabled =
|
||||
configBool(publicConfigQuery.data?.registration_enabled, true) &&
|
||||
configBool(publicConfigQuery.data?.password_register_enabled, true)
|
||||
configBool(publicConfigQuery.data?.password_register_enabled, true);
|
||||
|
||||
const emailRegisterEnabled = configBool(publicConfigQuery.data?.email_register_verification_enabled, false)
|
||||
const emailRegisterEnabled = configBool(
|
||||
publicConfigQuery.data?.email_register_verification_enabled,
|
||||
false,
|
||||
);
|
||||
|
||||
const capEnabled = configBool(publicConfigQuery.data?.cap_login_enabled, false)
|
||||
const capAutoSolve = configBool(publicConfigQuery.data?.cap_auto_solve, true)
|
||||
const capEnabled = configBool(
|
||||
publicConfigQuery.data?.cap_login_enabled,
|
||||
false,
|
||||
);
|
||||
const capAutoSolve = configBool(publicConfigQuery.data?.cap_auto_solve, true);
|
||||
|
||||
const [capScope, setCapScope] = useState<'send_email_code' | 'register'>('send_email_code')
|
||||
const [capScope, setCapScope] = useState<'send_email_code' | 'register'>(
|
||||
'send_email_code',
|
||||
);
|
||||
|
||||
// 监听 emailRegisterEnabled 改变初始 scope
|
||||
useEffect(() => {
|
||||
setCapScope(emailRegisterEnabled ? 'send_email_code' : 'register')
|
||||
}, [emailRegisterEnabled])
|
||||
setCapScope(emailRegisterEnabled ? 'send_email_code' : 'register');
|
||||
}, [emailRegisterEnabled]);
|
||||
|
||||
const capTokenRef = useRef<string | null>(null)
|
||||
const [capReady, setCapReady] = useState(false)
|
||||
const [capError, setCapError] = useState(false)
|
||||
const [capResetKey, setCapResetKey] = useState(0)
|
||||
const capTokenRef = useRef<string | null>(null);
|
||||
const [capReady, setCapReady] = useState(false);
|
||||
const [capError, setCapError] = useState(false);
|
||||
const [capResetKey, setCapResetKey] = useState(0);
|
||||
|
||||
const handleCapToken = (token: string) => {
|
||||
capTokenRef.current = token
|
||||
setCapReady(true)
|
||||
setCapError(false)
|
||||
}
|
||||
capTokenRef.current = token;
|
||||
setCapReady(true);
|
||||
setCapError(false);
|
||||
};
|
||||
|
||||
const handleCapError = () => {
|
||||
capTokenRef.current = null
|
||||
setCapReady(false)
|
||||
setCapError(true)
|
||||
}
|
||||
capTokenRef.current = null;
|
||||
setCapReady(false);
|
||||
setCapError(true);
|
||||
};
|
||||
|
||||
// Redirect to login if registration is closed
|
||||
useEffect(() => {
|
||||
if (publicConfigQuery.isSuccess && !registrationEnabled) {
|
||||
toast.error("系统注册功能已关闭")
|
||||
router.replace("/login")
|
||||
toast.error('系统注册功能已关闭');
|
||||
router.replace('/login');
|
||||
}
|
||||
}, [publicConfigQuery.isSuccess, registrationEnabled, router])
|
||||
}, [publicConfigQuery.isSuccess, registrationEnabled, router]);
|
||||
|
||||
const registerMutation = useMutation({
|
||||
mutationFn: (req: RegisterRequest) => {
|
||||
const headers: Record<string, string> = {}
|
||||
const headers: Record<string, string> = {};
|
||||
if (capEnabled && capTokenRef.current) {
|
||||
headers["X-Cap-Token"] = capTokenRef.current
|
||||
capTokenRef.current = null
|
||||
setCapReady(false)
|
||||
headers['X-Cap-Token'] = capTokenRef.current;
|
||||
capTokenRef.current = null;
|
||||
setCapReady(false);
|
||||
}
|
||||
return AuthService.register(req, Object.keys(headers).length ? headers : undefined)
|
||||
return AuthService.register(
|
||||
req,
|
||||
Object.keys(headers).length ? headers : undefined,
|
||||
);
|
||||
},
|
||||
onSuccess: (user) => {
|
||||
setUser(user)
|
||||
router.replace(redirectTarget)
|
||||
toast.success("注册并登录成功")
|
||||
setUser(user);
|
||||
router.replace(redirectTarget);
|
||||
toast.success('注册并登录成功');
|
||||
},
|
||||
onError: (error: Error) => {
|
||||
setErrorMessage(error.message || "注册失败,请重试")
|
||||
setErrorMessage(error.message || '注册失败,请重试');
|
||||
if (capEnabled) {
|
||||
capTokenRef.current = null
|
||||
setCapReady(false)
|
||||
setCapResetKey((key) => key + 1)
|
||||
capTokenRef.current = null;
|
||||
setCapReady(false);
|
||||
setCapResetKey((key) => key + 1);
|
||||
}
|
||||
},
|
||||
})
|
||||
});
|
||||
|
||||
const sendRegisterCodeMutation = useMutation({
|
||||
mutationFn: (targetEmail: string) => {
|
||||
const headers: Record<string, string> = {}
|
||||
const headers: Record<string, string> = {};
|
||||
if (capEnabled && capTokenRef.current) {
|
||||
headers["X-Cap-Token"] = capTokenRef.current
|
||||
capTokenRef.current = null
|
||||
setCapReady(false)
|
||||
headers['X-Cap-Token'] = capTokenRef.current;
|
||||
capTokenRef.current = null;
|
||||
setCapReady(false);
|
||||
}
|
||||
return AuthService.sendEmailCode(targetEmail, "register", Object.keys(headers).length ? headers : undefined)
|
||||
return AuthService.sendEmailCode(
|
||||
targetEmail,
|
||||
'register',
|
||||
Object.keys(headers).length ? headers : undefined,
|
||||
);
|
||||
},
|
||||
onSuccess: () => {
|
||||
setRegisterCooldown(60)
|
||||
toast.success("验证码已发送至您的邮箱,请查收")
|
||||
setRegisterCooldown(60);
|
||||
toast.success('验证码已发送至您的邮箱,请查收');
|
||||
if (capEnabled) {
|
||||
setCapScope('register')
|
||||
capTokenRef.current = null
|
||||
setCapReady(false)
|
||||
setCapResetKey((key) => key + 1)
|
||||
setCapScope('register');
|
||||
capTokenRef.current = null;
|
||||
setCapReady(false);
|
||||
setCapResetKey((key) => key + 1);
|
||||
}
|
||||
},
|
||||
onError: (error: Error) => {
|
||||
toast.error(error.message || "发送验证码失败,请重试")
|
||||
toast.error(error.message || '发送验证码失败,请重试');
|
||||
if (capEnabled) {
|
||||
capTokenRef.current = null
|
||||
setCapReady(false)
|
||||
setCapResetKey((key) => key + 1)
|
||||
capTokenRef.current = null;
|
||||
setCapReady(false);
|
||||
setCapResetKey((key) => key + 1);
|
||||
}
|
||||
},
|
||||
})
|
||||
});
|
||||
|
||||
const registerDisabled =
|
||||
registerMutation.isPending ||
|
||||
(capEnabled && capScope === 'register' && capAutoSolve && !capReady && !capError)
|
||||
(capEnabled &&
|
||||
capScope === 'register' &&
|
||||
capAutoSolve &&
|
||||
!capReady &&
|
||||
!capError);
|
||||
|
||||
const sendCodeDisabled =
|
||||
registerCooldown > 0 ||
|
||||
sendRegisterCodeMutation.isPending ||
|
||||
(capEnabled && capScope === 'send_email_code' && capAutoSolve && !capReady && !capError)
|
||||
(capEnabled &&
|
||||
capScope === 'send_email_code' &&
|
||||
capAutoSolve &&
|
||||
!capReady &&
|
||||
!capError);
|
||||
|
||||
const handleSendRegisterCode = () => {
|
||||
const trimmedEmail = email.trim()
|
||||
const trimmedEmail = email.trim();
|
||||
if (!trimmedEmail) {
|
||||
toast.error("请先输入邮箱地址")
|
||||
return
|
||||
toast.error('请先输入邮箱地址');
|
||||
return;
|
||||
}
|
||||
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
|
||||
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
|
||||
if (!emailRegex.test(trimmedEmail)) {
|
||||
toast.error("请输入有效的邮箱地址")
|
||||
return
|
||||
toast.error('请输入有效的邮箱地址');
|
||||
return;
|
||||
}
|
||||
if (capEnabled && capScope === 'send_email_code' && !capReady) {
|
||||
toast.error(
|
||||
capAutoSolve
|
||||
? "人机验证尚未完成,请稍候…"
|
||||
: "请先点击「开始验证」完成人机验证",
|
||||
)
|
||||
return
|
||||
? '人机验证尚未完成,请稍候…'
|
||||
: '请先点击「开始验证」完成人机验证',
|
||||
);
|
||||
return;
|
||||
}
|
||||
sendRegisterCodeMutation.mutate(trimmedEmail)
|
||||
}
|
||||
sendRegisterCodeMutation.mutate(trimmedEmail);
|
||||
};
|
||||
|
||||
const handleRegister = () => {
|
||||
setErrorMessage("")
|
||||
setErrorMessage('');
|
||||
if (!username.trim() || !password) {
|
||||
toast.error("用户名和密码不能为空")
|
||||
return
|
||||
toast.error('用户名和密码不能为空');
|
||||
return;
|
||||
}
|
||||
if (password.length < 8) {
|
||||
toast.error("密码长度不能少于 8 位")
|
||||
return
|
||||
toast.error('密码长度不能少于 8 位');
|
||||
return;
|
||||
}
|
||||
const trimmedEmail = email.trim()
|
||||
const trimmedEmail = email.trim();
|
||||
if (!trimmedEmail) {
|
||||
toast.error("邮箱不能为空")
|
||||
return
|
||||
toast.error('邮箱不能为空');
|
||||
return;
|
||||
}
|
||||
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
|
||||
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
|
||||
if (!emailRegex.test(trimmedEmail)) {
|
||||
toast.error("请输入有效的邮箱地址")
|
||||
return
|
||||
toast.error('请输入有效的邮箱地址');
|
||||
return;
|
||||
}
|
||||
if (emailRegisterEnabled && !code.trim()) {
|
||||
toast.error("验证码不能为空")
|
||||
return
|
||||
toast.error('验证码不能为空');
|
||||
return;
|
||||
}
|
||||
if (capEnabled && capScope === 'register' && !capReady) {
|
||||
toast.error(
|
||||
capAutoSolve
|
||||
? "人机验证尚未完成,请稍候…"
|
||||
: "请先点击「开始验证」完成人机验证",
|
||||
)
|
||||
return
|
||||
? '人机验证尚未完成,请稍候…'
|
||||
: '请先点击「开始验证」完成人机验证',
|
||||
);
|
||||
return;
|
||||
}
|
||||
registerMutation.mutate({
|
||||
username: username.trim(),
|
||||
@@ -227,104 +252,116 @@ export function RegisterForm() {
|
||||
nickname: nickname.trim() || undefined,
|
||||
email: trimmedEmail,
|
||||
code: code.trim() || undefined,
|
||||
})
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
if (publicConfigQuery.isPending) {
|
||||
return (
|
||||
<div className="flex items-center justify-center py-24">
|
||||
<div className='flex items-center justify-center py-24'>
|
||||
<Spinner />
|
||||
</div>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
if (!registrationEnabled) {
|
||||
return null
|
||||
return null;
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-6 [@media(max-height:700px)]:gap-4">
|
||||
<div className='flex flex-col gap-6 [@media(max-height:700px)]:gap-4'>
|
||||
<AuthHeading
|
||||
siteName={publicConfigQuery.data?.site_name}
|
||||
title="创建您的账号"
|
||||
description="填写以下信息,开始使用平台服务。"
|
||||
title='创建您的账号'
|
||||
description='填写以下信息,开始使用平台服务。'
|
||||
/>
|
||||
|
||||
<div className="flex flex-col gap-5 [@media(max-height:700px)]:gap-3">
|
||||
<FieldGroup className="gap-4 [@media(min-width:500px)]:grid [@media(min-width:500px)]:grid-cols-2 [@media(max-height:700px)]:gap-3">
|
||||
<Field className="gap-1.5">
|
||||
<FieldLabel htmlFor="username">用户名 <span className="text-destructive">*</span></FieldLabel>
|
||||
<Input
|
||||
id="username"
|
||||
value={username}
|
||||
onChange={(e) => setUsername(e.target.value)}
|
||||
placeholder="请输入用户名"
|
||||
autoComplete="username"
|
||||
className="h-10 text-sm [@media(max-height:700px)]:h-9"
|
||||
onKeyDown={(e) => e.key === "Enter" && handleRegister()}
|
||||
/>
|
||||
</Field>
|
||||
<Field className="gap-1.5">
|
||||
<FieldLabel htmlFor="nickname">
|
||||
昵称
|
||||
<span className="ml-1 text-xs font-normal text-muted-foreground">(可选)</span>
|
||||
<div className='flex flex-col gap-5 [@media(max-height:700px)]:gap-3'>
|
||||
<FieldGroup className='gap-4 [@media(min-width:500px)]:grid [@media(min-width:500px)]:grid-cols-2 [@media(max-height:700px)]:gap-3'>
|
||||
<Field className='gap-1.5'>
|
||||
<FieldLabel htmlFor='username'>
|
||||
用户名 <span className='text-destructive'>*</span>
|
||||
</FieldLabel>
|
||||
<Input
|
||||
id="nickname"
|
||||
id='username'
|
||||
value={username}
|
||||
onChange={(e) => setUsername(e.target.value)}
|
||||
placeholder='请输入用户名'
|
||||
autoComplete='username'
|
||||
className='h-10 text-sm [@media(max-height:700px)]:h-9'
|
||||
onKeyDown={(e) => e.key === 'Enter' && handleRegister()}
|
||||
/>
|
||||
</Field>
|
||||
<Field className='gap-1.5'>
|
||||
<FieldLabel htmlFor='nickname'>
|
||||
昵称
|
||||
<span className='ml-1 text-xs font-normal text-muted-foreground'>
|
||||
(可选)
|
||||
</span>
|
||||
</FieldLabel>
|
||||
<Input
|
||||
id='nickname'
|
||||
value={nickname}
|
||||
onChange={(e) => setNickname(e.target.value)}
|
||||
placeholder="请输入昵称"
|
||||
autoComplete="nickname"
|
||||
className="h-10 text-sm [@media(max-height:700px)]:h-9"
|
||||
onKeyDown={(e) => e.key === "Enter" && handleRegister()}
|
||||
placeholder='请输入昵称'
|
||||
autoComplete='nickname'
|
||||
className='h-10 text-sm [@media(max-height:700px)]:h-9'
|
||||
onKeyDown={(e) => e.key === 'Enter' && handleRegister()}
|
||||
/>
|
||||
</Field>
|
||||
<Field className="gap-1.5">
|
||||
<FieldLabel htmlFor="email">电子邮箱 <span className="text-destructive">*</span></FieldLabel>
|
||||
<Field className='gap-1.5'>
|
||||
<FieldLabel htmlFor='email'>
|
||||
电子邮箱 <span className='text-destructive'>*</span>
|
||||
</FieldLabel>
|
||||
<Input
|
||||
id="email"
|
||||
id='email'
|
||||
value={email}
|
||||
onChange={(e) => setEmail(e.target.value)}
|
||||
placeholder="请输入电子邮箱"
|
||||
autoComplete="email"
|
||||
className="h-10 text-sm [@media(max-height:700px)]:h-9"
|
||||
onKeyDown={(e) => e.key === "Enter" && handleRegister()}
|
||||
placeholder='请输入电子邮箱'
|
||||
autoComplete='email'
|
||||
className='h-10 text-sm [@media(max-height:700px)]:h-9'
|
||||
onKeyDown={(e) => e.key === 'Enter' && handleRegister()}
|
||||
/>
|
||||
</Field>
|
||||
<Field className="gap-1.5">
|
||||
<FieldLabel htmlFor="password">密码 <span className="text-destructive">*</span></FieldLabel>
|
||||
<Field className='gap-1.5'>
|
||||
<FieldLabel htmlFor='password'>
|
||||
密码 <span className='text-destructive'>*</span>
|
||||
</FieldLabel>
|
||||
<Input
|
||||
id="password"
|
||||
id='password'
|
||||
value={password}
|
||||
onChange={(e) => setPassword(e.target.value)}
|
||||
type="password"
|
||||
placeholder="请输入密码(至少 8 位)"
|
||||
autoComplete="new-password"
|
||||
className="h-10 text-sm [@media(max-height:700px)]:h-9"
|
||||
onKeyDown={(e) => e.key === "Enter" && handleRegister()}
|
||||
type='password'
|
||||
placeholder='请输入密码(至少 8 位)'
|
||||
autoComplete='new-password'
|
||||
className='h-10 text-sm [@media(max-height:700px)]:h-9'
|
||||
onKeyDown={(e) => e.key === 'Enter' && handleRegister()}
|
||||
/>
|
||||
</Field>
|
||||
{emailRegisterEnabled && (
|
||||
<Field className="gap-1.5 [@media(min-width:500px)]:col-span-2">
|
||||
<FieldLabel htmlFor="code">邮箱验证码 <span className="text-destructive">*</span></FieldLabel>
|
||||
<div className="flex gap-2">
|
||||
<Field className='gap-1.5 [@media(min-width:500px)]:col-span-2'>
|
||||
<FieldLabel htmlFor='code'>
|
||||
邮箱验证码 <span className='text-destructive'>*</span>
|
||||
</FieldLabel>
|
||||
<div className='flex gap-2'>
|
||||
<Input
|
||||
id="code"
|
||||
id='code'
|
||||
value={code}
|
||||
onChange={(e) => setCode(e.target.value)}
|
||||
placeholder="请输入 6 位邮箱验证码"
|
||||
placeholder='请输入 6 位邮箱验证码'
|
||||
maxLength={6}
|
||||
className="h-10 flex-1 text-sm [@media(max-height:700px)]:h-9"
|
||||
onKeyDown={(e) => e.key === "Enter" && handleRegister()}
|
||||
className='h-10 flex-1 text-sm [@media(max-height:700px)]:h-9'
|
||||
onKeyDown={(e) => e.key === 'Enter' && handleRegister()}
|
||||
/>
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
type='button'
|
||||
variant='outline'
|
||||
onClick={handleSendRegisterCode}
|
||||
disabled={sendCodeDisabled}
|
||||
className="h-10 w-[120px] text-xs [@media(max-height:700px)]:h-9"
|
||||
className='h-10 w-[120px] text-xs [@media(max-height:700px)]:h-9'
|
||||
>
|
||||
{registerCooldown > 0 ? `${registerCooldown}秒后重发` : "获取验证码"}
|
||||
{registerCooldown > 0
|
||||
? `${registerCooldown}秒后重发`
|
||||
: '获取验证码'}
|
||||
</Button>
|
||||
</div>
|
||||
</Field>
|
||||
@@ -342,15 +379,15 @@ export function RegisterForm() {
|
||||
)}
|
||||
|
||||
{errorMessage ? (
|
||||
<div className="rounded-lg border border-destructive/30 bg-destructive/5 px-3 py-2 text-sm text-destructive">
|
||||
<div className='rounded-lg border border-destructive/30 bg-destructive/5 px-3 py-2 text-sm text-destructive'>
|
||||
{errorMessage}
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
<Button
|
||||
type="button"
|
||||
className="h-10 w-full [@media(max-height:700px)]:h-9"
|
||||
variant="auth"
|
||||
type='button'
|
||||
className='h-10 w-full [@media(max-height:700px)]:h-9'
|
||||
variant='auth'
|
||||
onClick={handleRegister}
|
||||
disabled={registerDisabled}
|
||||
>
|
||||
@@ -360,17 +397,20 @@ export function RegisterForm() {
|
||||
注册中...
|
||||
</>
|
||||
) : (
|
||||
"创建账号"
|
||||
'创建账号'
|
||||
)}
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<div className="text-center text-sm text-muted-foreground">
|
||||
已经有账号?{" "}
|
||||
<Link href="/login" className="font-medium text-foreground underline underline-offset-4">
|
||||
<div className='text-center text-sm text-muted-foreground'>
|
||||
已经有账号?{' '}
|
||||
<Link
|
||||
href='/login'
|
||||
className='font-medium text-foreground underline underline-offset-4'
|
||||
>
|
||||
返回登录
|
||||
</Link>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,12 +1,12 @@
|
||||
"use client"
|
||||
'use client';
|
||||
|
||||
import {RegisterForm} from "@/components/auth/register-form"
|
||||
import {AuthShell} from "@/components/auth/auth-shell"
|
||||
import { RegisterForm } from '@/components/auth/register-form';
|
||||
import { AuthShell } from '@/components/auth/auth-shell';
|
||||
|
||||
export function RegisterPage() {
|
||||
return (
|
||||
<AuthShell wide>
|
||||
<RegisterForm />
|
||||
</AuthShell>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,16 +1,16 @@
|
||||
"use client"
|
||||
'use client';
|
||||
|
||||
import type {ReactNode} from "react"
|
||||
import {Loader2} from "lucide-react"
|
||||
import type { ReactNode } from 'react';
|
||||
import { Loader2 } from 'lucide-react';
|
||||
|
||||
import {ErrorPage} from "@/components/layout/error"
|
||||
import {useUser} from "@/contexts/user-context"
|
||||
import { ErrorPage } from '@/components/layout/error';
|
||||
import { useUser } from '@/contexts/user-context';
|
||||
|
||||
type RequireAuthProps = {
|
||||
children: ReactNode
|
||||
fallback?: ReactNode
|
||||
minHeightClassName?: string
|
||||
}
|
||||
children: ReactNode;
|
||||
fallback?: ReactNode;
|
||||
minHeightClassName?: string;
|
||||
};
|
||||
|
||||
/**
|
||||
* Guards page content until the session user is available.
|
||||
@@ -19,49 +19,48 @@ type RequireAuthProps = {
|
||||
export function RequireAuth({
|
||||
children,
|
||||
fallback,
|
||||
minHeightClassName = "min-h-[400px]",
|
||||
minHeightClassName = 'min-h-[400px]',
|
||||
}: RequireAuthProps) {
|
||||
const {user, loading} = useUser()
|
||||
const { user, loading } = useUser();
|
||||
|
||||
if (loading) {
|
||||
return fallback ?? (
|
||||
<div className={`flex items-center justify-center ${minHeightClassName}`}>
|
||||
<Loader2 className="size-6 animate-spin text-primary" />
|
||||
</div>
|
||||
)
|
||||
return (
|
||||
fallback ?? (
|
||||
<div
|
||||
className={`flex items-center justify-center ${minHeightClassName}`}
|
||||
>
|
||||
<Loader2 className='size-6 animate-spin text-primary' />
|
||||
</div>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
if (!user) {
|
||||
return null
|
||||
return null;
|
||||
}
|
||||
|
||||
return <>{children}</>
|
||||
return <>{children}</>;
|
||||
}
|
||||
|
||||
type RequireAdminAuthProps = {
|
||||
children: ReactNode
|
||||
}
|
||||
children: ReactNode;
|
||||
};
|
||||
|
||||
/** Guards admin routes after the shared shell has rendered. */
|
||||
export function RequireAdminAuth({children}: RequireAdminAuthProps) {
|
||||
const {user, loading} = useUser()
|
||||
export function RequireAdminAuth({ children }: RequireAdminAuthProps) {
|
||||
const { user, loading } = useUser();
|
||||
|
||||
if (loading) {
|
||||
return (
|
||||
<div className="flex min-h-[400px] items-center justify-center">
|
||||
<Loader2 className="size-6 animate-spin text-primary" />
|
||||
<div className='flex min-h-[400px] items-center justify-center'>
|
||||
<Loader2 className='size-6 animate-spin text-primary' />
|
||||
</div>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
if (!user?.is_admin) {
|
||||
return (
|
||||
<ErrorPage
|
||||
title="访问被拒绝"
|
||||
message="您没有权限访问此页面"
|
||||
/>
|
||||
)
|
||||
return <ErrorPage title='访问被拒绝' message='您没有权限访问此页面' />;
|
||||
}
|
||||
|
||||
return <>{children}</>
|
||||
}
|
||||
return <>{children}</>;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user