Rôle modérateur + gestion des comptes admin/modérateur

- Nouveau rôle users.role='moderator' (contrainte CHECK migrée via
  DROP+ADD CONSTRAINT, idempotent) : accès à Membres, Rencontres,
  Inscriptions uniquement. Dashboard, Catégories (écriture), Contenu du
  site, Demandes d'adhésion et gestion des comptes restent admin-only,
  imposé côté serveur (requireAuth accepte désormais un tableau de rôles)
- Nouvel onglet « Administrateurs » (admin-only) : créer un compte admin
  ou modérateur (mot de passe temporaire généré, même mécanique que pour
  les membres — visible tant que non changé, changement forcé à la
  première connexion), réinitialiser l'accès, promouvoir/rétrograder,
  supprimer. Garde-fous : impossible de se supprimer ou de se rétrograder
  soi-même, impossible de supprimer le dernier administrateur
- users.full_name (colonne migrée) pour l'affichage des comptes staff
- AccessCell/CredentialsModal extraits dans AccessControls.jsx, partagés
  entre la gestion des membres et celle des comptes admin/modérateur
- AdminShell filtre ses onglets par rôle ; Espace.jsx route admin et
  modérateur vers le back-office

Corrigé en cours de route : GET /api/admin/categories doit rester lisible
par les modérateurs (nécessaire au formulaire membre) même si sa gestion
en écriture reste admin-only — sans quoi le Promise.all du frontend
échouait silencieusement et vidait la liste des membres.

Vérifié : 34 + 21 tests existants toujours au vert, 26 nouveaux tests de
permissions par rôle, parcours navigateur complet (création modérateur,
connexion, changement forcé, menu restreint, accès aux membres).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Fkg15RCxNgUys4ru73He2o
This commit is contained in:
Claude committed 2026-07-13 14:42:29 +00:00
1 parent 56ca6d8559
commit fab64bc38a
15 files changed
+514 -144

No files matched your search

+7 -4
View File
@@ -12,12 +12,15 @@ import { useAuth } from './lib/AuthContext.jsx';
export default function App() {
const location = useLocation();
const { user } = useAuth();
// The admin backend (shown inside /espace-membre once an admin logs in)
// uses its own full-height sidebar layout, without the public header/footer.
// A forced password change is still shown inside the normal site layout.
// The admin backend (shown inside /espace-membre once an admin or
// moderator logs in) uses its own full-height sidebar layout, without the
// public header/footer. A forced password change is still shown inside
// the normal site layout.
const isAdminBackend =
location.pathname.startsWith('/admin') ||
(location.pathname === '/espace-membre' && user?.role === 'admin' && !user?.mustChangePassword);
(location.pathname === '/espace-membre' &&
(user?.role === 'admin' || user?.role === 'moderator') &&
!user?.mustChangePassword);
useEffect(() => {
window.scrollTo(0, 0);
@@ -0,0 +1,94 @@
import { useState } from 'react';
import Modal from '../Modal.jsx';
// Shows a just-generated temporary password so the admin can relay it
// (copy button). It also stays readable inline (via AccessCell below)
// until the account holder changes it.
export function CredentialsModal({ recipient, tempPassword, onClose }) {
const [copied, setCopied] = useState(false);
const copy = async () => {
try {
await navigator.clipboard.writeText(tempPassword);
setCopied(true);
setTimeout(() => setCopied(false), 1500);
} catch {
/* clipboard unavailable (non-HTTPS, older browser) — password stays selectable */
}
};
return (
<Modal onClose={onClose} maxWidth={440} header={{ kicker: 'Accès', title: 'Mot de passe temporaire généré' }}>
<div style={{ padding: '26px 30px' }}>
<p style={{ fontSize: 14, color: 'var(--gray)', lineHeight: 1.6, marginBottom: 18 }}>
Communiquez ces identifiants à <strong>{recipient}</strong>. Ce mot de passe devra être
changé dès la première connexion.
</p>
<div style={{ display: 'flex', alignItems: 'center', gap: 10, background: 'var(--admin-bg)', borderRadius: 6, padding: '14px 16px' }}>
<code style={{ fontSize: 18, fontWeight: 700, letterSpacing: '.02em', flex: 1, userSelect: 'all' }}>{tempPassword}</code>
<button type="button" className="btn btn-outline-soft btn-sm" style={{ fontSize: 13, padding: '8px 14px' }} onClick={copy}>
{copied ? '✓ Copié' : 'Copier'}
</button>
</div>
<p style={{ fontSize: 12.5, color: 'var(--gray-light)', lineHeight: 1.55, marginTop: 12 }}>
Ce mot de passe reste visible dans la liste tant qu'il n'a pas été changé.
</p>
<button type="button" className="btn btn-dark btn-sm" style={{ width: '100%', marginTop: 20, fontSize: 14 }} onClick={onClose}>
Fermer
</button>
</div>
</Modal>
);
}
// Compact cell for a table row: shows the live temp password (+ copy +
// reset), a "Défini" badge once changed, or a "Créer l'accès" action when
// there's no login yet.
export function AccessCell({ hasEmail = true, hasLogin, mustChangePassword, tempPassword, onGenerate, createLabel = "Créer l'accès" }) {
const [copied, setCopied] = useState(false);
const copy = async (text) => {
try {
await navigator.clipboard.writeText(text);
setCopied(true);
setTimeout(() => setCopied(false), 1500);
} catch {
/* clipboard unavailable */
}
};
if (!hasEmail) {
return (
<span style={{ fontSize: 12.5, color: 'var(--gray-light)' }} title="Ajoutez un email pour créer un accès">
—
</span>
);
}
if (!hasLogin) {
return (
<button type="button" className="btn-link" style={{ fontSize: 12.5 }} onClick={onGenerate}>
{createLabel}
</button>
);
}
if (mustChangePassword && tempPassword) {
return (
<div style={{ display: 'flex', alignItems: 'center', gap: 8, flexWrap: 'wrap' }}>
<code style={{ fontSize: 12, background: 'var(--admin-bg)', padding: '4px 8px', borderRadius: 3, fontWeight: 600 }}>
{tempPassword}
</code>
<button type="button" className="btn-link-gray" style={{ fontSize: 11.5 }} onClick={() => copy(tempPassword)}>
{copied ? '✓' : 'copier'}
</button>
<button type="button" className="btn-link-gray" style={{ fontSize: 11.5 }} onClick={onGenerate}>
réinitialiser
</button>
</div>
);
}
return (
<div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
<span className="badge badge-green">Défini</span>
<button type="button" className="btn-link-gray" style={{ fontSize: 11.5 }} onClick={onGenerate}>
réinitialiser
</button>
</div>
);
}
+11 -93
View File
@@ -1,6 +1,7 @@
import { useEffect, useState } from 'react';
import { api, dateParts, seasonLabel, statutLabel } from '../../lib/api.js';
import Modal from '../Modal.jsx';
import { AccessCell, CredentialsModal } from './AccessControls.jsx';
/* ---------------- Members ---------------- */
@@ -88,95 +89,6 @@ function MemberFormModal({ member, categories, onClose, onSaved }) {
);
}
// Shows a just-generated temporary password so the admin can relay it to
// the member (copy button). It also stays readable in the members table
// below until the member changes it.
function CredentialsModal({ email, tempPassword, onClose }) {
const [copied, setCopied] = useState(false);
const copy = async () => {
try {
await navigator.clipboard.writeText(tempPassword);
setCopied(true);
setTimeout(() => setCopied(false), 1500);
} catch {
/* clipboard unavailable (non-HTTPS, older browser) — password stays selectable */
}
};
return (
<Modal onClose={onClose} maxWidth={440} header={{ kicker: 'Accès membre', title: 'Mot de passe temporaire généré' }}>
<div style={{ padding: '26px 30px' }}>
<p style={{ fontSize: 14, color: 'var(--gray)', lineHeight: 1.6, marginBottom: 18 }}>
Communiquez ces identifiants à <strong>{email}</strong>. Ce mot de passe devra être
changé dès la première connexion.
</p>
<div style={{ display: 'flex', alignItems: 'center', gap: 10, background: 'var(--admin-bg)', borderRadius: 6, padding: '14px 16px' }}>
<code style={{ fontSize: 18, fontWeight: 700, letterSpacing: '.02em', flex: 1, userSelect: 'all' }}>{tempPassword}</code>
<button type="button" className="btn btn-outline-soft btn-sm" style={{ fontSize: 13, padding: '8px 14px' }} onClick={copy}>
{copied ? '✓ Copié' : 'Copier'}
</button>
</div>
<p style={{ fontSize: 12.5, color: 'var(--gray-light)', lineHeight: 1.55, marginTop: 12 }}>
Ce mot de passe reste visible dans la liste des membres tant qu'il n'a pas été changé.
</p>
<button type="button" className="btn btn-dark btn-sm" style={{ width: '100%', marginTop: 20, fontSize: 14 }} onClick={onClose}>
Fermer
</button>
</div>
</Modal>
);
}
function AccessCell({ member, onGenerate }) {
const [copied, setCopied] = useState(false);
const copy = async (text) => {
try {
await navigator.clipboard.writeText(text);
setCopied(true);
setTimeout(() => setCopied(false), 1500);
} catch {
/* clipboard unavailable */
}
};
if (!member.email) {
return (
<span style={{ fontSize: 12.5, color: 'var(--gray-light)' }} title="Ajoutez un email pour créer un accès">
—
</span>
);
}
if (!member.has_login) {
return (
<button type="button" className="btn-link" style={{ fontSize: 12.5 }} onClick={() => onGenerate(member)}>
Créer l'accès
</button>
);
}
if (member.must_change_password && member.temp_password) {
return (
<div style={{ display: 'flex', alignItems: 'center', gap: 8, flexWrap: 'wrap' }}>
<code style={{ fontSize: 12, background: 'var(--admin-bg)', padding: '4px 8px', borderRadius: 3, fontWeight: 600 }}>
{member.temp_password}
</code>
<button type="button" className="btn-link-gray" style={{ fontSize: 11.5 }} onClick={() => copy(member.temp_password)}>
{copied ? '✓' : 'copier'}
</button>
<button type="button" className="btn-link-gray" style={{ fontSize: 11.5 }} onClick={() => onGenerate(member)}>
réinitialiser
</button>
</div>
);
}
return (
<div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
<span className="badge badge-green">Défini</span>
<button type="button" className="btn-link-gray" style={{ fontSize: 11.5 }} onClick={() => onGenerate(member)}>
réinitialiser
</button>
</div>
);
}
export function MembersTab() {
const [members, setMembers] = useState([]);
const [categories, setCategories] = useState([]);
@@ -206,7 +118,7 @@ export function MembersTab() {
setAccessError('');
try {
const d = await api.post(`/api/admin/members/${m.id}/reset-access`);
setCredentials({ email: m.email, tempPassword: d.tempPassword });
setCredentials({ recipient: m.email, tempPassword: d.tempPassword });
reload();
} catch (err) {
setAccessError(err.message);
@@ -255,7 +167,13 @@ export function MembersTab() {
</span>
</td>
<td>
<AccessCell member={m} onGenerate={generateAccess} />
<AccessCell
hasEmail={!!m.email}
hasLogin={m.has_login}
mustChangePassword={m.must_change_password}
tempPassword={m.temp_password}
onGenerate={() => generateAccess(m)}
/>
</td>
<td style={{ textAlign: 'right', whiteSpace: 'nowrap' }}>
<button className="btn-link-gray" style={{ color: 'var(--gray)', marginRight: 14 }} onClick={() => toggle(m)}>
@@ -277,7 +195,7 @@ export function MembersTab() {
setModal(null);
reload();
if (result?.tempPassword) {
setCredentials({ email: result.email, tempPassword: result.tempPassword });
setCredentials({ recipient: result.email, tempPassword: result.tempPassword });
} else if (result?.accessError) {
setAccessError(`Membre créé, mais accès non créé : ${result.accessError}`);
}
@@ -286,7 +204,7 @@ export function MembersTab() {
)}
{credentials && (
<CredentialsModal
email={credentials.email}
recipient={credentials.recipient}
tempPassword={credentials.tempPassword}
onClose={() => setCredentials(null)}
/>
+180
View File
@@ -0,0 +1,180 @@
import { useEffect, useState } from 'react';
import { api } from '../../lib/api.js';
import Modal from '../Modal.jsx';
import { AccessCell, CredentialsModal } from './AccessControls.jsx';
const ROLE_LABEL = { admin: 'Administrateur', moderator: 'Modérateur' };
function UserFormModal({ onClose, onCreated }) {
const [form, setForm] = useState({ fullName: '', email: '', role: 'moderator' });
const [error, setError] = useState('');
const onChange = (e) => setForm({ ...form, [e.target.name]: e.target.value });
const submit = async (e) => {
e.preventDefault();
setError('');
try {
const result = await api.post('/api/admin/users', form);
onCreated({ ...result, email: form.email, fullName: form.fullName });
} catch (err) {
setError(err.message);
}
};
return (
<Modal onClose={onClose} maxWidth={480} header={{ kicker: 'Comptes', title: 'Nouveau compte' }}>
<form onSubmit={submit} style={{ padding: '26px 30px' }}>
<div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
<label className="field">Nom complet
<input name="fullName" value={form.fullName} onChange={onChange} required maxLength={120} />
</label>
<label className="field">Email
<input name="email" type="email" value={form.email} onChange={onChange} required maxLength={254} />
</label>
<label className="field">Rôle
<select name="role" value={form.role} onChange={onChange}>
<option value="moderator">Modérateur — membres, rencontres, inscriptions</option>
<option value="admin">Administrateur — accès complet</option>
</select>
</label>
</div>
{error && <p className="error-text" style={{ marginTop: 12 }}>{error}</p>}
<div style={{ display: 'flex', gap: 12, marginTop: 24 }}>
<button type="submit" className="btn btn-red btn-sm" style={{ flex: 1, fontSize: 14.5, padding: 13 }}>
Créer le compte
</button>
<button type="button" className="btn btn-outline-soft btn-sm" style={{ fontSize: 14.5, padding: '13px 22px' }} onClick={onClose}>
Annuler
</button>
</div>
</form>
</Modal>
);
}
export function UsersTab() {
const [users, setUsers] = useState([]);
const [modal, setModal] = useState(false);
const [credentials, setCredentials] = useState(null);
const [error, setError] = useState('');
const reload = () => api.get('/api/admin/users').then((d) => setUsers(d.users)).catch(() => {});
useEffect(() => {
reload();
}, []);
const generateAccess = async (u) => {
setError('');
try {
const d = await api.post(`/api/admin/users/${u.id}/reset-access`);
setCredentials({ recipient: `${u.full_name} (${u.email})`, tempPassword: d.tempPassword });
reload();
} catch (err) {
setError(err.message);
}
};
const changeRole = async (u, role) => {
setError('');
try {
await api.put(`/api/admin/users/${u.id}/role`, { role });
reload();
} catch (err) {
setError(err.message);
}
};
const remove = async (u) => {
if (!window.confirm(`Supprimer le compte de ${u.full_name || u.email} ?`)) return;
setError('');
try {
await api.del(`/api/admin/users/${u.id}`);
reload();
} catch (err) {
setError(err.message);
}
};
return (
<div className="card" style={{ borderRadius: 6, overflow: 'hidden' }}>
<div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '20px 24px', borderBottom: '1px solid var(--border)' }}>
<div>
<h3 className="serif" style={{ fontSize: 19, fontWeight: 600 }}>Administrateurs & modérateurs</h3>
<div style={{ fontSize: 12.5, color: 'var(--gray-light)', marginTop: 3, maxWidth: 520, lineHeight: 1.5 }}>
Les modérateurs gèrent les membres, les rencontres et les inscriptions. Les administrateurs
ont accès à l'ensemble du back-office.
</div>
</div>
<button className="btn btn-red btn-sm" style={{ fontSize: 13, padding: '10px 18px' }} onClick={() => setModal(true)}>
+ Ajouter un compte
</button>
</div>
{error && <p className="error-text" style={{ padding: '12px 24px 0' }}>{error}</p>}
<div style={{ overflowX: 'auto' }}>
<table className="table">
<thead>
<tr>
<th>Nom</th><th>Email</th><th>Rôle</th><th>Accès</th><th></th>
</tr>
</thead>
<tbody>
{users.map((u) => (
<tr key={u.id}>
<td>{u.full_name || '—'}</td>
<td>{u.email}</td>
<td>
<span className={`badge ${u.role === 'admin' ? 'badge-green' : 'badge-amber'}`}>
{ROLE_LABEL[u.role]}
</span>
</td>
<td>
<AccessCell
hasLogin
mustChangePassword={u.must_change_password}
tempPassword={u.temp_password}
onGenerate={() => generateAccess(u)}
/>
</td>
<td style={{ textAlign: 'right', whiteSpace: 'nowrap' }}>
{u.is_self ? (
<span style={{ fontSize: 12, color: 'var(--gray-light)' }}>Vous</span>
) : (
<>
<button
className="btn-link-gray"
style={{ color: 'var(--gray)', marginRight: 14 }}
onClick={() => changeRole(u, u.role === 'admin' ? 'moderator' : 'admin')}
>
{u.role === 'admin' ? 'Passer modérateur' : 'Passer admin'}
</button>
<button className="btn-link" style={{ fontSize: 13 }} onClick={() => remove(u)}>Supprimer</button>
</>
)}
</td>
</tr>
))}
</tbody>
</table>
</div>
{modal && (
<UserFormModal
onClose={() => setModal(false)}
onCreated={(result) => {
setModal(false);
reload();
setCredentials({ recipient: `${result.fullName} (${result.email})`, tempPassword: result.tempPassword });
}}
/>
)}
{credentials && (
<CredentialsModal
recipient={credentials.recipient}
tempPassword={credentials.tempPassword}
onClose={() => setCredentials(null)}
/>
)}
</div>
);
}
+21 -12
View File
@@ -4,14 +4,19 @@ import { useAuth } from '../lib/AuthContext.jsx';
import { api, dateParts, statutLabel } from '../lib/api.js';
import { MembersTab, RencontresTab, InscriptionsTab } from '../components/admin/AdminTabs.jsx';
import { CategoriesTab, ContenuTab } from '../components/admin/AdminContent.jsx';
import { UsersTab } from '../components/admin/AdminUsers.jsx';
// Moderators only get members/rencontres/inscriptions — everything else
// (dashboard, taxonomy, site content, staff account management) is
// admin-only, enforced both here (sidebar) and server-side (routes).
const TABS = [
{ key: 'dashboard', icon: '◧', label: 'Tableau de bord', title: 'Tableau de bord' },
{ key: 'membres', icon: '▤', label: 'Membres', title: 'Gestion des membres' },
{ key: 'rencontres', icon: '◈', label: 'Rencontres', title: 'Rencontres' },
{ key: 'inscriptions', icon: '✎', label: 'Inscriptions', title: 'Inscriptions' },
{ key: 'categories', icon: '☲', label: 'Catégories', title: 'Catégories' },
{ key: 'contenu', icon: '▧', label: 'Contenu du site', title: 'Contenu du site' },
{ key: 'dashboard', icon: '◧', label: 'Tableau de bord', title: 'Tableau de bord', roles: ['admin'] },
{ key: 'membres', icon: '▤', label: 'Membres', title: 'Gestion des membres', roles: ['admin', 'moderator'] },
{ key: 'rencontres', icon: '◈', label: 'Rencontres', title: 'Rencontres', roles: ['admin', 'moderator'] },
{ key: 'inscriptions', icon: '✎', label: 'Inscriptions', title: 'Inscriptions', roles: ['admin', 'moderator'] },
{ key: 'categories', icon: '☲', label: 'Catégories', title: 'Catégories', roles: ['admin'] },
{ key: 'contenu', icon: '▧', label: 'Contenu du site', title: 'Contenu du site', roles: ['admin'] },
{ key: 'utilisateurs', icon: '⚿', label: 'Administrateurs', title: 'Administrateurs & modérateurs', roles: ['admin'] },
];
function Dashboard() {
@@ -86,13 +91,14 @@ function Dashboard() {
}
// Rendered inside /espace-membre once a logged-in user is confirmed as
// admin (see Espace.jsx). Assumes an authenticated admin user — no auth
// gate here, the caller already checked it.
// admin or moderator (see Espace.jsx). Assumes an authenticated staff
// user — no auth gate here, the caller already checked it.
export function AdminShell() {
const { user, logout } = useAuth();
const [tab, setTab] = useState('dashboard');
const tabs = TABS.filter((t) => t.roles.includes(user.role));
const [tab, setTab] = useState(tabs[0].key);
const current = TABS.find((t) => t.key === tab);
const current = tabs.find((t) => t.key === tab) || tabs[0];
const today = new Date().toLocaleDateString('fr-FR', { weekday: 'long', day: 'numeric', month: 'long', year: 'numeric' });
return (
@@ -101,12 +107,14 @@ export function AdminShell() {
<div style={{ padding: '0 24px 26px', borderBottom: '1px solid rgba(255,255,255,.1)', display: 'flex', alignItems: 'center', gap: 12 }}>
<img src="/assets/logo.jpg" alt="SLUC" style={{ height: 40, width: 40, objectFit: 'cover', borderRadius: 4, background: '#fff' }} />
<div style={{ lineHeight: 1.1 }}>
<div className="serif" style={{ fontSize: 16, fontWeight: 600 }}>Admin</div>
<div className="serif" style={{ fontSize: 16, fontWeight: 600 }}>
{user.role === 'admin' ? 'Admin' : 'Modérateur'}
</div>
<div style={{ fontSize: 10, letterSpacing: '.14em', textTransform: 'uppercase', color: '#8A8279' }}>Business Club</div>
</div>
</div>
<nav style={{ padding: '20px 14px', display: 'flex', flexDirection: 'column', gap: 4, flex: 1 }}>
{TABS.map((t) => (
{tabs.map((t) => (
<button key={t.key} className={`admin-nav-btn${tab === t.key ? ' active' : ''}`} onClick={() => setTab(t.key)}>
{t.icon} {t.label}
</button>
@@ -138,6 +146,7 @@ export function AdminShell() {
{tab === 'inscriptions' && <InscriptionsTab />}
{tab === 'categories' && <CategoriesTab />}
{tab === 'contenu' && <ContenuTab />}
{tab === 'utilisateurs' && <UsersTab />}
</div>
</div>
</div>
+4 -4
View File
@@ -332,15 +332,15 @@ function Portal() {
);
}
// Single login entry point for both members and admins. Once authenticated,
// the content shown depends on the account's role — the URL and the login
// form never differ.
// Single login entry point for members, admins and moderators. Once
// authenticated, the content shown depends on the account's role — the
// URL and the login form never differ.
export default function Espace() {
const { user, loading } = useAuth();
if (loading) return <main style={{ minHeight: '60vh' }} />;
if (!user) return <main><LoginSection /></main>;
if (user.mustChangePassword) return <main><ForcedPasswordChange /></main>;
if (user.role === 'admin') return <AdminShell />;
if (user.role === 'admin' || user.role === 'moderator') return <AdminShell />;
return <main><Portal /></main>;
}