Files
planet/frontend/src/pages/Register/Register.tsx
T
linkong 5bdb55f3f1
ci / backend (push) Has been cancelled
ci / frontend (push) Has been cancelled
ci / delivery (push) Has been cancelled
release / images (push) Has been cancelled
release: bump version to 0.74.0
2026-06-30 13:52:52 +08:00

128 lines
5.6 KiB
TypeScript

import axios from 'axios'
import { useEffect, useState, type FormEvent } from 'react'
import { Trans, useTranslation } from 'react-i18next'
import { Link, useNavigate } from 'react-router-dom'
import { AuthButton, AuthField, AuthForm, AuthInput, AuthLinks, AuthNotice, AuthShell } from '../Auth/AuthShell'
import { describeApiError } from '../../i18n/api-errors'
import { useAuthStore } from '../../stores/auth'
const API_URL = import.meta.env.VITE_API_URL || '/api/v1'
const RESEND_COOLDOWN_SECONDS = 60
interface ErrorBody {
response?: {
data?: {
detail?: string | { code?: string; message?: string; retry_after_seconds?: number }
}
}
}
function Register() {
const { t } = useTranslation()
const navigate = useNavigate()
const [step, setStep] = useState<'register' | 'verify'>('register')
const [username, setUsername] = useState('')
const [email, setEmail] = useState('')
const [password, setPassword] = useState('')
const [code, setCode] = useState('')
const [loading, setLoading] = useState(false)
const [resending, setResending] = useState(false)
const [cooldown, setCooldown] = useState(0)
const [feedback, setFeedback] = useState<{ tone: 'error' | 'warning' | 'success' | 'info'; text: string } | null>(null)
useEffect(() => {
if (cooldown <= 0) return
const timer = window.setTimeout(() => setCooldown((value) => value - 1), 1000)
return () => window.clearTimeout(timer)
}, [cooldown])
const onRegister = async (event: FormEvent<HTMLFormElement>) => {
event.preventDefault()
setLoading(true)
setFeedback(null)
try {
await axios.post(`${API_URL}/auth/register`, { username: username.trim(), email: email.trim(), password })
setStep('verify')
setCooldown(RESEND_COOLDOWN_SECONDS)
setFeedback({ tone: 'success', text: t('auth.verificationSent') })
} catch (error) {
setFeedback({ tone: 'error', text: describeApiError(error, t('common.operationFailed')) })
} finally {
setLoading(false)
}
}
const onVerify = async (event: FormEvent<HTMLFormElement>) => {
event.preventDefault()
setLoading(true)
setFeedback(null)
try {
const response = await axios.post(`${API_URL}/auth/verify-email`, { email, code })
const { access_token, user } = response.data
useAuthStore.setState({ token: access_token, user })
axios.defaults.headers.common.Authorization = `Bearer ${access_token}`
navigate('/admin', { replace: true })
} catch (error) {
setFeedback({ tone: 'error', text: describeApiError(error, t('common.operationFailed')) })
} finally {
setLoading(false)
}
}
const onResend = async () => {
if (cooldown > 0 || !email) return
setResending(true)
setFeedback(null)
try {
await axios.post(`${API_URL}/auth/resend-code`, { email, purpose: 'register' })
setCooldown(RESEND_COOLDOWN_SECONDS)
setFeedback({ tone: 'success', text: t('auth.resendSuccess') })
} catch (error) {
const err = error as ErrorBody
const detail = err.response?.data?.detail
if (detail && typeof detail === 'object' && detail.retry_after_seconds) setCooldown(detail.retry_after_seconds)
setFeedback({ tone: 'error', text: describeApiError(error, t('common.operationFailed')) })
} finally {
setResending(false)
}
}
return (
<AuthShell eyebrow={t('auth.createAccount')} title={step === 'register' ? t('auth.registerAccount') : t('auth.verifyEmail')} description={t('auth.registerDescription')}>
{step === 'register' ? (
<AuthForm onSubmit={onRegister}>
{feedback ? <AuthNotice tone={feedback.tone}>{feedback.text}</AuthNotice> : null}
<AuthField label={t('auth.username')} hint={t('auth.usernameHint')}>
<AuthInput value={username} onChange={(event) => setUsername(event.target.value)} minLength={3} maxLength={50} required autoComplete="username" />
</AuthField>
<AuthField label={t('auth.email')}>
<AuthInput value={email} onChange={(event) => setEmail(event.target.value)} type="email" required autoComplete="email" />
</AuthField>
<AuthField label={t('auth.password')} hint={t('auth.passwordHint')}>
<AuthInput value={password} onChange={(event) => setPassword(event.target.value)} type="password" minLength={8} required autoComplete="new-password" />
</AuthField>
<AuthButton type="submit" loading={loading}>{t('auth.register')}</AuthButton>
<AuthLinks><Link className="auth-link" to="/login">{t('auth.alreadyHaveAccount')}</Link></AuthLinks>
</AuthForm>
) : (
<AuthForm onSubmit={onVerify}>
{feedback ? <AuthNotice tone={feedback.tone}>{feedback.text}</AuthNotice> : null}
<AuthNotice><Trans i18nKey="auth.codeSent" values={{ email }} components={{ strong: <strong /> }} /></AuthNotice>
<AuthField label={t('auth.code')}>
<AuthInput value={code} onChange={(event) => setCode(event.target.value)} maxLength={6} inputMode="numeric" required />
</AuthField>
<AuthButton type="submit" loading={loading}>{t('auth.verifyAndLogin')}</AuthButton>
<AuthLinks>
<button className="auth-link auth-link--button" type="button" onClick={() => setStep('register')}>{t('auth.updateEmail')}</button>
<button className="auth-link auth-link--button" type="button" disabled={cooldown > 0 || resending} onClick={onResend}>
{cooldown > 0 ? t('auth.resendCountdown', { seconds: cooldown }) : t('auth.resend')}
</button>
</AuthLinks>
</AuthForm>
)}
</AuthShell>
)
}
export default Register