Fase 2 (isla): selector de cuenta de juego en React/TSX, sin POST
El selector de cuenta de juego (bnet con varias) pasa a isla React y la selección
se hace vía GET (a petición), no POST:
- Nuevo endpoint GET /api/account/select/?account_id=<id> (account_select_api):
idempotente y solo permite elegir cuentas ligadas a la bnet en sesión; fija la
cuenta en sesión y devuelve {success, redirect}. 401 si no hay sesión bnet.
- select_account_view: se elimina el manejo de POST (queda solo la lógica GET:
redirect si no hay bnet, autoseleccionar si hay una, render si hay varias).
- SelectAccount.tsx lee las cuentas embebidas con json_script y, al pulsar, hace
fetch GET y redirige. Nueva entry 'select_account'.
- select_account.html: el <form> POST se sustituye por la isla + json_script.
Verificado: check OK, endpoint 401 sin sesión, /select-account/ redirige a login.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,67 @@
|
||||
import { useState } from 'react'
|
||||
|
||||
export interface GameAccount {
|
||||
id: number
|
||||
username: string
|
||||
index: number
|
||||
}
|
||||
|
||||
interface Props {
|
||||
accounts: GameAccount[]
|
||||
selectUrl: string
|
||||
}
|
||||
|
||||
export function SelectAccount({ accounts, selectUrl }: Props) {
|
||||
const [busy, setBusy] = useState<number | null>(null)
|
||||
const [error, setError] = useState<string | null>(null)
|
||||
|
||||
async function select(id: number) {
|
||||
if (busy !== null) return
|
||||
setBusy(id)
|
||||
setError(null)
|
||||
try {
|
||||
const r = await fetch(`${selectUrl}?account_id=${id}`, {
|
||||
headers: { Accept: 'application/json' },
|
||||
credentials: 'same-origin',
|
||||
})
|
||||
const d: { success?: boolean; redirect?: string; error?: string } = await r.json()
|
||||
if (d.success && d.redirect) {
|
||||
window.location.href = d.redirect
|
||||
} else {
|
||||
setError(d.error || 'No se pudo seleccionar la cuenta.')
|
||||
setBusy(null)
|
||||
}
|
||||
} catch {
|
||||
setError('Error de red. Inténtalo de nuevo.')
|
||||
setBusy(null)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<table className="middle-center-table">
|
||||
<tbody>
|
||||
{accounts.map((a) => (
|
||||
<tr key={a.id}>
|
||||
<td>
|
||||
<button
|
||||
type="button"
|
||||
className="login-button"
|
||||
disabled={busy !== null}
|
||||
onClick={() => select(a.id)}
|
||||
>
|
||||
{busy === a.id ? 'Entrando…' : a.username}
|
||||
</button>
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
{error && (
|
||||
<tr>
|
||||
<td>
|
||||
<span className="red-form-response">{error}</span>
|
||||
</td>
|
||||
</tr>
|
||||
)}
|
||||
</tbody>
|
||||
</table>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
import { StrictMode } from 'react'
|
||||
import { createRoot } from 'react-dom/client'
|
||||
import { SelectAccount, type GameAccount } from '../components/SelectAccount'
|
||||
|
||||
const dataEl = document.getElementById('select-account-data')
|
||||
const accounts: GameAccount[] = dataEl ? JSON.parse(dataEl.textContent || '[]') : []
|
||||
|
||||
const el = document.getElementById('select-account-app')
|
||||
if (el) {
|
||||
createRoot(el).render(
|
||||
<StrictMode>
|
||||
<SelectAccount
|
||||
accounts={accounts}
|
||||
selectUrl={el.dataset.selectUrl || '/api/account/select/'}
|
||||
/>
|
||||
</StrictMode>,
|
||||
)
|
||||
}
|
||||
@@ -17,6 +17,7 @@ export default defineConfig({
|
||||
home: resolve(__dirname, 'src/entries/home.tsx'),
|
||||
login: resolve(__dirname, 'src/entries/login.tsx'),
|
||||
register: resolve(__dirname, 'src/entries/register.tsx'),
|
||||
select_account: resolve(__dirname, 'src/entries/select_account.tsx'),
|
||||
},
|
||||
},
|
||||
},
|
||||
|
||||
@@ -5,4 +5,5 @@ from . import views
|
||||
urlpatterns = [
|
||||
path('home/news/', views.home_news_api, name='api_home_news'),
|
||||
path('home/status/', views.home_status_api, name='api_home_status'),
|
||||
path('account/select/', views.account_select_api, name='api_account_select'),
|
||||
]
|
||||
|
||||
@@ -20,20 +20,12 @@
|
||||
{% if game_accounts %}
|
||||
<p>Tu cuenta Battle.net tiene varias cuentas de juego. Elige con cuál quieres continuar:</p>
|
||||
<br>
|
||||
<form action="{% url 'select-account' %}" method="POST" accept-charset="utf-8">
|
||||
{% csrf_token %}
|
||||
<table class="middle-center-table">
|
||||
{% for account in game_accounts %}
|
||||
<tr>
|
||||
<td>
|
||||
<button type="submit" name="account_id" value="{{ account.id }}" class="login-button">
|
||||
{{ account.username }}
|
||||
</button>
|
||||
</td>
|
||||
</tr>
|
||||
{% endfor %}
|
||||
</table>
|
||||
</form>
|
||||
{% load django_vite %}
|
||||
<!-- Isla React (Vite): selector de cuenta de juego. Selección vía GET
|
||||
a /api/account/select/ (sin POST); redirige a my-account. -->
|
||||
<div id="select-account-app" data-select-url="/api/account/select/"></div>
|
||||
{{ game_accounts|json_script:"select-account-data" }}
|
||||
{% vite_asset 'src/entries/select_account.tsx' %}
|
||||
{% else %}
|
||||
<p>No se han encontrado cuentas de juego asociadas a esta cuenta Battle.net.</p>
|
||||
<br>
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
from ._base import *
|
||||
from .pages import check_server_status, get_online_characters_count
|
||||
from .auth import _set_game_account_session
|
||||
|
||||
# Endpoints JSON que alimentan las islas React/TSX del frontend (Vite).
|
||||
# Se montan bajo /api/ (fuera de i18n_patterns). De momento con JsonResponse;
|
||||
@@ -37,3 +38,25 @@ def home_status_api(request):
|
||||
"status": status,
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
def account_select_api(request):
|
||||
"""Selecciona la cuenta de juego de la bnet en sesión (isla del selector).
|
||||
|
||||
Vía GET (sin POST): es idempotente y solo permite elegir cuentas ligadas a la
|
||||
propia cuenta Battle.net de la sesión, así que no expone nada de otros usuarios.
|
||||
"""
|
||||
bnet_id = request.session.get('bnet_id')
|
||||
if not bnet_id:
|
||||
return JsonResponse({"success": False, "error": "No autenticado"}, status=401)
|
||||
try:
|
||||
selected_id = int(request.GET.get("account_id", ""))
|
||||
except (TypeError, ValueError):
|
||||
return JsonResponse({"success": False, "error": "Cuenta no válida"})
|
||||
with connections['acore_auth'].cursor() as cursor:
|
||||
accounts = bnet.get_game_accounts_for_bnet(cursor, bnet_id)
|
||||
chosen = next((g for g in accounts if g["id"] == selected_id), None)
|
||||
if not chosen:
|
||||
return JsonResponse({"success": False, "error": "Cuenta de juego no válida."})
|
||||
_set_game_account_session(request, chosen)
|
||||
return JsonResponse({"success": True, "redirect": reverse("my-account")})
|
||||
|
||||
+1
-10
@@ -93,16 +93,7 @@ def select_account_view(request):
|
||||
with connections['acore_auth'].cursor() as cursor:
|
||||
game_accounts = bnet.get_game_accounts_for_bnet(cursor, bnet_id)
|
||||
|
||||
if request.method == 'POST':
|
||||
try:
|
||||
selected_id = int(request.POST.get('account_id', ''))
|
||||
except (TypeError, ValueError):
|
||||
selected_id = None
|
||||
chosen = next((g for g in game_accounts if g['id'] == selected_id), None)
|
||||
if chosen:
|
||||
_set_game_account_session(request, chosen)
|
||||
return redirect('my-account')
|
||||
messages.error(request, 'Cuenta de juego no válida.')
|
||||
# La selección la hace la isla React vía GET (/api/account/select/), sin POST.
|
||||
|
||||
# Autoseleccionar si solo hay una
|
||||
if len(game_accounts) == 1:
|
||||
|
||||
Reference in New Issue
Block a user