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:
@@ -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 <select>, con la freccia disegnata a parte perché
|
||||
quella di sistema non si può vestire. */
|
||||
.arole {
|
||||
appearance: none; -webkit-appearance: none; border: 1px solid #e0d9cd; background-color: #faf8f5;
|
||||
padding: 6px 30px 6px 12px; font-family: var(--font-heading); font-size: .68rem; font-weight: 600;
|
||||
letter-spacing: .12em; text-transform: uppercase; color: var(--c-heading); cursor: pointer;
|
||||
background-image: url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 12 8'%3E%3Cpath d='M1 1.5 6 6.5l5-5' fill='none' stroke='%238a8a8a' stroke-width='1.6'/%3E%3C/svg%3E");
|
||||
background-repeat: no-repeat; background-position: right 11px center; background-size: 9px;
|
||||
}
|
||||
.arole:hover { border-color: var(--c-accent); }
|
||||
.arole:focus-visible { outline: 2px solid var(--c-accent); outline-offset: 1px; }
|
||||
.arole[data-role='admin'] { background-color: #efe7dc; border-color: #d9c7ab; color: #6b5334; }
|
||||
.arole[data-role='superuser'] { background-color: #ece7dc; border-color: #d8cfbe; color: #6f6353; }
|
||||
.arole[data-role='piattaforme'] { background-color: #e6ede4; border-color: #cbdcc6; color: #4d6a48; }
|
||||
|
||||
/* Riquadro della password appena generata */
|
||||
.apw { background: #fff; border: 1px solid var(--c-accent); padding: 18px 20px; margin: 0 0 20px; }
|
||||
.apw__label { margin: 0 0 10px; font-size: .85rem; color: var(--c-text-light); }
|
||||
.apw__label strong { color: var(--c-heading); }
|
||||
.apw__row { display: flex; align-items: center; gap: 10px; flex-wrap: wrap; }
|
||||
.apw__row code {
|
||||
background: var(--c-bg-alt); border: 1px solid #e4dfd7; padding: 9px 14px;
|
||||
font-size: 1rem; letter-spacing: .06em; color: var(--c-heading);
|
||||
}
|
||||
.apw__hint { margin: 10px 0 0; font-size: .78rem; color: var(--c-text-light); }
|
||||
.apw__input { width: auto; min-width: 260px; margin-bottom: 0; }
|
||||
|
||||
/* Comandi di riga: icona sola, per non far pesare le azioni quanto il contenuto. */
|
||||
.aicon {
|
||||
display: inline-flex; align-items: center; justify-content: center; width: 32px; height: 32px;
|
||||
padding: 0; background: none; border: 1px solid #ddd6cb; cursor: pointer; color: var(--c-text);
|
||||
}
|
||||
.aicon + .aicon { margin-left: 6px; }
|
||||
.aicon svg { width: 17px; height: 17px; fill: currentColor; }
|
||||
.aicon:hover { border-color: var(--c-accent); color: var(--c-accent-dark); }
|
||||
.aicon--danger:hover { border-color: #a4544a; background: #a4544a; color: #fff; }
|
||||
td.uactions, th.uactions { text-align: right; white-space: nowrap; }
|
||||
|
||||
.form-msg { font-size: .88rem; margin-top: 8px; }
|
||||
.form-msg--ok { color: #5f7c5a; }
|
||||
.form-msg--err { color: #a4544a; }
|
||||
|
||||
+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