Cloudflare Turnstile en login y registro (Next.js)
- lib/turnstile.ts: verifyTurnstile(token, ip) contra siteverify (fail-closed). - components/Turnstile.tsx: widget cliente (carga el script de Cloudflare, callback con el token). Site key por NEXT_PUBLIC_TURNSTILE_SITE_KEY; secreto server-only. - LoginForm/RegisterForm: widget + token en el POST; submit deshabilitado hasta resolver el captcha (si hay site key). - Routes login/register: verifican el token antes de continuar (error captchaFailed). - Catálogos: captchaFailed. Verificado: POST sin token -> captchaFailed en login y registro (enforcement server). Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -3,8 +3,10 @@
|
||||
import { useState } from 'react'
|
||||
import { useTranslations } from 'next-intl'
|
||||
import { useRouter } from '@/i18n/navigation'
|
||||
import { Turnstile } from '@/components/Turnstile'
|
||||
|
||||
const ERROR_KEYS = ['invalidCredentials', 'missingFields', 'invalidRequest'] as const
|
||||
const ERROR_KEYS = ['invalidCredentials', 'missingFields', 'invalidRequest', 'captchaFailed'] as const
|
||||
const SITE_KEY = process.env.NEXT_PUBLIC_TURNSTILE_SITE_KEY
|
||||
|
||||
export function LoginForm() {
|
||||
const t = useTranslations('Login')
|
||||
@@ -13,6 +15,7 @@ export function LoginForm() {
|
||||
const [password, setPassword] = useState('')
|
||||
const [showPw, setShowPw] = useState(false)
|
||||
const [busy, setBusy] = useState(false)
|
||||
const [captcha, setCaptcha] = useState('')
|
||||
const [message, setMessage] = useState<{ ok: boolean; text: string } | null>(null)
|
||||
|
||||
async function handleSubmit(e: React.FormEvent) {
|
||||
@@ -29,7 +32,7 @@ export function LoginForm() {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
credentials: 'same-origin',
|
||||
body: JSON.stringify({ email: email.trim(), password }),
|
||||
body: JSON.stringify({ email: email.trim(), password, turnstileToken: captcha }),
|
||||
})
|
||||
const data: { success?: boolean; needsSelection?: boolean; error?: string } = await res.json()
|
||||
if (data.success) {
|
||||
@@ -77,9 +80,10 @@ export function LoginForm() {
|
||||
{showPw ? '🙈' : '👁'}
|
||||
</button>
|
||||
</div>
|
||||
<Turnstile onVerify={setCaptcha} />
|
||||
<button
|
||||
type="submit"
|
||||
disabled={busy}
|
||||
disabled={busy || (!!SITE_KEY && !captcha)}
|
||||
className="w-full rounded bg-amber-600 px-4 py-2 font-semibold text-[#1b120b] disabled:opacity-60"
|
||||
>
|
||||
{busy ? t('connecting') : t('submit')}
|
||||
|
||||
Reference in New Issue
Block a user