feat: add admin role management with user authentication checks and update sidebar for admin access

This commit is contained in:
Julien Froidefond
2025-10-16 22:39:04 +02:00
parent 83f523c11a
commit 9899789fce
25 changed files with 1636 additions and 6 deletions

View File

@@ -0,0 +1,88 @@
"use client";
import { useState, useCallback } from "react";
import type { AdminUserData } from "@/lib/services/admin.service";
import { StatsCards } from "./StatsCards";
import { UsersTable } from "./UsersTable";
import { Button } from "@/components/ui/button";
import { RefreshCw } from "lucide-react";
import { useToast } from "@/components/ui/use-toast";
interface AdminContentProps {
initialUsers: AdminUserData[];
initialStats: {
totalUsers: number;
totalAdmins: number;
usersWithKomga: number;
usersWithPreferences: number;
};
}
export function AdminContent({ initialUsers, initialStats }: AdminContentProps) {
const [users, setUsers] = useState(initialUsers);
const [stats, setStats] = useState(initialStats);
const [isRefreshing, setIsRefreshing] = useState(false);
const { toast } = useToast();
const refreshData = useCallback(async () => {
setIsRefreshing(true);
try {
const [usersResponse, statsResponse] = await Promise.all([
fetch("/api/admin/users"),
fetch("/api/admin/stats"),
]);
if (!usersResponse.ok || !statsResponse.ok) {
throw new Error("Erreur lors du rafraîchissement");
}
const [newUsers, newStats] = await Promise.all([
usersResponse.json(),
statsResponse.json(),
]);
setUsers(newUsers);
setStats(newStats);
toast({
title: "Données rafraîchies",
description: "Les données ont été mises à jour",
});
} catch {
toast({
variant: "destructive",
title: "Erreur",
description: "Impossible de rafraîchir les données",
});
} finally {
setIsRefreshing(false);
}
}, [toast]);
return (
<div className="container mx-auto px-4 py-8">
<div className="max-w-7xl mx-auto space-y-8">
<div className="flex items-center justify-between">
<div>
<h1 className="text-3xl font-bold">Administration</h1>
<p className="text-muted-foreground mt-2">
Gérez les utilisateurs de la plateforme
</p>
</div>
<Button onClick={refreshData} disabled={isRefreshing}>
<RefreshCw className={`h-4 w-4 mr-2 ${isRefreshing ? "animate-spin" : ""}`} />
Rafraîchir
</Button>
</div>
<StatsCards stats={stats} />
<div>
<h2 className="text-2xl font-semibold mb-4">Utilisateurs</h2>
<UsersTable users={users} onUserUpdated={refreshData} />
</div>
</div>
</div>
);
}

View File

@@ -0,0 +1,92 @@
"use client";
import { useState } from "react";
import {
AlertDialog,
AlertDialogAction,
AlertDialogCancel,
AlertDialogContent,
AlertDialogDescription,
AlertDialogFooter,
AlertDialogHeader,
AlertDialogTitle,
} from "@/components/ui/alert-dialog";
import { useToast } from "@/components/ui/use-toast";
import type { AdminUserData } from "@/lib/services/admin.service";
interface DeleteUserDialogProps {
user: AdminUserData;
open: boolean;
onOpenChange: (open: boolean) => void;
onSuccess: () => void;
}
export function DeleteUserDialog({
user,
open,
onOpenChange,
onSuccess,
}: DeleteUserDialogProps) {
const [isLoading, setIsLoading] = useState(false);
const { toast } = useToast();
const handleDelete = async () => {
setIsLoading(true);
try {
const response = await fetch(`/api/admin/users/${user.id}`, {
method: "DELETE",
});
if (!response.ok) {
const data = await response.json();
throw new Error(data.error || "Erreur lors de la suppression");
}
toast({
title: "Succès",
description: "L'utilisateur a été supprimé",
});
onSuccess();
} catch (error) {
toast({
variant: "destructive",
title: "Erreur",
description: error instanceof Error ? error.message : "Une erreur est survenue",
});
setIsLoading(false);
}
};
return (
<AlertDialog open={open} onOpenChange={onOpenChange}>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>Êtes-vous sûr?</AlertDialogTitle>
<AlertDialogDescription>
Vous allez supprimer l&apos;utilisateur <strong>{user.email}</strong>.
<br />
Cette action est irréversible et supprimera également :
<ul className="list-disc list-inside mt-2">
<li>Sa configuration Komga</li>
<li>Ses préférences</li>
<li>Ses favoris ({user._count?.favorites || 0})</li>
</ul>
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel disabled={isLoading}>Annuler</AlertDialogCancel>
<AlertDialogAction
onClick={handleDelete}
disabled={isLoading}
className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
>
{isLoading ? "Suppression..." : "Supprimer"}
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
);
}

View File

@@ -0,0 +1,128 @@
"use client";
import { useState } from "react";
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
} from "@/components/ui/dialog";
import { Button } from "@/components/ui/button";
import { Checkbox } from "@/components/ui/checkbox";
import { Label } from "@/components/ui/label";
import { useToast } from "@/components/ui/use-toast";
import type { AdminUserData } from "@/lib/services/admin.service";
interface EditUserDialogProps {
user: AdminUserData;
open: boolean;
onOpenChange: (open: boolean) => void;
onSuccess: () => void;
}
const AVAILABLE_ROLES = [
{ value: "ROLE_USER", label: "User" },
{ value: "ROLE_ADMIN", label: "Admin" },
];
export function EditUserDialog({
user,
open,
onOpenChange,
onSuccess,
}: EditUserDialogProps) {
const [selectedRoles, setSelectedRoles] = useState<string[]>(user.roles);
const [isLoading, setIsLoading] = useState(false);
const { toast } = useToast();
const handleRoleToggle = (role: string) => {
setSelectedRoles((prev) =>
prev.includes(role) ? prev.filter((r) => r !== role) : [...prev, role]
);
};
const handleSubmit = async () => {
if (selectedRoles.length === 0) {
toast({
variant: "destructive",
title: "Erreur",
description: "L'utilisateur doit avoir au moins un rôle",
});
return;
}
setIsLoading(true);
try {
const response = await fetch(`/api/admin/users/${user.id}`, {
method: "PATCH",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ roles: selectedRoles }),
});
if (!response.ok) {
const data = await response.json();
throw new Error(data.error || "Erreur lors de la mise à jour");
}
toast({
title: "Succès",
description: "Les rôles ont été mis à jour",
});
onSuccess();
} catch (error) {
toast({
variant: "destructive",
title: "Erreur",
description: error instanceof Error ? error.message : "Une erreur est survenue",
});
} finally {
setIsLoading(false);
}
};
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent>
<DialogHeader>
<DialogTitle>Modifier l&apos;utilisateur</DialogTitle>
<DialogDescription>
Gérer les rôles de <strong>{user.email}</strong>
</DialogDescription>
</DialogHeader>
<div className="space-y-4 py-4">
<div className="space-y-2">
<Label>Rôles</Label>
{AVAILABLE_ROLES.map((role) => (
<div key={role.value} className="flex items-center space-x-2">
<Checkbox
id={role.value}
checked={selectedRoles.includes(role.value)}
onCheckedChange={() => handleRoleToggle(role.value)}
disabled={isLoading}
/>
<Label htmlFor={role.value} className="font-normal cursor-pointer">
{role.label}
</Label>
</div>
))}
</div>
</div>
<DialogFooter>
<Button variant="outline" onClick={() => onOpenChange(false)} disabled={isLoading}>
Annuler
</Button>
<Button onClick={handleSubmit} disabled={isLoading}>
{isLoading ? "Enregistrement..." : "Enregistrer"}
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
);
}

View File

@@ -0,0 +1,170 @@
"use client";
import { useState } from "react";
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
} from "@/components/ui/dialog";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { useToast } from "@/components/ui/use-toast";
import { Lock } from "lucide-react";
import type { AdminUserData } from "@/lib/services/admin.service";
interface ResetPasswordDialogProps {
user: AdminUserData;
open: boolean;
onOpenChange: (open: boolean) => void;
onSuccess: () => void;
}
export function ResetPasswordDialog({
user,
open,
onOpenChange,
onSuccess,
}: ResetPasswordDialogProps) {
const [newPassword, setNewPassword] = useState("");
const [confirmPassword, setConfirmPassword] = useState("");
const [isLoading, setIsLoading] = useState(false);
const { toast } = useToast();
const handleSubmit = async () => {
if (!newPassword || !confirmPassword) {
toast({
variant: "destructive",
title: "Erreur",
description: "Veuillez remplir tous les champs",
});
return;
}
if (newPassword !== confirmPassword) {
toast({
variant: "destructive",
title: "Erreur",
description: "Les mots de passe ne correspondent pas",
});
return;
}
if (newPassword.length < 8) {
toast({
variant: "destructive",
title: "Erreur",
description: "Le mot de passe doit contenir au moins 8 caractères",
});
return;
}
setIsLoading(true);
try {
const response = await fetch(`/api/admin/users/${user.id}/password`, {
method: "PUT",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ newPassword }),
});
if (!response.ok) {
const data = await response.json();
throw new Error(data.error || "Erreur lors de la réinitialisation");
}
toast({
title: "Succès",
description: "Le mot de passe a été réinitialisé",
});
setNewPassword("");
setConfirmPassword("");
onSuccess();
} catch (error) {
toast({
variant: "destructive",
title: "Erreur",
description: error instanceof Error ? error.message : "Une erreur est survenue",
});
} finally {
setIsLoading(false);
}
};
const handleOpenChange = (open: boolean) => {
if (!open) {
setNewPassword("");
setConfirmPassword("");
}
onOpenChange(open);
};
return (
<Dialog open={open} onOpenChange={handleOpenChange}>
<DialogContent>
<DialogHeader>
<DialogTitle>Réinitialiser le mot de passe</DialogTitle>
<DialogDescription>
Définir un nouveau mot de passe pour <strong>{user.email}</strong>
</DialogDescription>
</DialogHeader>
<div className="space-y-4 py-4">
<div className="space-y-2">
<Label htmlFor="newPassword">Nouveau mot de passe</Label>
<div className="relative">
<Lock className="absolute left-3 top-3 h-4 w-4 text-muted-foreground" />
<Input
id="newPassword"
type="password"
value={newPassword}
onChange={(e) => setNewPassword(e.target.value)}
className="pl-9"
placeholder="Minimum 8 caractères"
disabled={isLoading}
/>
</div>
</div>
<div className="space-y-2">
<Label htmlFor="confirmPassword">Confirmer le mot de passe</Label>
<div className="relative">
<Lock className="absolute left-3 top-3 h-4 w-4 text-muted-foreground" />
<Input
id="confirmPassword"
type="password"
value={confirmPassword}
onChange={(e) => setConfirmPassword(e.target.value)}
className="pl-9"
placeholder="Confirmer le nouveau mot de passe"
disabled={isLoading}
/>
</div>
</div>
<p className="text-sm text-muted-foreground">
Le mot de passe doit contenir au moins 8 caractères, une majuscule et un chiffre.
</p>
</div>
<DialogFooter>
<Button
variant="outline"
onClick={() => handleOpenChange(false)}
disabled={isLoading}
>
Annuler
</Button>
<Button onClick={handleSubmit} disabled={isLoading}>
{isLoading ? "Réinitialisation..." : "Réinitialiser"}
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
);
}

View File

@@ -0,0 +1,63 @@
"use client";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Users, Shield, Settings, Bookmark } from "lucide-react";
interface StatsCardsProps {
stats: {
totalUsers: number;
totalAdmins: number;
usersWithKomga: number;
usersWithPreferences: number;
};
}
export function StatsCards({ stats }: StatsCardsProps) {
const cards = [
{
title: "Utilisateurs totaux",
value: stats.totalUsers,
icon: Users,
description: "Comptes enregistrés",
},
{
title: "Administrateurs",
value: stats.totalAdmins,
icon: Shield,
description: "Avec privilèges admin",
},
{
title: "Config Komga",
value: stats.usersWithKomga,
icon: Bookmark,
description: "Utilisateurs configurés",
},
{
title: "Préférences",
value: stats.usersWithPreferences,
icon: Settings,
description: "Préférences personnalisées",
},
];
return (
<div className="grid gap-4 md:grid-cols-2 lg:grid-cols-4">
{cards.map((card) => {
const Icon = card.icon;
return (
<Card key={card.title}>
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
<CardTitle className="text-sm font-medium">{card.title}</CardTitle>
<Icon className="h-4 w-4 text-muted-foreground" />
</CardHeader>
<CardContent>
<div className="text-2xl font-bold">{card.value}</div>
<p className="text-xs text-muted-foreground">{card.description}</p>
</CardContent>
</Card>
);
})}
</div>
);
}

View File

@@ -0,0 +1,170 @@
"use client";
import { useState } from "react";
import {
Table,
TableBody,
TableCell,
TableHead,
TableHeader,
TableRow,
} from "@/components/ui/table";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Pencil, Trash2, Check, X, KeyRound } from "lucide-react";
import type { AdminUserData } from "@/lib/services/admin.service";
import { EditUserDialog } from "./EditUserDialog";
import { DeleteUserDialog } from "./DeleteUserDialog";
import { ResetPasswordDialog } from "./ResetPasswordDialog";
interface UsersTableProps {
users: AdminUserData[];
onUserUpdated: () => void;
}
export function UsersTable({ users, onUserUpdated }: UsersTableProps) {
const [editingUser, setEditingUser] = useState<AdminUserData | null>(null);
const [deletingUser, setDeletingUser] = useState<AdminUserData | null>(null);
const [resettingPasswordUser, setResettingPasswordUser] = useState<AdminUserData | null>(null);
return (
<>
<div className="rounded-md border">
<Table>
<TableHeader>
<TableRow>
<TableHead>Email</TableHead>
<TableHead>Rôles</TableHead>
<TableHead>Config Komga</TableHead>
<TableHead>Préférences</TableHead>
<TableHead>Favoris</TableHead>
<TableHead>Créé le</TableHead>
<TableHead className="text-right">Actions</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{users.length === 0 ? (
<TableRow>
<TableCell colSpan={7} className="text-center text-muted-foreground">
Aucun utilisateur
</TableCell>
</TableRow>
) : (
users.map((user) => (
<TableRow key={user.id}>
<TableCell className="font-medium">{user.email}</TableCell>
<TableCell>
<div className="flex gap-1">
{user.roles.map((role) => (
<Badge
key={role}
variant={role === "ROLE_ADMIN" ? "default" : "secondary"}
>
{role.replace("ROLE_", "")}
</Badge>
))}
</div>
</TableCell>
<TableCell>
{user.hasKomgaConfig ? (
<div className="flex items-center gap-2">
<Check className="h-4 w-4 text-green-500" />
<span className="text-xs text-green-600 dark:text-green-400">Configuré</span>
</div>
) : (
<div className="flex items-center gap-2">
<X className="h-4 w-4 text-red-500" />
<span className="text-xs text-red-600 dark:text-red-400">Non configuré</span>
</div>
)}
</TableCell>
<TableCell>
{user.hasPreferences ? (
<div className="flex items-center gap-2">
<Check className="h-4 w-4 text-green-500" />
<span className="text-xs text-green-600 dark:text-green-400">Oui</span>
</div>
) : (
<div className="flex items-center gap-2">
<X className="h-4 w-4 text-red-500" />
<span className="text-xs text-red-600 dark:text-red-400">Non</span>
</div>
)}
</TableCell>
<TableCell>{user._count?.favorites || 0}</TableCell>
<TableCell>
{new Date(user.createdAt).toLocaleDateString("fr-FR")}
</TableCell>
<TableCell className="text-right">
<div className="flex justify-end gap-2">
<Button
variant="ghost"
size="sm"
onClick={() => setEditingUser(user)}
title="Modifier les rôles"
>
<Pencil className="h-4 w-4" />
</Button>
<Button
variant="ghost"
size="sm"
onClick={() => setResettingPasswordUser(user)}
title="Réinitialiser le mot de passe"
>
<KeyRound className="h-4 w-4 text-blue-500" />
</Button>
<Button
variant="ghost"
size="sm"
onClick={() => setDeletingUser(user)}
title="Supprimer l'utilisateur"
>
<Trash2 className="h-4 w-4 text-destructive" />
</Button>
</div>
</TableCell>
</TableRow>
))
)}
</TableBody>
</Table>
</div>
{editingUser && (
<EditUserDialog
user={editingUser}
open={!!editingUser}
onOpenChange={(open) => !open && setEditingUser(null)}
onSuccess={() => {
setEditingUser(null);
onUserUpdated();
}}
/>
)}
{resettingPasswordUser && (
<ResetPasswordDialog
user={resettingPasswordUser}
open={!!resettingPasswordUser}
onOpenChange={(open) => !open && setResettingPasswordUser(null)}
onSuccess={() => {
setResettingPasswordUser(null);
}}
/>
)}
{deletingUser && (
<DeleteUserDialog
user={deletingUser}
open={!!deletingUser}
onOpenChange={(open) => !open && setDeletingUser(null)}
onSuccess={() => {
setDeletingUser(null);
onUserUpdated();
}}
/>
)}
</>
);
}