Utenti: pannello password, ruolo come pillola e azioni a icona
Le due azioni di riga diventano icone (chiave e cestino) con etichetta accessibile: pesavano quanto il contenuto della tabella. Il ruolo smette di essere il menu a tendina di sistema e prende la forma di una pillola colorata per livello, restando un <select> che salva al cambio. La chiave apre un pannello dove la password si può scrivere a mano oppure far generare: l'endpoint accetta ora una password scelta, con lo stesso minimo di otto caratteri della creazione, e continua a restituirla in chiaro una volta sola perché nel database ne resta solo l'hash. Il valore si copia con un pulsante invece che dal prompt del browser. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
This commit is contained in:
+110
-11
@@ -10,20 +10,53 @@ const me = Astro.locals.user!;
|
||||
<h1>Utenti</h1>
|
||||
|
||||
<p><a class="abtn" href="/admin/users/new">+ Nuovo utente</a></p>
|
||||
|
||||
<!-- Pannello password: si apre dall'icona a chiave della riga. Permette di scegliere una
|
||||
password o di farla generare; il risultato si vede una volta sola, perché nel database
|
||||
finisce solo il suo hash. -->
|
||||
<div class="apw" id="pwbox" hidden>
|
||||
<p class="apw__label">Password di <strong id="pwbox-user"></strong></p>
|
||||
|
||||
<div id="pwbox-form">
|
||||
<div class="apw__row">
|
||||
<input class="afield apw__input" type="text" id="pwbox-input" placeholder="Scrivi una password (min 8)" autocomplete="off" />
|
||||
<button class="abtn" type="button" id="pwbox-set">Imposta</button>
|
||||
<button class="abtn abtn--ghost" type="button" id="pwbox-gen">Genera casuale</button>
|
||||
<button class="abtn abtn--ghost" type="button" id="pwbox-close">Annulla</button>
|
||||
</div>
|
||||
<p class="apw__hint">La password attuale smetterà di funzionare.</p>
|
||||
<p class="form-msg" id="pwbox-msg" hidden></p>
|
||||
</div>
|
||||
|
||||
<div id="pwbox-result" hidden>
|
||||
<div class="apw__row">
|
||||
<code id="pwbox-value"></code>
|
||||
<button class="abtn" type="button" id="pwbox-copy">Copia</button>
|
||||
<button class="abtn abtn--ghost" type="button" id="pwbox-done">Chiudi</button>
|
||||
</div>
|
||||
<p class="apw__hint">Consegnala ora: chiuso questo riquadro non è più recuperabile.</p>
|
||||
</div>
|
||||
</div>
|
||||
<table>
|
||||
<thead><tr><th>Utente</th><th>Ruolo</th><th></th></tr></thead>
|
||||
<thead><tr><th>Utente</th><th>Ruolo</th><th class="uactions">Azioni</th></tr></thead>
|
||||
<tbody>
|
||||
{users.map((u) => (
|
||||
<tr data-id={u.id}>
|
||||
<td>{u.username}{u.id === me.id && ' (tu)'}</td>
|
||||
<td>
|
||||
<select class="role-sel" data-id={u.id}>
|
||||
<select class="role-sel arole" data-id={u.id} data-role={u.role} aria-label={`Ruolo di ${u.username}`}>
|
||||
{['user', 'superuser', 'piattaforme', 'admin'].map((r) => <option value={r} selected={u.role === r}>{r}</option>)}
|
||||
</select>
|
||||
</td>
|
||||
<td>
|
||||
<button class="abtn" data-reset={u.id}>Reset password</button>
|
||||
{u.id !== me.id && <button class="abtn abtn--danger" data-del={u.id}>Elimina</button>}
|
||||
<td class="uactions">
|
||||
<button class="aicon" data-reset={u.id} title="Genera una nuova password" aria-label={`Genera una nuova password per ${u.username}`}>
|
||||
<svg viewBox="0 0 24 24" aria-hidden="true"><path d="M14 7a4 4 0 1 1-3.9 5H7v2H5v2H2v-3l5.1-5.1A4 4 0 0 1 14 7Z"/><circle cx="15.5" cy="9.5" r="1.2" fill="#fff"/></svg>
|
||||
</button>
|
||||
{u.id !== me.id && (
|
||||
<button class="aicon aicon--danger" data-del={u.id} title="Elimina utente" aria-label={`Elimina ${u.username}`}>
|
||||
<svg viewBox="0 0 24 24" aria-hidden="true"><path d="M9 3h6l1 2h4v2H4V5h4l1-2Zm-3 6h12l-1 11a2 2 0 0 1-2 2H9a2 2 0 0 1-2-2L6 9Z"/></svg>
|
||||
</button>
|
||||
)}
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
@@ -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<void> {
|
||||
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<HTMLButtonElement>('[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<HTMLButtonElement>('[data-del]').forEach((b) =>
|
||||
|
||||
@@ -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 });
|
||||
};
|
||||
|
||||
Reference in New Issue
Block a user