Files
CoHaiSe-CLOUD/frontend/src/pages/Admin.tsx
T
Gitea ActionsandEsiah 9dd1ad72e0
CD — Déploiement / deploy (push) Failing after 25s
feat: logo et favicon, confirmation modale, fil d'ariane, e-mails sombres (#4)
- logo embarque dans les e-mails (CID) et gabarit repense en mode sombre
- favicon multi-tailles + icone PNG, logo a gauche du titre (app et auth)
- modale de confirmation animee a la place de window.confirm
- bouton retour et fil d'ariane dans l'explorateur

---------

Co-authored-by: xEsiah <[email protected]>
Reviewed-on: #4
Reviewed-by: Esiah <[email protected]>
Co-authored-by: Gitea Actions <-[email protected]>
2026-10-16 11:08:47 +00:00

767 lines
24 KiB
TypeScript

import { useEffect, useRef, useState, type FormEvent } from "react";
import { Button, Input, Spinner } from "../ui/index.js";
import {
ApiError,
api,
formatDate,
type AdminStats,
type AdminUser,
type AuditEntry,
type StorageLocation,
} from "../lib/api.js";
import { Alert, Badge, EmptyState, Modal, PageHeader } from "../components/feedback.js";
import { useConfirm } from "../components/confirm.js";
import { IconAction } from "../components/IconAction.js";
import {
ActivityIcon,
HardDriveIcon,
PlusIcon,
TrashIcon,
UsersIcon,
} from "../components/icons.js";
const GB = 1024 ** 3;
const MB = 1024 ** 2;
const messageOf = (caught: unknown, fallback: string): string =>
caught instanceof ApiError ? caught.message : fallback;
const toGb = (bytes: number): string =>
(bytes / GB).toLocaleString("fr-FR", { maximumFractionDigits: 1 });
const StatCard = ({ label, value }: { label: string; value: string }) => (
<div className="rounded-lg border border-border bg-surface p-3">
<p className="font-display text-[0.6875rem] font-semibold uppercase tracking-label text-subtle-foreground">
{label}
</p>
<p className="mt-1 text-lg font-semibold text-foreground">{value}</p>
</div>
);
export const AdminUsers = () => {
const confirm = useConfirm();
const [users, setUsers] = useState<AdminUser[] | null>(null);
const [stats, setStats] = useState<AdminStats | null>(null);
const [q, setQ] = useState("");
const [error, setError] = useState<string | null>(null);
const [busy, setBusy] = useState<string | null>(null);
const [createOpen, setCreateOpen] = useState(false);
const [edit, setEdit] = useState<AdminUser | null>(null);
const [credentials, setCredentials] = useState<{ email: string; password: string } | null>(null);
const termRef = useRef("");
const load = async (term: string) => {
termRef.current = term;
setError(null);
try {
const { users: list } = await api.adminUsers(term || undefined);
setUsers(list);
} catch (caught) {
setError(messageOf(caught, "Chargement impossible."));
setUsers([]);
}
};
useEffect(() => {
void load("");
api
.adminStats()
.then(setStats)
.catch(() => undefined);
}, []);
const toggleActive = async (user: AdminUser) => {
setBusy(user.id);
setError(null);
try {
await api.adminUpdateUser(user.id, { is_active: !user.is_active });
await load(termRef.current);
} catch (caught) {
setError(messageOf(caught, "Mise à jour impossible."));
} finally {
setBusy(null);
}
};
const resetPassword = async (user: AdminUser) => {
setBusy(user.id);
setError(null);
try {
const { password } = await api.adminResetPassword(user.id);
setCredentials({ email: user.email, password });
} catch (caught) {
setError(messageOf(caught, "Réinitialisation impossible."));
} finally {
setBusy(null);
}
};
const removeUser = async (user: AdminUser) => {
const ok = await confirm({
title: "Supprimer le membre",
message: (
<>
Supprimer définitivement <span className="font-semibold text-foreground">{user.email}</span>{" "}
ainsi que ses fichiers ? Cette action est irréversible.
</>
),
confirmLabel: "Supprimer",
tone: "danger",
});
if (!ok) return;
setBusy(user.id);
setError(null);
try {
await api.adminDeleteUser(user.id);
await load(termRef.current);
} catch (caught) {
setError(messageOf(caught, "Suppression impossible."));
} finally {
setBusy(null);
}
};
return (
<div className="flex flex-col gap-5">
<PageHeader
title="Comptes"
description="Créez des membres, ajustez leurs quotas et gérez les accès."
actions={
<Button
size="sm"
iconLeading={<PlusIcon className="h-3.5 w-3.5" />}
onClick={() => setCreateOpen(true)}
>
Nouveau membre
</Button>
}
/>
{stats ? (
<div className="grid grid-cols-3 gap-3">
<StatCard label="Membres" value={String(stats.users)} />
<StatCard label="Fichiers" value={String(stats.files)} />
<StatCard label="Stockage" value={`${toGb(stats.usedBytes)} Go`} />
</div>
) : null}
<form
className="flex items-end gap-2"
onSubmit={(event) => {
event.preventDefault();
void load(q);
}}
>
<div className="flex-1">
<Input
label="Rechercher"
type="search"
placeholder="nom ou e-mail"
value={q}
onChange={(event) => setQ(event.target.value)}
/>
</div>
<Button type="submit" size="md" variant="secondary">
Filtrer
</Button>
</form>
{error ? <Alert>{error}</Alert> : null}
{users === null ? (
<div className="flex justify-center py-16">
<Spinner size="md" />
</div>
) : users.length === 0 ? (
<EmptyState icon={<UsersIcon className="h-8 w-8" />} title="Aucun membre" />
) : (
<ul className="flex flex-col divide-y divide-border rounded-lg border border-border bg-surface">
{users.map((user) => (
<li key={user.id} className="flex flex-wrap items-center gap-3 px-3 py-3">
<span className="min-w-0 flex-1">
<span className="flex items-center gap-2">
<span className="truncate text-sm font-medium text-foreground">
{user.first_name} {user.last_name}
</span>
{user.role_slug === "admin" ? <Badge tone="accent">Admin</Badge> : null}
{!user.is_active ? <Badge tone="danger">Inactif</Badge> : null}
{user.must_change_password ? <Badge tone="warning">À changer</Badge> : null}
</span>
<span className="block truncate text-[0.6875rem] text-subtle-foreground">
{user.email} · {toGb(user.used_bytes)} / {toGb(user.quota_bytes)} Go ·{" "}
{user.last_login_at
? `vu le ${formatDate(user.last_login_at)}`
: "jamais connecté"}
</span>
</span>
<div className="flex items-center gap-1">
<Button variant="ghost" size="sm" onClick={() => setEdit(user)}>
Modifier
</Button>
<IconAction
label={user.is_active ? "Désactiver" : "Réactiver"}
icon={<HardDriveIcon className="h-4 w-4" />}
isLoading={busy === user.id}
onClick={() => void toggleActive(user)}
/>
<IconAction
label="Réinitialiser le mot de passe"
icon={<ActivityIcon className="h-4 w-4" />}
isLoading={busy === user.id}
onClick={() => void resetPassword(user)}
/>
<IconAction
label="Supprimer"
icon={<TrashIcon className="h-4 w-4" />}
tone="danger"
isLoading={busy === user.id}
onClick={() => void removeUser(user)}
/>
</div>
</li>
))}
</ul>
)}
{createOpen ? (
<CreateUserDialog
onClose={() => setCreateOpen(false)}
onCreated={(email, password) => {
setCreateOpen(false);
setCredentials({ email, password });
void load(termRef.current);
}}
/>
) : null}
{edit ? (
<EditUserDialog
user={edit}
onClose={() => setEdit(null)}
onSaved={() => {
setEdit(null);
void load(termRef.current);
}}
/>
) : null}
<CredentialsModal credentials={credentials} onClose={() => setCredentials(null)} />
</div>
);
};
const CredentialsModal = ({
credentials,
onClose,
}: {
credentials: { email: string; password: string } | null;
onClose: () => void;
}) => {
if (!credentials) return null;
return (
<Modal open title="Identifiants générés" onClose={onClose}>
<div className="flex flex-col gap-4">
<Alert tone="success">
Transmettez ces informations par un canal sûr : le mot de passe ne sera plus affiché.
</Alert>
<dl className="flex flex-col gap-2 text-xs">
<div>
<dt className="text-subtle-foreground">Adresse</dt>
<dd className="font-medium text-foreground">{credentials.email}</dd>
</div>
<div>
<dt className="text-subtle-foreground">Mot de passe</dt>
<dd className="break-all font-mono text-foreground">{credentials.password}</dd>
</div>
</dl>
<div className="flex justify-end">
<Button size="md" onClick={onClose}>
Terminé
</Button>
</div>
</div>
</Modal>
);
};
const CreateUserDialog = ({
onClose,
onCreated,
}: {
onClose: () => void;
onCreated: (email: string, password: string) => void;
}) => {
const [email, setEmail] = useState("");
const [firstName, setFirstName] = useState("");
const [lastName, setLastName] = useState("");
const [role, setRole] = useState("user");
const [quotaGb, setQuotaGb] = useState("");
const [maxFileMb, setMaxFileMb] = useState("");
const [error, setError] = useState<string | null>(null);
const [busy, setBusy] = useState(false);
const submit = async (event: FormEvent<HTMLFormElement>) => {
event.preventDefault();
setBusy(true);
setError(null);
try {
const { user, password } = await api.adminCreateUser({
email: email.trim(),
first_name: firstName.trim(),
last_name: lastName.trim(),
role_slug: role,
quota_bytes: quotaGb ? Math.round(Number(quotaGb) * GB) : null,
max_file_bytes: maxFileMb ? Math.round(Number(maxFileMb) * MB) : null,
});
onCreated(user.email, password);
} catch (caught) {
setError(messageOf(caught, "Création impossible."));
} finally {
setBusy(false);
}
};
return (
<Modal open title="Nouveau membre" onClose={onClose}>
<form className="flex flex-col gap-3" onSubmit={(event) => void submit(event)}>
<Input
label="Adresse e-mail"
type="email"
required
autoFocus
value={email}
onChange={(event) => setEmail(event.target.value)}
/>
<div className="grid grid-cols-2 gap-3">
<Input
label="Prénom"
required
value={firstName}
onChange={(event) => setFirstName(event.target.value)}
/>
<Input
label="Nom"
required
value={lastName}
onChange={(event) => setLastName(event.target.value)}
/>
</div>
<label className="flex flex-col gap-1.5">
<span className="font-display text-[0.6875rem] font-semibold uppercase tracking-label text-foreground">
Rôle
</span>
<select
value={role}
onChange={(event) => setRole(event.target.value)}
className="h-10 w-full rounded-sm border border-border-control bg-surface px-3 text-sm text-foreground"
>
<option value="user">Utilisateur</option>
<option value="admin">Administrateur</option>
</select>
</label>
<div className="grid grid-cols-2 gap-3">
<Input
label="Quota (Go, optionnel)"
type="number"
min={1}
value={quotaGb}
onChange={(event) => setQuotaGb(event.target.value)}
/>
<Input
label="Fichier max (Mo)"
type="number"
min={1}
value={maxFileMb}
onChange={(event) => setMaxFileMb(event.target.value)}
/>
</div>
{error ? <Alert>{error}</Alert> : null}
<div className="flex justify-end gap-2">
<Button variant="ghost" size="md" onClick={onClose}>
Annuler
</Button>
<Button type="submit" size="md" isLoading={busy}>
Créer
</Button>
</div>
</form>
</Modal>
);
};
const EditUserDialog = ({
user,
onClose,
onSaved,
}: {
user: AdminUser;
onClose: () => void;
onSaved: () => void;
}) => {
const [firstName, setFirstName] = useState(user.first_name);
const [lastName, setLastName] = useState(user.last_name);
const [role, setRole] = useState(user.role_slug);
const [quotaGb, setQuotaGb] = useState(String(Math.round(user.quota_bytes / GB)));
const [maxFileMb, setMaxFileMb] = useState(String(Math.round(user.max_file_bytes / MB)));
const [error, setError] = useState<string | null>(null);
const [busy, setBusy] = useState(false);
const submit = async (event: FormEvent<HTMLFormElement>) => {
event.preventDefault();
setBusy(true);
setError(null);
try {
await api.adminUpdateUser(user.id, {
first_name: firstName.trim(),
last_name: lastName.trim(),
role_slug: role,
quota_bytes: Math.round(Number(quotaGb) * GB),
max_file_bytes: Math.round(Number(maxFileMb) * MB),
});
onSaved();
} catch (caught) {
setError(messageOf(caught, "Enregistrement impossible."));
} finally {
setBusy(false);
}
};
return (
<Modal open title="Modifier le membre" onClose={onClose}>
<form className="flex flex-col gap-3" onSubmit={(event) => void submit(event)}>
<div className="grid grid-cols-2 gap-3">
<Input
label="Prénom"
required
value={firstName}
onChange={(event) => setFirstName(event.target.value)}
/>
<Input
label="Nom"
required
value={lastName}
onChange={(event) => setLastName(event.target.value)}
/>
</div>
<label className="flex flex-col gap-1.5">
<span className="font-display text-[0.6875rem] font-semibold uppercase tracking-label text-foreground">
Rôle
</span>
<select
value={role}
onChange={(event) => setRole(event.target.value)}
className="h-10 w-full rounded-sm border border-border-control bg-surface px-3 text-sm text-foreground"
>
<option value="user">Utilisateur</option>
<option value="admin">Administrateur</option>
</select>
</label>
<div className="grid grid-cols-2 gap-3">
<Input
label="Quota (Go)"
type="number"
min={1}
value={quotaGb}
onChange={(event) => setQuotaGb(event.target.value)}
/>
<Input
label="Fichier max (Mo)"
type="number"
min={1}
value={maxFileMb}
onChange={(event) => setMaxFileMb(event.target.value)}
/>
</div>
{error ? <Alert>{error}</Alert> : null}
<div className="flex justify-end gap-2">
<Button variant="ghost" size="md" onClick={onClose}>
Annuler
</Button>
<Button type="submit" size="md" isLoading={busy}>
Enregistrer
</Button>
</div>
</form>
</Modal>
);
};
export const AdminStorage = () => {
const [locations, setLocations] = useState<StorageLocation[] | null>(null);
const [error, setError] = useState<string | null>(null);
const [createOpen, setCreateOpen] = useState(false);
const load = async () => {
setError(null);
try {
const { locations: list } = await api.adminStorageLocations();
setLocations(list);
} catch (caught) {
setError(messageOf(caught, "Chargement impossible."));
setLocations([]);
}
};
useEffect(() => {
void load();
}, []);
const toggle = async (location: StorageLocation) => {
setError(null);
try {
await api.adminUpdateStorageLocation(location.id, { is_active: !location.is_active });
await load();
} catch (caught) {
setError(messageOf(caught, "Mise à jour impossible."));
}
};
return (
<div className="flex flex-col gap-5">
<PageHeader
title="Emplacements de stockage"
description="Volumes montés utilisés pour stocker les fichiers."
actions={
<Button
size="sm"
iconLeading={<PlusIcon className="h-3.5 w-3.5" />}
onClick={() => setCreateOpen(true)}
>
Nouvel emplacement
</Button>
}
/>
{error ? <Alert>{error}</Alert> : null}
{locations === null ? (
<div className="flex justify-center py-16">
<Spinner size="md" />
</div>
) : locations.length === 0 ? (
<EmptyState icon={<HardDriveIcon className="h-8 w-8" />} title="Aucun emplacement" />
) : (
<ul className="flex flex-col divide-y divide-border rounded-lg border border-border bg-surface">
{locations.map((location) => (
<li key={location.id} className="flex flex-wrap items-center gap-3 px-3 py-3">
<span className="min-w-0 flex-1">
<span className="flex items-center gap-2">
<span className="truncate text-sm font-medium text-foreground">
{location.name}
</span>
{!location.is_active ? <Badge tone="danger">Inactif</Badge> : null}
</span>
<span className="block truncate text-[0.6875rem] text-subtle-foreground">
{location.slug} · {location.mount_path} ·{" "}
{location.quota_bytes
? `${toGb(location.used_bytes)} / ${toGb(location.quota_bytes)} Go`
: `${toGb(location.used_bytes)} Go utilisés`}
</span>
</span>
<Button variant="ghost" size="sm" onClick={() => void toggle(location)}>
{location.is_active ? "Désactiver" : "Réactiver"}
</Button>
</li>
))}
</ul>
)}
{createOpen ? (
<CreateLocationDialog
onClose={() => setCreateOpen(false)}
onCreated={() => {
setCreateOpen(false);
void load();
}}
/>
) : null}
</div>
);
};
const CreateLocationDialog = ({
onClose,
onCreated,
}: {
onClose: () => void;
onCreated: () => void;
}) => {
const [name, setName] = useState("");
const [slug, setSlug] = useState("");
const [mountPath, setMountPath] = useState("");
const [quotaGb, setQuotaGb] = useState("");
const [error, setError] = useState<string | null>(null);
const [busy, setBusy] = useState(false);
const submit = async (event: FormEvent<HTMLFormElement>) => {
event.preventDefault();
setBusy(true);
setError(null);
try {
await api.adminCreateStorageLocation({
name: name.trim(),
slug: slug.trim(),
mount_path: mountPath.trim(),
quota_bytes: quotaGb ? Math.round(Number(quotaGb) * GB) : null,
});
onCreated();
} catch (caught) {
setError(messageOf(caught, "Création impossible."));
} finally {
setBusy(false);
}
};
return (
<Modal open title="Nouvel emplacement" onClose={onClose}>
<form className="flex flex-col gap-3" onSubmit={(event) => void submit(event)}>
<Input
label="Nom"
required
autoFocus
value={name}
onChange={(event) => setName(event.target.value)}
/>
<Input
label="Identifiant technique"
required
placeholder="principal"
pattern="[a-z0-9][a-z0-9-]*"
value={slug}
onChange={(event) => setSlug(event.target.value)}
/>
<Input
label="Chemin de montage"
required
placeholder="/data/cloud"
value={mountPath}
onChange={(event) => setMountPath(event.target.value)}
/>
<Input
label="Quota (Go, optionnel)"
type="number"
min={1}
value={quotaGb}
onChange={(event) => setQuotaGb(event.target.value)}
/>
{error ? <Alert>{error}</Alert> : null}
<div className="flex justify-end gap-2">
<Button variant="ghost" size="md" onClick={onClose}>
Annuler
</Button>
<Button type="submit" size="md" isLoading={busy}>
Créer
</Button>
</div>
</form>
</Modal>
);
};
export const AdminAudit = () => {
const [entries, setEntries] = useState<AuditEntry[] | null>(null);
const [action, setAction] = useState("");
const [error, setError] = useState<string | null>(null);
const [loadingMore, setLoadingMore] = useState(false);
const load = async (term: string) => {
setError(null);
try {
const { entries: list } = await api.adminAudit(100, 0, term || undefined);
setEntries(list);
} catch (caught) {
setError(messageOf(caught, "Chargement impossible."));
setEntries([]);
}
};
useEffect(() => {
void load("");
}, []);
const loadMore = async () => {
if (!entries) return;
setLoadingMore(true);
setError(null);
try {
const { entries: more } = await api.adminAudit(100, entries.length, action || undefined);
setEntries((previous) => [...(previous ?? []), ...more]);
} catch (caught) {
setError(messageOf(caught, "Chargement impossible."));
} finally {
setLoadingMore(false);
}
};
return (
<div className="flex flex-col gap-5">
<PageHeader title="Journal d'activité" description="Dernières actions enregistrées." />
<form
className="flex items-end gap-2"
onSubmit={(event) => {
event.preventDefault();
void load(action);
}}
>
<div className="flex-1">
<Input
label="Filtrer par action"
placeholder="auth.login, file.upload…"
value={action}
onChange={(event) => setAction(event.target.value)}
/>
</div>
<Button type="submit" variant="secondary" size="md">
Filtrer
</Button>
</form>
{error ? <Alert>{error}</Alert> : null}
{entries === null ? (
<div className="flex justify-center py-16">
<Spinner size="md" />
</div>
) : entries.length === 0 ? (
<EmptyState icon={<ActivityIcon className="h-8 w-8" />} title="Aucune entrée" />
) : (
<>
<ul className="flex flex-col divide-y divide-border rounded-lg border border-border bg-surface">
{entries.map((entry) => (
<li key={entry.id} className="flex flex-wrap items-center gap-3 px-3 py-2.5">
<span className="min-w-0 flex-1">
<span className="block truncate text-sm font-medium text-foreground">
{entry.action}
<span className="ml-2 font-normal text-subtle-foreground">
{entry.resource}
{entry.resource_id ? ` · ${entry.resource_id}` : ""}
</span>
</span>
<span className="block truncate text-[0.6875rem] text-subtle-foreground">
{entry.user_email ?? "système"} · {formatDate(entry.created_at)}
{entry.ip_address ? ` · ${entry.ip_address}` : ""}
</span>
</span>
</li>
))}
</ul>
{entries.length >= 100 ? (
<div className="flex justify-center">
<Button
variant="secondary"
size="md"
isLoading={loadingMore}
onClick={() => void loadMore()}
>
Charger plus
</Button>
</div>
) : null}
</>
)}
</div>
);
};