Implementa la recuperación de cuenta (contraseña / cuentas / activación) + islas
recover_account_view era un stub que solo renderizaba (los formularios no tenían backend y el HTML arrastraba un reCAPTCHA de otro dominio). Ahora es funcional: Backend: - Modelo PasswordReset (token+email+expiración 1h) + migración 0014. - recover_account_view maneja POST JSON con 3 tipos, todo por email (bnet), con respuestas genéricas anti-enumeración: * password: crea token y envía enlace de reset (emails/password_reset.html). * accountname: envía las cuentas de juego ligadas (emails/account_names.html). * activation: reenvía el enlace de activación pendiente (emails/activation.html). - reset_password_view: GET valida el token (isla), POST re-deriva el verifier SRP6 v2 de la cuenta bnet (bnet.bnet_make_registration) y lo actualiza; marca el token usado. Ruta 'reset-password'. - Resiliente si la BD de cuentas (AzerothCore) no está disponible: mensaje limpio, nunca 500. Frontend (islas Vite): RecoverForm.tsx (selector de tipo + email) y ResetPassword.tsx (nueva contraseña con token). Se elimina el reCAPTCHA roto; se puede añadir uno propio si se aportan claves. Verificado en producción: los 3 flujos devuelven éxito genérico; reset valida token y contraseñas; token válido no provoca 500. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,97 @@
|
||||
import { useState } from 'react'
|
||||
|
||||
interface Props {
|
||||
recoverUrl: string
|
||||
csrfToken: string
|
||||
}
|
||||
|
||||
const OPTIONS = [
|
||||
{ value: 'password', label: 'Contraseña' },
|
||||
{ value: 'accountname', label: 'Nombre de cuenta' },
|
||||
{ value: 'activation', label: 'Enlace de activación' },
|
||||
] as const
|
||||
|
||||
export function RecoverForm({ recoverUrl, csrfToken }: Props) {
|
||||
const [type, setType] = useState<string>('password')
|
||||
const [email, setEmail] = useState('')
|
||||
const [busy, setBusy] = useState(false)
|
||||
const [message, setMessage] = useState<{ ok: boolean; text: string } | null>(null)
|
||||
|
||||
async function handleSubmit(e: React.FormEvent) {
|
||||
e.preventDefault()
|
||||
if (busy) return
|
||||
setBusy(true)
|
||||
setMessage(null)
|
||||
|
||||
const body = new URLSearchParams()
|
||||
body.set('type', type)
|
||||
body.set('email', email.trim())
|
||||
body.set('csrfmiddlewaretoken', csrfToken)
|
||||
|
||||
try {
|
||||
const resp = await fetch(recoverUrl, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/x-www-form-urlencoded',
|
||||
'X-CSRFToken': csrfToken,
|
||||
Accept: 'application/json',
|
||||
},
|
||||
credentials: 'same-origin',
|
||||
body: body.toString(),
|
||||
})
|
||||
if (!resp.ok) throw new Error(`HTTP ${resp.status}`)
|
||||
const data: { success?: boolean; message?: string } = await resp.json()
|
||||
setMessage({ ok: !!data.success, text: data.message || '' })
|
||||
} catch {
|
||||
setMessage({ ok: false, text: 'Error en el servidor. Inténtalo de nuevo más tarde.' })
|
||||
} finally {
|
||||
setBusy(false)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<p>Escoge la opción acorde a la información que quieres recuperar</p>
|
||||
<br />
|
||||
<form id="nw-recover-form" onSubmit={handleSubmit} acceptCharset="utf-8">
|
||||
<select id="selection" value={type} onChange={(e) => setType(e.target.value)}>
|
||||
{OPTIONS.map((o) => (
|
||||
<option key={o.value} value={o.value}>
|
||||
{o.label}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
<table className="middle-center-table">
|
||||
<tbody>
|
||||
<tr>
|
||||
<td>
|
||||
<input
|
||||
type="email"
|
||||
name="email"
|
||||
id="email"
|
||||
placeholder="Correo electrónico de Gmail"
|
||||
required
|
||||
value={email}
|
||||
onChange={(e) => setEmail(e.target.value)}
|
||||
/>
|
||||
</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>
|
||||
<button type="submit" className="recover-button" disabled={busy}>
|
||||
{busy ? 'Enviando…' : 'Solicitar'}
|
||||
</button>
|
||||
</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</form>
|
||||
<hr />
|
||||
<div className="alert-message" id="recover-response" style={{ display: message ? 'block' : 'none' }}>
|
||||
{message && (
|
||||
<span className={message.ok ? 'ok-form-response' : 'red-form-response'}>{message.text}</span>
|
||||
)}
|
||||
</div>
|
||||
</>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,131 @@
|
||||
import { useState } from 'react'
|
||||
|
||||
interface Props {
|
||||
valid: boolean
|
||||
token: string
|
||||
resetUrl: string
|
||||
recoverUrl: string
|
||||
csrfToken: string
|
||||
}
|
||||
|
||||
export function ResetPassword({ valid, token, resetUrl, recoverUrl, csrfToken }: Props) {
|
||||
const [password, setPassword] = useState('')
|
||||
const [confPassword, setConfPassword] = useState('')
|
||||
const [showPw, setShowPw] = useState(false)
|
||||
const [busy, setBusy] = useState(false)
|
||||
const [message, setMessage] = useState<{ ok: boolean; text: string } | null>(null)
|
||||
const [done, setDone] = useState(false)
|
||||
|
||||
if (!valid) {
|
||||
return (
|
||||
<div className="body-box-content centered">
|
||||
<p className="red-form-response">El enlace no es válido o ha caducado.</p>
|
||||
<br />
|
||||
<p>
|
||||
Puedes solicitar uno nuevo en <a href={recoverUrl}>recuperar cuenta</a>.
|
||||
</p>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
async function handleSubmit(e: React.FormEvent) {
|
||||
e.preventDefault()
|
||||
if (busy || done) return
|
||||
if (password.trim() === '' || password.trim() !== confPassword.trim()) {
|
||||
setMessage({ ok: false, text: 'Las contraseñas no coinciden.' })
|
||||
return
|
||||
}
|
||||
setBusy(true)
|
||||
setMessage(null)
|
||||
|
||||
const body = new URLSearchParams()
|
||||
body.set('token', token)
|
||||
body.set('new-password', password.trim())
|
||||
body.set('conf-password', confPassword.trim())
|
||||
body.set('csrfmiddlewaretoken', csrfToken)
|
||||
|
||||
try {
|
||||
const resp = await fetch(resetUrl, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/x-www-form-urlencoded',
|
||||
'X-CSRFToken': csrfToken,
|
||||
Accept: 'application/json',
|
||||
},
|
||||
credentials: 'same-origin',
|
||||
body: body.toString(),
|
||||
})
|
||||
if (!resp.ok) throw new Error(`HTTP ${resp.status}`)
|
||||
const data: { success?: boolean; message?: string; redirect?: string } = await resp.json()
|
||||
setMessage({ ok: !!data.success, text: data.message || '' })
|
||||
if (data.success) {
|
||||
setDone(true)
|
||||
if (data.redirect) {
|
||||
setTimeout(() => {
|
||||
window.location.href = data.redirect as string
|
||||
}, 2500)
|
||||
}
|
||||
} else {
|
||||
setBusy(false)
|
||||
}
|
||||
} catch {
|
||||
setMessage({ ok: false, text: 'Error en el servidor. Inténtalo de nuevo más tarde.' })
|
||||
setBusy(false)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="body-box-content centered">
|
||||
<form id="nw-reset-form" onSubmit={handleSubmit} acceptCharset="utf-8">
|
||||
<table className="middle-center-table">
|
||||
<tbody>
|
||||
<tr>
|
||||
<td>
|
||||
<input
|
||||
type={showPw ? 'text' : 'password'}
|
||||
maxLength={16}
|
||||
name="new-password"
|
||||
id="new-password"
|
||||
placeholder="Nueva contraseña"
|
||||
autoFocus
|
||||
value={password}
|
||||
onChange={(e) => setPassword(e.target.value)}
|
||||
/>
|
||||
<span
|
||||
className={`far toggle-password ${showPw ? 'fa-eye-slash' : 'fa-eye'}`}
|
||||
onClick={() => setShowPw((v) => !v)}
|
||||
/>
|
||||
</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>
|
||||
<input
|
||||
type={showPw ? 'text' : 'password'}
|
||||
maxLength={16}
|
||||
name="conf-password"
|
||||
id="conf-password"
|
||||
placeholder="Confirmar contraseña"
|
||||
value={confPassword}
|
||||
onChange={(e) => setConfPassword(e.target.value)}
|
||||
/>
|
||||
</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>
|
||||
<button type="submit" className="login-button" disabled={busy || done}>
|
||||
{done ? 'Hecho' : busy ? 'Guardando…' : 'Restablecer contraseña'}
|
||||
</button>
|
||||
</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</form>
|
||||
<hr />
|
||||
<div className="alert-message" style={{ display: message ? 'block' : 'none' }}>
|
||||
{message && (
|
||||
<span className={message.ok ? 'ok-form-response' : 'red-form-response'}>{message.text}</span>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
import { StrictMode } from 'react'
|
||||
import { createRoot } from 'react-dom/client'
|
||||
import { RecoverForm } from '../components/RecoverForm'
|
||||
|
||||
const el = document.getElementById('recover-app')
|
||||
if (el) {
|
||||
createRoot(el).render(
|
||||
<StrictMode>
|
||||
<RecoverForm recoverUrl={el.dataset.recoverUrl || ''} csrfToken={el.dataset.csrf || ''} />
|
||||
</StrictMode>,
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
import { StrictMode } from 'react'
|
||||
import { createRoot } from 'react-dom/client'
|
||||
import { ResetPassword } from '../components/ResetPassword'
|
||||
|
||||
const el = document.getElementById('reset-password-app')
|
||||
if (el) {
|
||||
createRoot(el).render(
|
||||
<StrictMode>
|
||||
<ResetPassword
|
||||
valid={el.dataset.valid === 'true'}
|
||||
token={el.dataset.token || ''}
|
||||
resetUrl={el.dataset.resetUrl || ''}
|
||||
recoverUrl={el.dataset.recoverUrl || 'recover'}
|
||||
csrfToken={el.dataset.csrf || ''}
|
||||
/>
|
||||
</StrictMode>,
|
||||
)
|
||||
}
|
||||
@@ -18,6 +18,8 @@ export default defineConfig({
|
||||
login: resolve(__dirname, 'src/entries/login.tsx'),
|
||||
register: resolve(__dirname, 'src/entries/register.tsx'),
|
||||
select_account: resolve(__dirname, 'src/entries/select_account.tsx'),
|
||||
recover: resolve(__dirname, 'src/entries/recover.tsx'),
|
||||
reset_password: resolve(__dirname, 'src/entries/reset_password.tsx'),
|
||||
},
|
||||
},
|
||||
},
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
# Generated by Django 6.0.7 on 2026-07-12 20:53
|
||||
|
||||
import django.utils.timezone
|
||||
from django.db import migrations, models
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('home', '0013_stripelog_fulfilled'),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.CreateModel(
|
||||
name='PasswordReset',
|
||||
fields=[
|
||||
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
|
||||
('email', models.EmailField(max_length=254)),
|
||||
('token', models.CharField(max_length=64, unique=True)),
|
||||
('created_at', models.DateTimeField(default=django.utils.timezone.now)),
|
||||
('used', models.BooleanField(default=False)),
|
||||
],
|
||||
),
|
||||
]
|
||||
@@ -28,6 +28,20 @@ class AccountActivation(models.Model):
|
||||
def __str__(self):
|
||||
return f"Activation for {self.username}"
|
||||
|
||||
class PasswordReset(models.Model):
|
||||
"""Token de restablecimiento de contraseña (cuenta Battle.net, por email)."""
|
||||
email = models.EmailField()
|
||||
token = models.CharField(max_length=64, unique=True)
|
||||
created_at = models.DateTimeField(default=timezone.now)
|
||||
used = models.BooleanField(default=False)
|
||||
|
||||
def is_expired(self):
|
||||
return timezone.now() > self.created_at + timezone.timedelta(hours=1)
|
||||
|
||||
def __str__(self):
|
||||
return f"PasswordReset for {self.email}"
|
||||
|
||||
|
||||
class SecurityToken(models.Model):
|
||||
user = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True)
|
||||
token = models.CharField(max_length=6)
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
<!DOCTYPE html>
|
||||
|
||||
{% include 'partials/head.html' %}
|
||||
{% include 'partials/header.html' %}
|
||||
{% include 'partials/video.html' %}
|
||||
{% load django_vite %}
|
||||
<div class="main-page">
|
||||
<div class="middle-content">
|
||||
<div class="body-content">
|
||||
<div class="title-content">
|
||||
<h1>Restablecer contraseña</h1>
|
||||
</div>
|
||||
<div class="box-content">
|
||||
<!-- Isla React (Vite): fija la nueva contraseña con el token del enlace.
|
||||
POST a {% url 'reset_password' %} (JSON) -> re-deriva el verifier bnet. -->
|
||||
<div id="reset-password-app"
|
||||
data-csrf="{{ csrf_token }}"
|
||||
data-valid="{{ valid|yesno:'true,false' }}"
|
||||
data-token="{{ token }}"
|
||||
data-reset-url="{% url 'reset_password' %}"
|
||||
data-recover-url="{% url 'recover' %}"></div>
|
||||
{% vite_asset 'src/entries/reset_password.tsx' %}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
{% include 'partials/social.html' %}
|
||||
{% include 'partials/footer.html' %}
|
||||
{% include 'partials/final.html' %}
|
||||
@@ -0,0 +1,34 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="es">
|
||||
<head><meta charset="utf-8"></head>
|
||||
<body style="margin:0;padding:0;background:#1b120b;font-family:Arial,Helvetica,sans-serif;color:#e8dccb;">
|
||||
<table role="presentation" width="100%" cellpadding="0" cellspacing="0" style="background:#1b120b;padding:24px 0;">
|
||||
<tr>
|
||||
<td align="center">
|
||||
<table role="presentation" width="600" cellpadding="0" cellspacing="0" style="max-width:600px;width:100%;background:#241812;border:1px solid #4a3320;border-radius:8px;">
|
||||
<tr>
|
||||
<td style="padding:28px 32px;">
|
||||
<h1 style="margin:0 0 8px;font-size:20px;color:#d79602;">{{ NOMBRE_SERVIDOR }}</h1>
|
||||
<h2 style="margin:0 0 16px;font-size:16px;color:#e8dccb;">Tus cuentas de juego</h2>
|
||||
<p style="margin:0 0 12px;line-height:1.5;">Hola,</p>
|
||||
<p style="margin:0 0 16px;line-height:1.5;">Estas son las cuentas de juego asociadas a tu cuenta Battle.net (<strong>{{ email }}</strong>). Recuerda: para iniciar sesión en la web usas tu <strong>correo electrónico</strong>.</p>
|
||||
<table role="presentation" cellpadding="0" cellspacing="0" style="width:100%;border-collapse:collapse;margin:0 0 16px;">
|
||||
{% for a in accounts %}
|
||||
<tr>
|
||||
<td style="padding:10px 14px;border:1px solid #4a3320;background:#2c1e14;color:#e8dccb;">{{ a.username }}</td>
|
||||
</tr>
|
||||
{% empty %}
|
||||
<tr>
|
||||
<td style="padding:10px 14px;border:1px solid #4a3320;background:#2c1e14;color:#b1997f;">No hay cuentas de juego asociadas todavía.</td>
|
||||
</tr>
|
||||
{% endfor %}
|
||||
</table>
|
||||
<p style="margin:0;line-height:1.5;font-size:13px;color:#b1997f;">Si no has solicitado esta información, ignora este correo.</p>
|
||||
</td>
|
||||
</tr>
|
||||
</table>
|
||||
</td>
|
||||
</tr>
|
||||
</table>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,29 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="es">
|
||||
<head><meta charset="utf-8"></head>
|
||||
<body style="margin:0;padding:0;background:#1b120b;font-family:Arial,Helvetica,sans-serif;color:#e8dccb;">
|
||||
<table role="presentation" width="100%" cellpadding="0" cellspacing="0" style="background:#1b120b;padding:24px 0;">
|
||||
<tr>
|
||||
<td align="center">
|
||||
<table role="presentation" width="600" cellpadding="0" cellspacing="0" style="max-width:600px;width:100%;background:#241812;border:1px solid #4a3320;border-radius:8px;">
|
||||
<tr>
|
||||
<td style="padding:28px 32px;">
|
||||
<h1 style="margin:0 0 8px;font-size:20px;color:#d79602;">{{ NOMBRE_SERVIDOR }}</h1>
|
||||
<h2 style="margin:0 0 16px;font-size:16px;color:#e8dccb;">Restablecer contraseña</h2>
|
||||
<p style="margin:0 0 12px;line-height:1.5;">Hola,</p>
|
||||
<p style="margin:0 0 12px;line-height:1.5;">Hemos recibido una solicitud para restablecer la contraseña de la cuenta Battle.net asociada a <strong>{{ email }}</strong>.</p>
|
||||
<p style="margin:0 0 20px;line-height:1.5;">Pulsa el botón para elegir una nueva contraseña. El enlace caduca en 1 hora.</p>
|
||||
<p style="margin:0 0 20px;">
|
||||
<a href="{{ reset_link }}" style="display:inline-block;padding:12px 22px;background:#d79602;color:#1b120b;text-decoration:none;border-radius:6px;font-weight:bold;">Restablecer contraseña</a>
|
||||
</p>
|
||||
<p style="margin:0 0 8px;line-height:1.5;font-size:13px;color:#b1997f;">Si el botón no funciona, copia esta dirección en tu navegador:</p>
|
||||
<p style="margin:0 0 20px;line-height:1.5;font-size:13px;word-break:break-all;"><a href="{{ reset_link }}" style="color:#2471a9;">{{ reset_link }}</a></p>
|
||||
<p style="margin:0;line-height:1.5;font-size:13px;color:#b1997f;">Si no has solicitado este cambio, ignora este correo: tu contraseña no se modificará.</p>
|
||||
</td>
|
||||
</tr>
|
||||
</table>
|
||||
</td>
|
||||
</tr>
|
||||
</table>
|
||||
</body>
|
||||
</html>
|
||||
@@ -1,3 +1,4 @@
|
||||
{% load django_vite %}
|
||||
<div class="main-page">
|
||||
<div class="middle-content">
|
||||
<div class="body-content">
|
||||
@@ -7,15 +8,15 @@
|
||||
<div class="body-box-content justified">
|
||||
<span>Si has olvidado la contraseña de la cuenta:</span>
|
||||
<p>- Selecciona la opción 'Contraseña'.</p>
|
||||
<p>- Escribe Nombre de usuario.</p>
|
||||
<p>- Escribe el correo electrónico de la cuenta.</p>
|
||||
<p>- Un correo será enviado con un enlace para generar una contraseña nueva.</p>
|
||||
<br>
|
||||
<span>Si has olvidado el nombre de la cuenta:</span>
|
||||
<span>Si has olvidado con qué cuentas de juego cuentas:</span>
|
||||
<p>- Selecciona la opción 'Nombre de cuenta'.</p>
|
||||
<p>- Escribe el correo electrónico.</p>
|
||||
<p>- Un correo será enviado con todas las cuentas ligadas al correo.</p>
|
||||
<br>
|
||||
<span>Si no has recibido en enlace de activación:</span>
|
||||
<span>Si no has recibido el enlace de activación:</span>
|
||||
<p>- Selecciona la opción 'Enlace de activación'.</p>
|
||||
<p>- Escribe el correo electrónico.</p>
|
||||
<p>- Un correo será enviado con el enlace de activación.</p>
|
||||
@@ -25,57 +26,15 @@
|
||||
<div class="box-content">
|
||||
<div class="title-box-content"><h2>Solicitud de información</h2></div>
|
||||
<div class="body-box-content centered">
|
||||
<p>Escoge la opción acorde a la información que quieres recuperar</p><p>
|
||||
<br>
|
||||
<select onchange="updateForm(this.value)" id="selection">
|
||||
<option value="recover-accountpassword-form" selected="selected">Contraseña</option>
|
||||
<option value="recover-accountname-form">Nombre de cuenta</option>
|
||||
<option value="recover-activationlink-form">Enlace de activación</option>
|
||||
</select>
|
||||
</p><form action="" method="POST" id="nw-recover-accountpassword-form" accept-charset="utf-8" style="">
|
||||
<table class="middle-center-table">
|
||||
<tbody><tr>
|
||||
<td><input type="text" maxlength="20" name="username" id="username" placeholder="Nombre de usuario"></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><div class="g-recaptcha g-recaptcha-div" id="gcaptcha" data-theme="dark" data-sitekey="6LcsJH4UAAAAAKqW0y4c-OVFijZjtZqkadRlpbRI"><div style="width: 304px; height: 78px;"><div><iframe title="reCAPTCHA" width="304" height="78" role="presentation" name="a-qxqlxz4xlesu" frameborder="0" scrolling="no" sandbox="allow-forms allow-popups allow-same-origin allow-scripts allow-top-navigation allow-modals allow-popups-to-escape-sandbox allow-storage-access-by-user-activation" src="https://www.google.com/recaptcha/api2/anchor?ar=1&k=6LcsJH4UAAAAAKqW0y4c-OVFijZjtZqkadRlpbRI&co=aHR0cHM6Ly91bHRpbW93b3cuY29tOjQ0Mw..&hl=en&v=-ZG7BC9TxCVEbzIO2m429usb&theme=dark&size=normal&cb=m8d6xkv8z4oz"></iframe></div><textarea id="g-recaptcha-response" name="g-recaptcha-response" class="g-recaptcha-response" style="width: 250px; height: 40px; border: 1px solid rgb(193, 193, 193); margin: 10px 25px; padding: 0px; resize: none; display: none;"></textarea></div></div></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><button type="submit" name="recover" class="recover-button" data-id="RecuperarInfo">Solicitar</button></td>
|
||||
</tr>
|
||||
</tbody></table>
|
||||
</form>
|
||||
<form action="" method="POST" id="nw-recover-accountname-form" accept-charset="utf-8" style="display: none;">
|
||||
<table class="middle-center-table">
|
||||
<tbody><tr>
|
||||
<td><input type="email" name="email" id="email" placeholder="Correo electrónico"></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><div class="g-recaptcha g-recaptcha-div" id="gcaptcha" data-theme="dark" data-sitekey="6LcsJH4UAAAAAKqW0y4c-OVFijZjtZqkadRlpbRI"><div style="width: 304px; height: 78px;"><div><iframe title="reCAPTCHA" width="304" height="78" role="presentation" name="a-xflp6m78yzp" frameborder="0" scrolling="no" sandbox="allow-forms allow-popups allow-same-origin allow-scripts allow-top-navigation allow-modals allow-popups-to-escape-sandbox allow-storage-access-by-user-activation" src="https://www.google.com/recaptcha/api2/anchor?ar=1&k=6LcsJH4UAAAAAKqW0y4c-OVFijZjtZqkadRlpbRI&co=aHR0cHM6Ly91bHRpbW93b3cuY29tOjQ0Mw..&hl=en&v=-ZG7BC9TxCVEbzIO2m429usb&theme=dark&size=normal&cb=3s51wzqngwmx"></iframe></div><textarea id="g-recaptcha-response-1" name="g-recaptcha-response" class="g-recaptcha-response" style="width: 250px; height: 40px; border: 1px solid rgb(193, 193, 193); margin: 10px 25px; padding: 0px; resize: none; display: none;"></textarea></div></div></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><button type="submit" name="recover" class="recover-button" data-id="RecuperarInfo">Solicitar</button></td>
|
||||
</tr>
|
||||
</tbody></table>
|
||||
</form>
|
||||
<form action="" method="POST" id="nw-recover-activationlink-form" accept-charset="utf-8" style="display: none;">
|
||||
<table class="middle-center-table">
|
||||
<tbody><tr>
|
||||
<td><input type="text" maxlength="20" name="username" id="username" placeholder="Nombre de usuario"></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><div class="g-recaptcha g-recaptcha-div" id="gcaptcha" data-theme="dark" data-sitekey="6LcsJH4UAAAAAKqW0y4c-OVFijZjtZqkadRlpbRI"><div style="width: 304px; height: 78px;"><div><iframe title="reCAPTCHA" width="304" height="78" role="presentation" name="a-sv4k9abynly6" frameborder="0" scrolling="no" sandbox="allow-forms allow-popups allow-same-origin allow-scripts allow-top-navigation allow-modals allow-popups-to-escape-sandbox allow-storage-access-by-user-activation" src="https://www.google.com/recaptcha/api2/anchor?ar=1&k=6LcsJH4UAAAAAKqW0y4c-OVFijZjtZqkadRlpbRI&co=aHR0cHM6Ly91bHRpbW93b3cuY29tOjQ0Mw..&hl=en&v=-ZG7BC9TxCVEbzIO2m429usb&theme=dark&size=normal&cb=ujz7erfdzg8x"></iframe></div><textarea id="g-recaptcha-response-2" name="g-recaptcha-response" class="g-recaptcha-response" style="width: 250px; height: 40px; border: 1px solid rgb(193, 193, 193); margin: 10px 25px; padding: 0px; resize: none; display: none;"></textarea></div><iframe style="display: none;"></iframe></div></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><button type="submit" name="recover" class="recover-button" data-id="RecuperarInfo">Solicitar</button></td>
|
||||
</tr>
|
||||
</tbody></table>
|
||||
</form>
|
||||
<hr>
|
||||
<div class="alert-message" id="recover-response"></div>
|
||||
<!-- Isla React (Vite): recuperación de cuenta (contraseña / nombre de
|
||||
cuenta / reenvío de activación). POST a {% url 'recover' %} (JSON). -->
|
||||
<div id="recover-app"
|
||||
data-csrf="{{ csrf_token }}"
|
||||
data-recover-url="{% url 'recover' %}"></div>
|
||||
{% vite_asset 'src/entries/recover.tsx' %}
|
||||
<br>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -12,6 +12,7 @@ urlpatterns = [
|
||||
path('create-account/', views.register_view, name='register'),
|
||||
path('novawow-realm/', views.novawow_realm_view, name='novawow_realm'),
|
||||
path('recover/', views.recover_account_view, name='recover'),
|
||||
path('reset-password', views.reset_password_view, name='reset_password'),
|
||||
path('contact-us/', views.contact_us_view, name='contact_us'),
|
||||
path('legal-notice/', views.legal_notice_view, name='legal_notice'),
|
||||
path('terms-and-conditions/', views.terms_and_conditions_view, name='terms_and_conditions'),
|
||||
|
||||
@@ -35,6 +35,7 @@ from ..models import (
|
||||
GuildRenameSettings, VoteSite, VoteLog, HomeApiPoints, UnstuckHistory, ReviveHistory,
|
||||
RenamePrice, CustomizePrice, ChangeRacePrice, ChangeFactionPrice, LevelUpPrice,
|
||||
GoldPrice, TransferPrice, Category, Item, StripeLog, LoginAttempt, Pedido,
|
||||
PasswordReset,
|
||||
)
|
||||
|
||||
# Configuración del logger
|
||||
|
||||
@@ -246,7 +246,115 @@ def activate_account_view(request):
|
||||
except AccountActivation.DoesNotExist:
|
||||
return render(request, 'auth/activation_invalid.html')
|
||||
def recover_account_view(request):
|
||||
"""Recuperación de cuenta (Battle.net, por email). 3 tipos:
|
||||
password (enlace de reset), accountname (lista de cuentas), activation (reenvío).
|
||||
Respuestas genéricas para no revelar si el correo existe (anti-enumeración).
|
||||
"""
|
||||
if request.method == 'POST':
|
||||
rtype = request.POST.get('type', '').strip()
|
||||
email = request.POST.get('email', '').strip()
|
||||
if not email or not re.match(r'^[a-zA-Z0-9._%+-]+@gmail\.com$', email):
|
||||
return JsonResponse({'success': False, 'message': 'Introduce un correo de Gmail válido.'})
|
||||
|
||||
if rtype == 'password':
|
||||
try:
|
||||
with connections['acore_auth'].cursor() as cursor:
|
||||
account = bnet.get_bnet_account_by_email(cursor, email)
|
||||
except Exception as e:
|
||||
logger.warning("recover(password): BD de cuentas no disponible: %s", e)
|
||||
account = None
|
||||
if account:
|
||||
token = get_random_string(64)
|
||||
PasswordReset.objects.create(email=email, token=token)
|
||||
reset_link = f"{settings.URL_PRINCIPAL}/es/reset-password?token={token}"
|
||||
enviar_correo(
|
||||
subject=f'Restablecer contraseña - {settings.NOMBRE_SERVIDOR}',
|
||||
to_email=email,
|
||||
template='emails/password_reset.html',
|
||||
context={'reset_link': reset_link, 'email': email,
|
||||
'NOMBRE_SERVIDOR': settings.NOMBRE_SERVIDOR,
|
||||
'URL_PRINCIPAL': settings.URL_PRINCIPAL},
|
||||
)
|
||||
return JsonResponse({'success': True, 'message': 'Si existe una cuenta con ese correo, te hemos enviado un enlace para restablecer la contraseña.'})
|
||||
|
||||
if rtype == 'accountname':
|
||||
try:
|
||||
with connections['acore_auth'].cursor() as cursor:
|
||||
account = bnet.get_bnet_account_by_email(cursor, email)
|
||||
game_accounts = bnet.get_game_accounts_for_bnet(cursor, account['id']) if account else []
|
||||
except Exception as e:
|
||||
logger.warning("recover(accountname): BD de cuentas no disponible: %s", e)
|
||||
account, game_accounts = None, []
|
||||
if account:
|
||||
enviar_correo(
|
||||
subject=f'Tus cuentas de juego - {settings.NOMBRE_SERVIDOR}',
|
||||
to_email=email,
|
||||
template='emails/account_names.html',
|
||||
context={'email': email, 'accounts': game_accounts,
|
||||
'NOMBRE_SERVIDOR': settings.NOMBRE_SERVIDOR,
|
||||
'URL_PRINCIPAL': settings.URL_PRINCIPAL},
|
||||
)
|
||||
return JsonResponse({'success': True, 'message': 'Si existe una cuenta con ese correo, te hemos enviado la lista de cuentas asociadas.'})
|
||||
|
||||
if rtype == 'activation':
|
||||
activation = AccountActivation.objects.filter(
|
||||
email=email, old_email__isnull=True).order_by('-created_at').first()
|
||||
if activation:
|
||||
activation_link = f"{settings.URL_PRINCIPAL}/es/activate-account?act={activation.hash}"
|
||||
enviar_correo(
|
||||
subject=f'Activación de la cuenta {email} - {settings.NOMBRE_SERVIDOR}',
|
||||
to_email=email,
|
||||
template='emails/activation.html',
|
||||
context={'username': email, 'password': activation.password,
|
||||
'activation_link': activation_link,
|
||||
'NOMBRE_SERVIDOR': settings.NOMBRE_SERVIDOR},
|
||||
)
|
||||
return JsonResponse({'success': True, 'message': 'Si hay una activación pendiente para ese correo, te hemos reenviado el enlace.'})
|
||||
|
||||
return JsonResponse({'success': False, 'message': 'Opción no válida.'})
|
||||
|
||||
return render(request, 'auth/recover_account.html')
|
||||
|
||||
|
||||
def reset_password_view(request):
|
||||
"""Fija una nueva contraseña a partir de un token de PasswordReset (por email).
|
||||
Re-deriva el verifier SRP6 v2 de la cuenta Battle.net (igual que change_password)."""
|
||||
if request.method == 'POST':
|
||||
token = request.POST.get('token', '').strip()
|
||||
new_password = request.POST.get('new-password', '').strip()
|
||||
conf_password = request.POST.get('conf-password', '').strip()
|
||||
|
||||
pr = PasswordReset.objects.filter(token=token, used=False).first()
|
||||
if not pr or pr.is_expired():
|
||||
return JsonResponse({'success': False, 'message': 'El enlace no es válido o ha caducado.'})
|
||||
if not new_password or new_password != conf_password:
|
||||
return JsonResponse({'success': False, 'message': 'Las contraseñas no coinciden.'})
|
||||
if len(new_password) > 16:
|
||||
return JsonResponse({'success': False, 'message': 'La contraseña no debe exceder los 16 caracteres.'})
|
||||
|
||||
new_salt, new_verifier, srp_version = bnet.bnet_make_registration(pr.email, new_password)
|
||||
try:
|
||||
with connections['acore_auth'].cursor() as cursor:
|
||||
account = bnet.get_bnet_account_by_email(cursor, pr.email)
|
||||
if not account:
|
||||
return JsonResponse({'success': False, 'message': 'No se ha encontrado la cuenta.'})
|
||||
cursor.execute(
|
||||
"UPDATE battlenet_accounts SET srp_version = %s, salt = %s, verifier = %s WHERE id = %s",
|
||||
[srp_version, new_salt, new_verifier, account['id']]
|
||||
)
|
||||
except Exception as e:
|
||||
logger.error("reset_password: error al actualizar la cuenta: %s", e)
|
||||
return JsonResponse({'success': False, 'message': 'No se ha podido actualizar la contraseña. Inténtalo más tarde.'})
|
||||
pr.used = True
|
||||
pr.save(update_fields=['used'])
|
||||
return JsonResponse({'success': True,
|
||||
'message': 'Contraseña restablecida. Ya puedes iniciar sesión.',
|
||||
'redirect': reverse('login')})
|
||||
|
||||
token = request.GET.get('token', '').strip()
|
||||
pr = PasswordReset.objects.filter(token=token, used=False).first()
|
||||
valid = bool(pr and not pr.is_expired())
|
||||
return render(request, 'auth/reset_password.html', {'token': token, 'valid': valid})
|
||||
def change_password_view(request):
|
||||
# Verificar si el usuario está autenticado mediante la sesión
|
||||
username = request.session.get('username')
|
||||
|
||||
Reference in New Issue
Block a user