diff --git a/src/layouts/Admin.astro b/src/layouts/Admin.astro index 2292faa..5f6e49d 100644 --- a/src/layouts/Admin.astro +++ b/src/layouts/Admin.astro @@ -133,6 +133,44 @@ const attiva = (v: { href: string; exact?: boolean }) => .abtn--ghost { background: none; color: var(--c-heading); border-color: #ddd6cb; } .abtn--ghost:hover { background: none; border-color: var(--c-accent); color: var(--c-accent-dark); } + /* Ruolo: una pillola che resta un + + + + +

La password attuale smetterà di funzionare.

+ + + + + - + {users.map((u) => ( - ))} @@ -44,16 +77,82 @@ const me = Astro.locals.user!; const res = await fetch(`/api/admin/users/${sel.dataset.id}/role`, { method: 'PUT', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ role: sel.value }), }); - if (res.ok) show(rowMsg, 'Ruolo aggiornato ✓', true); + if (res.ok) { sel.dataset.role = sel.value; show(rowMsg, 'Ruolo aggiornato', true); } else { show(rowMsg, (await res.json()).error ?? 'Errore'); location.reload(); } })); + const pwbox = document.getElementById('pwbox')!; + const pwUser = document.getElementById('pwbox-user')!; + const pwValue = document.getElementById('pwbox-value')!; + const pwForm = document.getElementById('pwbox-form')!; + const pwResult = document.getElementById('pwbox-result')!; + const pwInput = document.getElementById('pwbox-input') as HTMLInputElement; + const pwMsg = document.getElementById('pwbox-msg')!; + const pwCopy = document.getElementById('pwbox-copy') as HTMLButtonElement; + let idCorrente = ''; + + const chiudi = () => { pwbox.hidden = true; }; + document.getElementById('pwbox-close')!.addEventListener('click', chiudi); + document.getElementById('pwbox-done')!.addEventListener('click', chiudi); + + /** Manda la nuova password: senza corpo il server ne genera una a caso. */ + async function cambiaPassword(password?: string): Promise { + const res = await fetch(`/api/admin/users/${idCorrente}/reset-password`, { + method: 'POST', + ...(password + ? { headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ password }) } + : {}), + }); + if (!res.ok) { + pwMsg.hidden = false; + pwMsg.className = 'form-msg form-msg--err'; + pwMsg.textContent = (await res.json()).error ?? 'Operazione non riuscita.'; + return; + } + const dati = await res.json(); + pwValue.textContent = dati.password; + pwForm.hidden = true; + pwResult.hidden = false; + } + + document.getElementById('pwbox-set')!.addEventListener('click', () => { + const scelta = pwInput.value.trim(); + if (scelta.length < 8) { + pwMsg.hidden = false; + pwMsg.className = 'form-msg form-msg--err'; + pwMsg.textContent = 'Password troppo corta (min 8).'; + return; + } + cambiaPassword(scelta); + }); + + document.getElementById('pwbox-gen')!.addEventListener('click', () => cambiaPassword()); + + pwCopy.addEventListener('click', async () => { + try { + await navigator.clipboard.writeText(pwValue.textContent ?? ''); + pwCopy.textContent = 'Copiata'; + setTimeout(() => { pwCopy.textContent = 'Copia'; }, 1500); + } catch { + // Senza permesso sugli appunti resta la selezione manuale: evidenziamo il testo. + const range = document.createRange(); + range.selectNodeContents(pwValue); + getSelection()?.removeAllRanges(); + getSelection()?.addRange(range); + } + }); + document.querySelectorAll('[data-reset]').forEach((b) => - b.addEventListener('click', async () => { - if (!confirm('Generare una nuova password per questo utente?')) return; - const res = await fetch(`/api/admin/users/${b.dataset.reset}/reset-password`, { method: 'POST' }); - if (res.ok) { const { password } = await res.json(); prompt('Nuova password (copiala e consegnala ora):', password); } - else show(rowMsg, (await res.json()).error ?? 'Errore'); + b.addEventListener('click', () => { + idCorrente = b.dataset.reset!; + pwUser.textContent = (b.closest('tr')!.querySelector('td')!.textContent ?? '').replace(' (tu)', ''); + pwInput.value = ''; + pwMsg.hidden = true; + pwResult.hidden = true; + pwForm.hidden = false; + pwbox.hidden = false; + pwbox.scrollIntoView({ block: 'nearest' }); + pwInput.focus(); })); document.querySelectorAll('[data-del]').forEach((b) => diff --git a/src/pages/api/admin/users/[id]/reset-password.ts b/src/pages/api/admin/users/[id]/reset-password.ts index 7101e88..fe6ab81 100644 --- a/src/pages/api/admin/users/[id]/reset-password.ts +++ b/src/pages/api/admin/users/[id]/reset-password.ts @@ -6,11 +6,27 @@ export const prerender = false; const json = (status: number, body: object) => new Response(JSON.stringify(body), { status, headers: { 'Content-Type': 'application/json' } }); -export const POST: APIRoute = ({ params }) => { +/** + * Cambia la password di un utente. Senza corpo la genera a caso; con `{ password }` usa + * quella scelta dall'admin. In entrambi i casi la risposta la riporta in chiaro una volta + * sola: nel database finisce solo il suo hash. + */ +export const POST: APIRoute = async ({ params, request }) => { const id = Number(params.id); if (!getUserById(getDb(), id)) return json(404, { error: 'Utente inesistente.' }); - const password = randomPassword(); + + let scelta = ''; + if (request.headers.get('content-type')?.includes('application/json')) { + try { + const data = (await request.json()) as { password?: unknown }; + scelta = String(data.password ?? ''); + } catch { + return json(400, { error: 'Richiesta non valida.' }); + } + } + if (scelta && scelta.length < 8) return json(400, { error: 'Password troppo corta (min 8).' }); + + const password = scelta || randomPassword(); updateUserPassword(getDb(), id, hashPassword(password)); - // La password in chiaro è restituita UNA sola volta: l'admin la copia e la consegna. return json(200, { password }); };
UtenteRuolo
UtenteRuoloAzioni
{u.username}{u.id === me.id && ' (tu)'} - {['user', 'superuser', 'piattaforme', 'admin'].map((r) => )} - - {u.id !== me.id && } + + + {u.id !== me.id && ( + + )}