Registro + activación por email en Next.js (SRP6 + nodemailer)

- lib/mail.ts: transporte SMTP (nodemailer, mismas creds Gmail que Django).
- lib/register.ts: registerAccount (valida, comprueba email existente, crea fila en
  home_accountactivation reutilizando la tabla de Django, envía email de activación);
  activateAccount (crea battlenet_accounts con SRP6 v2 + account con SRP6 Grunt, como
  activate_account_view: expansion=2, battlenet_index=1; borra la activación).
- Route handlers /api/auth/register y /api/auth/activate.
- Páginas app/[locale]/register (RegisterForm cliente) y app/[locale]/activate-account
  (ActivateClient auto-POST al abrir el enlace). Textos en messages (Register, Activate).

Validado: validaciones (missingFields/passwordMismatch/invalidEmail/passwordTooLong);
ciclo completo activación->crea bnet+account->login OK con la cuenta creada
(needsSelection=false), password mala->invalidCredentials. Todo en TS, crypto validada.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
2026-07-12 22:53:09 +00:00
parent e00a439dd9
commit f332fc39ca
12 changed files with 429 additions and 0 deletions
@@ -0,0 +1,55 @@
'use client'
import { useEffect, useRef, useState } from 'react'
import { useTranslations } from 'next-intl'
import { Link } from '@/i18n/navigation'
const ERROR_KEYS = ['invalidLink', 'expiredLink'] as const
export function ActivateClient({ hash }: { hash: string }) {
const t = useTranslations('Activate')
const [state, setState] = useState<'loading' | 'ok' | 'error'>('loading')
const [errorKey, setErrorKey] = useState<string>('invalidLink')
const ran = useRef(false)
useEffect(() => {
if (ran.current) return // evita doble POST en StrictMode
ran.current = true
if (!hash) {
setErrorKey('invalidLink')
setState('error')
return
}
fetch('/api/auth/activate', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ hash }),
})
.then((r) => r.json())
.then((d: { success?: boolean; error?: string }) => {
if (d.success) setState('ok')
else {
setErrorKey((ERROR_KEYS as readonly string[]).includes(d.error ?? '') ? d.error! : 'invalidLink')
setState('error')
}
})
.catch(() => setState('error'))
}, [hash])
return (
<div className="text-center">
{state === 'loading' && <p>{t('activating')}</p>}
{state === 'ok' && (
<>
<p className="text-green-400">{t('success')}</p>
<p className="mt-4">
<Link href="/login" className="text-sky-400 underline">
{t('goLogin')}
</Link>
</p>
</>
)}
{state === 'error' && <p className="text-red-400">{t(errorKey)}</p>}
</div>
)
}
@@ -0,0 +1,20 @@
import { setRequestLocale } from 'next-intl/server'
import { ActivateClient } from './ActivateClient'
export default async function ActivatePage({
params,
searchParams,
}: {
params: Promise<{ locale: string }>
searchParams: Promise<{ act?: string }>
}) {
const { locale } = await params
setRequestLocale(locale)
const { act } = await searchParams
return (
<main className="mx-auto max-w-lg px-4 py-12">
<ActivateClient hash={act ?? ''} />
</main>
)
}
@@ -0,0 +1,74 @@
'use client'
import { useState } from 'react'
import { useTranslations } from 'next-intl'
const ERROR_KEYS = [
'missingFields',
'passwordMismatch',
'passwordTooLong',
'invalidEmail',
'emailExists',
'recruiterNotFound',
] as const
export function RegisterForm() {
const t = useTranslations('Register')
const [form, setForm] = useState({ password: '', confPassword: '', email: '', confEmail: '', recruiter: '' })
const [accepted, setAccepted] = useState(false)
const [busy, setBusy] = useState(false)
const [message, setMessage] = useState<{ ok: boolean; text: string } | null>(null)
function upd(k: string, v: string) {
setForm((f) => ({ ...f, [k]: v }))
}
async function handleSubmit(e: React.FormEvent) {
e.preventDefault()
if (busy || !accepted) return
setBusy(true)
setMessage(null)
try {
const res = await fetch('/api/auth/register', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
credentials: 'same-origin',
body: JSON.stringify(form),
})
const data: { success?: boolean; error?: string } = await res.json()
if (data.success) {
setMessage({ ok: true, text: t('success') })
} else {
const key = (ERROR_KEYS as readonly string[]).includes(data.error ?? '') ? data.error! : 'genericError'
setMessage({ ok: false, text: t(key) })
}
} catch {
setMessage({ ok: false, text: t('genericError') })
} finally {
setBusy(false)
}
}
const input = 'w-full rounded border border-amber-900/60 bg-[#2c1e14] px-3 py-2'
return (
<div className="mx-auto max-w-sm">
<p className="mb-4 text-sm text-amber-200/70">{t('info')}</p>
<form onSubmit={handleSubmit} className="space-y-3">
<input type="password" maxLength={16} placeholder={t('password')} value={form.password} onChange={(e) => upd('password', e.target.value)} className={input} />
<input type="password" maxLength={16} placeholder={t('confPassword')} value={form.confPassword} onChange={(e) => upd('confPassword', e.target.value)} className={input} />
<input type="email" placeholder={t('email')} value={form.email} onChange={(e) => upd('email', e.target.value)} className={input} />
<input type="email" placeholder={t('confEmail')} value={form.confEmail} onChange={(e) => upd('confEmail', e.target.value)} className={input} />
<input type="text" maxLength={12} placeholder={t('recruiter')} value={form.recruiter} onChange={(e) => upd('recruiter', e.target.value)} className={input} />
<label className="flex items-start gap-2 text-left text-sm">
<input type="checkbox" checked={accepted} onChange={(e) => setAccepted(e.target.checked)} className="mt-1" />
<span>{t('terms')}</span>
</label>
<button type="submit" disabled={busy || !accepted} className="w-full rounded bg-amber-600 px-4 py-2 font-semibold text-[#1b120b] disabled:opacity-60">
{busy ? t('creating') : t('submit')}
</button>
</form>
{message && <p className={`mt-3 text-center ${message.ok ? 'text-green-400' : 'text-red-400'}`}>{message.text}</p>}
</div>
)
}
+15
View File
@@ -0,0 +1,15 @@
import { getTranslations, setRequestLocale } from 'next-intl/server'
import { RegisterForm } from './RegisterForm'
export default async function RegisterPage({ params }: { params: Promise<{ locale: string }> }) {
const { locale } = await params
setRequestLocale(locale)
const t = await getTranslations('Register')
return (
<main className="mx-auto max-w-3xl px-4 py-8">
<h1 className="mb-6 text-center text-2xl font-bold text-amber-500">{t('title')}</h1>
<RegisterForm />
</main>
)
}
+16
View File
@@ -0,0 +1,16 @@
import { activateAccount } from '@/lib/register'
export async function POST(request: Request) {
let hash = ''
try {
const body = await request.json()
hash = String(body.hash ?? '')
} catch {
return Response.json({ success: false, error: 'invalidRequest' }, { status: 400 })
}
if (!hash) return Response.json({ success: false, error: 'invalidLink' })
const ip = (request.headers.get('x-forwarded-for') || '0.0.0.0').split(',')[0].trim()
const result = await activateAccount(hash, ip)
return Response.json(result)
}
+18
View File
@@ -0,0 +1,18 @@
import { registerAccount } from '@/lib/register'
export async function POST(request: Request) {
let body: Record<string, string>
try {
body = await request.json()
} catch {
return Response.json({ success: false, error: 'invalidRequest' }, { status: 400 })
}
const result = await registerAccount({
password: body.password ?? '',
confPassword: body.confPassword ?? '',
email: body.email ?? '',
confEmail: body.confEmail ?? '',
recruiter: body.recruiter ?? '',
})
return Response.json(result)
}