Fase 2 (isla): formulario de login en React/TSX

El login se migra a una isla React. login_view ya devolvía JSON en POST, así que
el backend no cambia: LoginForm.tsx hace fetch (form-urlencoded + CSRF) al mismo
{% url 'login' %} y replica el comportamiento del antiguo login_response.js
(mostrar/ocultar contraseña, estados del botón, éxito -> redirige a my-account,
alert/locked, errores transitorios).

- partials/login.html: el <form> + el script jQuery se sustituyen por
  #login-app (con data-csrf/data-login-url/data-success-url) + {% vite_asset %}.
  La rama "ya conectado" y los enlaces (recover, create-account) siguen en Django.
- CSRF vía data-csrf="{{ csrf_token }}" (fija la cookie y da el token); el fetch
  lo manda como X-CSRFToken y csrfmiddlewaretoken. El navegador adjunta Referer.
- Nueva entry 'login' en vite.config.ts.

Verificado: check OK, la página monta la isla, POST devuelve JSON correcto.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
2026-07-12 20:41:46 +00:00
parent b8cd6bac0c
commit 0909567e0d
4 changed files with 174 additions and 25 deletions
+149
View File
@@ -0,0 +1,149 @@
import { useState } from 'react'
interface Props {
loginUrl: string
successUrl: string
csrfToken: string
}
type LoginResponse = {
success?: boolean
alert?: boolean
locked?: boolean
error?: string
}
export function LoginForm({ loginUrl, successUrl, csrfToken }: Props) {
const [email, setEmail] = useState('')
const [password, setPassword] = useState('')
const [showPassword, setShowPassword] = useState(false)
const [buttonText, setButtonText] = useState('Conectar')
const [busy, setBusy] = useState(false)
const [message, setMessage] = useState<{ kind: 'ok' | 'err'; text: string } | null>(null)
function transientError(text: string) {
setMessage({ kind: 'err', text })
setBusy(false)
setButtonText('Conectar')
setTimeout(() => setMessage(null), 5000)
}
async function handleSubmit(e: React.FormEvent) {
e.preventDefault()
if (busy) return
if (email.trim() === '' || password.trim() === '') {
transientError('Por favor rellene todos los campos.')
return
}
setBusy(true)
setButtonText('Conectando')
setMessage(null)
const body = new URLSearchParams()
body.set('email', email.trim())
body.set('password', password.trim())
body.set('csrfmiddlewaretoken', csrfToken)
try {
const resp = await fetch(loginUrl, {
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: LoginResponse = await resp.json()
if (data.success === true) {
setButtonText('Conectado')
setMessage({ kind: 'ok', text: 'Conexión exitosa. Redirigiendo…' })
setTimeout(() => {
window.location.href = successUrl
}, 3000)
} else if (data.alert === true) {
setButtonText('Sancionado')
setBusy(false)
} else if (data.locked === true) {
setButtonText('Seguridad')
setBusy(false)
} else {
transientError(data.error || 'Nombre de usuario / Contraseña incorrectos.')
}
} catch {
setTimeout(() => {
alert('Algo ha salido mal. Por favor intente más tarde')
window.location.reload()
}, 2000)
}
}
return (
<>
<form id="nw-login-form" onSubmit={handleSubmit} acceptCharset="utf-8">
<table className="middle-center-table">
<tbody>
<tr>
<td>
<input
type="email"
maxLength={320}
name="email"
id="username"
placeholder="Correo electrónico"
autoFocus
required
value={email}
onChange={(e) => setEmail(e.target.value)}
/>
</td>
</tr>
<tr>
<td>
<input
type={showPassword ? 'text' : 'password'}
maxLength={16}
name="password"
id="password"
placeholder="Contraseña"
required
value={password}
onChange={(e) => setPassword(e.target.value)}
/>
<span
className={`far toggle-password ${showPassword ? 'fa-eye-slash' : 'fa-eye'}`}
onClick={() => setShowPassword((v) => !v)}
/>
</td>
</tr>
<tr>
<td>
<button
type="submit"
className="login-button"
id="login-button"
disabled={busy}
>
{buttonText}
</button>
</td>
</tr>
</tbody>
</table>
</form>
<hr />
<div className="alert-message" id="login-response">
{message && (
<span className={message.kind === 'ok' ? 'ok-form-response' : 'red-form-response'}>
{message.text}
</span>
)}
</div>
</>
)
}
+16
View File
@@ -0,0 +1,16 @@
import { StrictMode } from 'react'
import { createRoot } from 'react-dom/client'
import { LoginForm } from '../components/LoginForm'
const el = document.getElementById('login-app')
if (el) {
createRoot(el).render(
<StrictMode>
<LoginForm
loginUrl={el.dataset.loginUrl || ''}
successUrl={el.dataset.successUrl || 'my-account'}
csrfToken={el.dataset.csrf || ''}
/>
</StrictMode>,
)
}
+1
View File
@@ -15,6 +15,7 @@ export default defineConfig({
rollupOptions: {
input: {
home: resolve(__dirname, 'src/entries/home.tsx'),
login: resolve(__dirname, 'src/entries/login.tsx'),
},
},
},
+8 -25
View File
@@ -22,31 +22,14 @@
</div>
<div class="box-content">
<div class="body-box-content centered">
<script src="{{ URL_PRINCIPAL }}/static/nw-themes/nw-ryu/nw-js-handlers/login_response.js"></script>
<form action="{% url 'login' %}" method="POST" id="nw-login-form" accept-charset="utf-8" onsubmit="event.preventDefault(); submitLoginForm();">
{% csrf_token %}
<table class="middle-center-table">
<tr>
<td><input type="email" maxlength="320" name="email" id="username" placeholder="Correo electrónico" autofocus required></td>
</tr>
<tr>
<td>
<input type="password" maxlength="16" name="password" id="password" placeholder="Contraseña" required>
<span class="far fa-eye toggle-password" onclick="togglePasswordVisibility()"></span>
</td>
</tr>
<tr>
</tr>
<tr>
<td>
<button type="submit" class="login-button" id="login-button">Conectar</button>
</td>
</tr>
</table>
</form>
<hr>
<div class="alert-message" id="login-response"></div>
{% load django_vite %}
<!-- Isla React (Vite): formulario de login. POST a {% url 'login' %}
(que ya devuelve JSON) con CSRF; en éxito redirige a my-account. -->
<div id="login-app"
data-csrf="{{ csrf_token }}"
data-login-url="{% url 'login' %}"
data-success-url="my-account"></div>
{% vite_asset 'src/entries/login.tsx' %}
<br>
<p><a href="recover">He olvidado mi contraseña/usuario</a></p>
<p><a href="recover">No me ha llegado el enlace de activación</a></p>