feat: add admin role management with user authentication checks and update sidebar for admin access
This commit is contained in:
24
src/app/admin/page.tsx
Normal file
24
src/app/admin/page.tsx
Normal file
@@ -0,0 +1,24 @@
|
||||
import { AdminService } from "@/lib/services/admin.service";
|
||||
import { redirect } from "next/navigation";
|
||||
import { isAdmin } from "@/lib/auth-utils";
|
||||
import { AdminContent } from "@/components/admin/AdminContent";
|
||||
|
||||
export default async function AdminPage() {
|
||||
try {
|
||||
const hasAdminAccess = await isAdmin();
|
||||
|
||||
if (!hasAdminAccess) {
|
||||
redirect("/");
|
||||
}
|
||||
|
||||
const [users, stats] = await Promise.all([
|
||||
AdminService.getAllUsers(),
|
||||
AdminService.getUserStats(),
|
||||
]);
|
||||
|
||||
return <AdminContent initialUsers={users} initialStats={stats} />;
|
||||
} catch (error) {
|
||||
console.error("Erreur lors du chargement de la page admin:", error);
|
||||
redirect("/");
|
||||
}
|
||||
}
|
||||
28
src/app/api/admin/stats/route.ts
Normal file
28
src/app/api/admin/stats/route.ts
Normal file
@@ -0,0 +1,28 @@
|
||||
import { NextResponse } from "next/server";
|
||||
import { AdminService } from "@/lib/services/admin.service";
|
||||
import { AppError } from "@/utils/errors";
|
||||
|
||||
export async function GET() {
|
||||
try {
|
||||
const stats = await AdminService.getUserStats();
|
||||
return NextResponse.json(stats);
|
||||
} catch (error) {
|
||||
console.error("Erreur lors de la récupération des stats:", error);
|
||||
|
||||
if (error instanceof AppError) {
|
||||
return NextResponse.json(
|
||||
{ error: error.message, code: error.code },
|
||||
{
|
||||
status: error.code === "AUTH_FORBIDDEN" ? 403 :
|
||||
error.code === "AUTH_UNAUTHENTICATED" ? 401 : 500
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
return NextResponse.json(
|
||||
{ error: "Erreur lors de la récupération des stats" },
|
||||
{ status: 500 }
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
56
src/app/api/admin/users/[userId]/password/route.ts
Normal file
56
src/app/api/admin/users/[userId]/password/route.ts
Normal file
@@ -0,0 +1,56 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { AdminService } from "@/lib/services/admin.service";
|
||||
import { AppError } from "@/utils/errors";
|
||||
import { AuthServerService } from "@/lib/services/auth-server.service";
|
||||
|
||||
export async function PUT(
|
||||
request: NextRequest,
|
||||
{ params }: { params: Promise<{ userId: string }> }
|
||||
) {
|
||||
try {
|
||||
const { userId } = await params;
|
||||
const body = await request.json();
|
||||
const { newPassword } = body;
|
||||
|
||||
if (!newPassword) {
|
||||
return NextResponse.json(
|
||||
{ error: "Nouveau mot de passe manquant" },
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
|
||||
// Vérifier que le mot de passe est fort
|
||||
if (!AuthServerService.isPasswordStrong(newPassword)) {
|
||||
return NextResponse.json(
|
||||
{
|
||||
error: "Le mot de passe doit contenir au moins 8 caractères, une majuscule et un chiffre"
|
||||
},
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
|
||||
await AdminService.resetUserPassword(userId, newPassword);
|
||||
|
||||
return NextResponse.json({ success: true });
|
||||
} catch (error) {
|
||||
console.error("Erreur lors de la réinitialisation du mot de passe:", error);
|
||||
|
||||
if (error instanceof AppError) {
|
||||
return NextResponse.json(
|
||||
{ error: error.message, code: error.code },
|
||||
{
|
||||
status: error.code === "AUTH_FORBIDDEN" ? 403 :
|
||||
error.code === "AUTH_UNAUTHENTICATED" ? 401 :
|
||||
error.code === "AUTH_USER_NOT_FOUND" ? 404 :
|
||||
error.code === "ADMIN_CANNOT_RESET_OWN_PASSWORD" ? 400 : 500
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
return NextResponse.json(
|
||||
{ error: "Erreur lors de la réinitialisation du mot de passe" },
|
||||
{ status: 500 }
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
75
src/app/api/admin/users/[userId]/route.ts
Normal file
75
src/app/api/admin/users/[userId]/route.ts
Normal file
@@ -0,0 +1,75 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { AdminService } from "@/lib/services/admin.service";
|
||||
import { AppError } from "@/utils/errors";
|
||||
|
||||
export async function PATCH(
|
||||
request: NextRequest,
|
||||
{ params }: { params: Promise<{ userId: string }> }
|
||||
) {
|
||||
try {
|
||||
const { userId } = await params;
|
||||
const body = await request.json();
|
||||
const { roles } = body;
|
||||
|
||||
if (!roles || !Array.isArray(roles)) {
|
||||
return NextResponse.json(
|
||||
{ error: "Rôles invalides" },
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
|
||||
await AdminService.updateUserRoles(userId, roles);
|
||||
|
||||
return NextResponse.json({ success: true });
|
||||
} catch (error) {
|
||||
console.error("Erreur lors de la mise à jour de l'utilisateur:", error);
|
||||
|
||||
if (error instanceof AppError) {
|
||||
return NextResponse.json(
|
||||
{ error: error.message, code: error.code },
|
||||
{
|
||||
status: error.code === "AUTH_FORBIDDEN" ? 403 :
|
||||
error.code === "AUTH_UNAUTHENTICATED" ? 401 :
|
||||
error.code === "AUTH_USER_NOT_FOUND" ? 404 : 500
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
return NextResponse.json(
|
||||
{ error: "Erreur lors de la mise à jour de l'utilisateur" },
|
||||
{ status: 500 }
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export async function DELETE(
|
||||
request: NextRequest,
|
||||
{ params }: { params: Promise<{ userId: string }> }
|
||||
) {
|
||||
try {
|
||||
const { userId } = await params;
|
||||
await AdminService.deleteUser(userId);
|
||||
|
||||
return NextResponse.json({ success: true });
|
||||
} catch (error) {
|
||||
console.error("Erreur lors de la suppression de l'utilisateur:", error);
|
||||
|
||||
if (error instanceof AppError) {
|
||||
return NextResponse.json(
|
||||
{ error: error.message, code: error.code },
|
||||
{
|
||||
status: error.code === "AUTH_FORBIDDEN" ? 403 :
|
||||
error.code === "AUTH_UNAUTHENTICATED" ? 401 :
|
||||
error.code === "AUTH_USER_NOT_FOUND" ? 404 :
|
||||
error.code === "ADMIN_CANNOT_DELETE_SELF" ? 400 : 500
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
return NextResponse.json(
|
||||
{ error: "Erreur lors de la suppression de l'utilisateur" },
|
||||
{ status: 500 }
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
27
src/app/api/admin/users/route.ts
Normal file
27
src/app/api/admin/users/route.ts
Normal file
@@ -0,0 +1,27 @@
|
||||
import { NextResponse } from "next/server";
|
||||
import { AdminService } from "@/lib/services/admin.service";
|
||||
import { AppError } from "@/utils/errors";
|
||||
|
||||
export async function GET() {
|
||||
try {
|
||||
const users = await AdminService.getAllUsers();
|
||||
return NextResponse.json(users);
|
||||
} catch (error) {
|
||||
console.error("Erreur lors de la récupération des utilisateurs:", error);
|
||||
|
||||
if (error instanceof AppError) {
|
||||
return NextResponse.json(
|
||||
{ error: error.message, code: error.code },
|
||||
{
|
||||
status: error.code === "AUTH_FORBIDDEN" ? 403 :
|
||||
error.code === "AUTH_UNAUTHENTICATED" ? 401 : 500
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
return NextResponse.json(
|
||||
{ error: "Erreur lors de la récupération des utilisateurs" },
|
||||
{ status: 500 }
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -74,14 +74,16 @@ export default async function RootLayout({ children }: { children: React.ReactNo
|
||||
let libraries: KomgaLibrary[] = [];
|
||||
let favorites: KomgaSeries[] = [];
|
||||
let preferences: UserPreferences = defaultPreferences;
|
||||
let userIsAdmin = false;
|
||||
|
||||
try {
|
||||
// Tentative de chargement des données. Si l'utilisateur n'est pas authentifié,
|
||||
// les services lanceront une erreur mais l'application continuera de fonctionner
|
||||
const [librariesData, favoritesData, preferencesData] = await Promise.allSettled([
|
||||
const [librariesData, favoritesData, preferencesData, isAdminCheck] = await Promise.allSettled([
|
||||
LibraryService.getLibraries(),
|
||||
FavoriteService.getAllFavoriteIds(),
|
||||
PreferencesService.getPreferences(),
|
||||
import("@/lib/auth-utils").then((m) => m.isAdmin()),
|
||||
]);
|
||||
|
||||
if (librariesData.status === "fulfilled") {
|
||||
@@ -95,6 +97,10 @@ export default async function RootLayout({ children }: { children: React.ReactNo
|
||||
if (preferencesData.status === "fulfilled") {
|
||||
preferences = preferencesData.value;
|
||||
}
|
||||
|
||||
if (isAdminCheck.status === "fulfilled") {
|
||||
userIsAdmin = isAdminCheck.value;
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("Erreur lors du chargement des données de la sidebar:", error);
|
||||
}
|
||||
@@ -162,7 +168,11 @@ export default async function RootLayout({ children }: { children: React.ReactNo
|
||||
<AuthProvider>
|
||||
<I18nProvider locale={locale}>
|
||||
<PreferencesProvider initialPreferences={preferences}>
|
||||
<ClientLayout initialLibraries={libraries} initialFavorites={favorites}>
|
||||
<ClientLayout
|
||||
initialLibraries={libraries}
|
||||
initialFavorites={favorites}
|
||||
userIsAdmin={userIsAdmin}
|
||||
>
|
||||
{children}
|
||||
</ClientLayout>
|
||||
</PreferencesProvider>
|
||||
|
||||
88
src/components/admin/AdminContent.tsx
Normal file
88
src/components/admin/AdminContent.tsx
Normal 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>
|
||||
);
|
||||
}
|
||||
|
||||
92
src/components/admin/DeleteUserDialog.tsx
Normal file
92
src/components/admin/DeleteUserDialog.tsx
Normal 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'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>
|
||||
);
|
||||
}
|
||||
|
||||
128
src/components/admin/EditUserDialog.tsx
Normal file
128
src/components/admin/EditUserDialog.tsx
Normal 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'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>
|
||||
);
|
||||
}
|
||||
|
||||
170
src/components/admin/ResetPasswordDialog.tsx
Normal file
170
src/components/admin/ResetPasswordDialog.tsx
Normal 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>
|
||||
);
|
||||
}
|
||||
|
||||
63
src/components/admin/StatsCards.tsx
Normal file
63
src/components/admin/StatsCards.tsx
Normal 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>
|
||||
);
|
||||
}
|
||||
|
||||
170
src/components/admin/UsersTable.tsx
Normal file
170
src/components/admin/UsersTable.tsx
Normal 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();
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -20,9 +20,10 @@ interface ClientLayoutProps {
|
||||
children: React.ReactNode;
|
||||
initialLibraries: KomgaLibrary[];
|
||||
initialFavorites: KomgaSeries[];
|
||||
userIsAdmin?: boolean;
|
||||
}
|
||||
|
||||
export default function ClientLayout({ children, initialLibraries = [], initialFavorites = [] }: ClientLayoutProps) {
|
||||
export default function ClientLayout({ children, initialLibraries = [], initialFavorites = [], userIsAdmin = false }: ClientLayoutProps) {
|
||||
const [isSidebarOpen, setIsSidebarOpen] = useState(false);
|
||||
const pathname = usePathname();
|
||||
|
||||
@@ -77,7 +78,8 @@ export default function ClientLayout({ children, initialLibraries = [], initialF
|
||||
isOpen={isSidebarOpen}
|
||||
onClose={handleCloseSidebar}
|
||||
initialLibraries={initialLibraries}
|
||||
initialFavorites={initialFavorites}
|
||||
initialFavorites={initialFavorites}
|
||||
userIsAdmin={userIsAdmin}
|
||||
/>
|
||||
)}
|
||||
<main className={`${!isPublicRoute ? "container pt-safe" : ""}`}>{children}</main>
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
"use client";
|
||||
|
||||
import { Home, Library, Settings, LogOut, RefreshCw, Star, Download, User } from "lucide-react";
|
||||
import { Home, Library, Settings, LogOut, RefreshCw, Star, Download, User, Shield } from "lucide-react";
|
||||
import { usePathname, useRouter } from "next/navigation";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { signOut } from "next-auth/react";
|
||||
@@ -18,9 +18,10 @@ interface SidebarProps {
|
||||
onClose: () => void;
|
||||
initialLibraries: KomgaLibrary[];
|
||||
initialFavorites: KomgaSeries[];
|
||||
userIsAdmin?: boolean;
|
||||
}
|
||||
|
||||
export function Sidebar({ isOpen, onClose, initialLibraries, initialFavorites }: SidebarProps) {
|
||||
export function Sidebar({ isOpen, onClose, initialLibraries, initialFavorites, userIsAdmin = false }: SidebarProps) {
|
||||
const { t } = useTranslate();
|
||||
const pathname = usePathname();
|
||||
const router = useRouter();
|
||||
@@ -294,6 +295,18 @@ export function Sidebar({ isOpen, onClose, initialLibraries, initialFavorites }:
|
||||
<Settings className="mr-2 h-4 w-4" />
|
||||
{t("sidebar.settings.preferences")}
|
||||
</button>
|
||||
{userIsAdmin && (
|
||||
<button
|
||||
onClick={() => handleLinkClick("/admin")}
|
||||
className={cn(
|
||||
"w-full flex items-center rounded-lg px-3 py-2 text-sm font-medium hover:bg-accent hover:text-accent-foreground",
|
||||
pathname === "/admin" ? "bg-accent" : "transparent"
|
||||
)}
|
||||
>
|
||||
<Shield className="mr-2 h-4 w-4" />
|
||||
{t("sidebar.admin")}
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
117
src/components/ui/alert-dialog.tsx
Normal file
117
src/components/ui/alert-dialog.tsx
Normal file
@@ -0,0 +1,117 @@
|
||||
"use client";
|
||||
|
||||
import * as React from "react";
|
||||
import * as AlertDialogPrimitive from "@radix-ui/react-alert-dialog";
|
||||
|
||||
import { cn } from "@/lib/utils";
|
||||
import { buttonVariants } from "@/components/ui/button";
|
||||
|
||||
const AlertDialog = AlertDialogPrimitive.Root;
|
||||
|
||||
const AlertDialogTrigger = AlertDialogPrimitive.Trigger;
|
||||
|
||||
const AlertDialogPortal = AlertDialogPrimitive.Portal;
|
||||
|
||||
const AlertDialogOverlay = React.forwardRef<
|
||||
React.ElementRef<typeof AlertDialogPrimitive.Overlay>,
|
||||
React.ComponentPropsWithoutRef<typeof AlertDialogPrimitive.Overlay>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<AlertDialogPrimitive.Overlay
|
||||
className={cn(
|
||||
"fixed inset-0 z-50 bg-black/80 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
ref={ref}
|
||||
/>
|
||||
));
|
||||
AlertDialogOverlay.displayName = AlertDialogPrimitive.Overlay.displayName;
|
||||
|
||||
const AlertDialogContent = React.forwardRef<
|
||||
React.ElementRef<typeof AlertDialogPrimitive.Content>,
|
||||
React.ComponentPropsWithoutRef<typeof AlertDialogPrimitive.Content>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<AlertDialogPortal>
|
||||
<AlertDialogOverlay />
|
||||
<AlertDialogPrimitive.Content
|
||||
ref={ref}
|
||||
className={cn(
|
||||
"fixed left-[50%] top-[50%] z-50 grid w-full max-w-lg translate-x-[-50%] translate-y-[-50%] gap-4 border bg-background p-6 shadow-lg duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%] sm:rounded-lg",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
</AlertDialogPortal>
|
||||
));
|
||||
AlertDialogContent.displayName = AlertDialogPrimitive.Content.displayName;
|
||||
|
||||
const AlertDialogHeader = ({ className, ...props }: React.HTMLAttributes<HTMLDivElement>) => (
|
||||
<div className={cn("flex flex-col space-y-2 text-center sm:text-left", className)} {...props} />
|
||||
);
|
||||
AlertDialogHeader.displayName = "AlertDialogHeader";
|
||||
|
||||
const AlertDialogFooter = ({ className, ...props }: React.HTMLAttributes<HTMLDivElement>) => (
|
||||
<div
|
||||
className={cn("flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2", className)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
AlertDialogFooter.displayName = "AlertDialogFooter";
|
||||
|
||||
const AlertDialogTitle = React.forwardRef<
|
||||
React.ElementRef<typeof AlertDialogPrimitive.Title>,
|
||||
React.ComponentPropsWithoutRef<typeof AlertDialogPrimitive.Title>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<AlertDialogPrimitive.Title
|
||||
ref={ref}
|
||||
className={cn("text-lg font-semibold", className)}
|
||||
{...props}
|
||||
/>
|
||||
));
|
||||
AlertDialogTitle.displayName = AlertDialogPrimitive.Title.displayName;
|
||||
|
||||
const AlertDialogDescription = React.forwardRef<
|
||||
React.ElementRef<typeof AlertDialogPrimitive.Description>,
|
||||
React.ComponentPropsWithoutRef<typeof AlertDialogPrimitive.Description>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<AlertDialogPrimitive.Description
|
||||
ref={ref}
|
||||
className={cn("text-sm text-muted-foreground", className)}
|
||||
{...props}
|
||||
/>
|
||||
));
|
||||
AlertDialogDescription.displayName = AlertDialogPrimitive.Description.displayName;
|
||||
|
||||
const AlertDialogAction = React.forwardRef<
|
||||
React.ElementRef<typeof AlertDialogPrimitive.Action>,
|
||||
React.ComponentPropsWithoutRef<typeof AlertDialogPrimitive.Action>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<AlertDialogPrimitive.Action ref={ref} className={cn(buttonVariants(), className)} {...props} />
|
||||
));
|
||||
AlertDialogAction.displayName = AlertDialogPrimitive.Action.displayName;
|
||||
|
||||
const AlertDialogCancel = React.forwardRef<
|
||||
React.ElementRef<typeof AlertDialogPrimitive.Cancel>,
|
||||
React.ComponentPropsWithoutRef<typeof AlertDialogPrimitive.Cancel>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<AlertDialogPrimitive.Cancel
|
||||
ref={ref}
|
||||
className={cn(buttonVariants({ variant: "outline" }), "mt-2 sm:mt-0", className)}
|
||||
{...props}
|
||||
/>
|
||||
));
|
||||
AlertDialogCancel.displayName = AlertDialogPrimitive.Cancel.displayName;
|
||||
|
||||
export {
|
||||
AlertDialog,
|
||||
AlertDialogPortal,
|
||||
AlertDialogOverlay,
|
||||
AlertDialogTrigger,
|
||||
AlertDialogContent,
|
||||
AlertDialogHeader,
|
||||
AlertDialogFooter,
|
||||
AlertDialogTitle,
|
||||
AlertDialogDescription,
|
||||
AlertDialogAction,
|
||||
AlertDialogCancel,
|
||||
};
|
||||
29
src/components/ui/checkbox.tsx
Normal file
29
src/components/ui/checkbox.tsx
Normal file
@@ -0,0 +1,29 @@
|
||||
"use client";
|
||||
|
||||
import * as React from "react";
|
||||
import * as CheckboxPrimitive from "@radix-ui/react-checkbox";
|
||||
import { Check } from "lucide-react";
|
||||
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
const Checkbox = React.forwardRef<
|
||||
React.ElementRef<typeof CheckboxPrimitive.Root>,
|
||||
React.ComponentPropsWithoutRef<typeof CheckboxPrimitive.Root>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<CheckboxPrimitive.Root
|
||||
ref={ref}
|
||||
className={cn(
|
||||
"peer h-4 w-4 shrink-0 rounded-sm border border-primary ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 data-[state=checked]:bg-primary data-[state=checked]:text-primary-foreground",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
<CheckboxPrimitive.Indicator className={cn("flex items-center justify-center text-current")}>
|
||||
<Check className="h-4 w-4" />
|
||||
</CheckboxPrimitive.Indicator>
|
||||
</CheckboxPrimitive.Root>
|
||||
));
|
||||
Checkbox.displayName = CheckboxPrimitive.Root.displayName;
|
||||
|
||||
export { Checkbox };
|
||||
|
||||
104
src/components/ui/dialog.tsx
Normal file
104
src/components/ui/dialog.tsx
Normal file
@@ -0,0 +1,104 @@
|
||||
"use client";
|
||||
|
||||
import * as React from "react";
|
||||
import * as DialogPrimitive from "@radix-ui/react-dialog";
|
||||
import { X } from "lucide-react";
|
||||
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
const Dialog = DialogPrimitive.Root;
|
||||
|
||||
const DialogTrigger = DialogPrimitive.Trigger;
|
||||
|
||||
const DialogPortal = DialogPrimitive.Portal;
|
||||
|
||||
const DialogClose = DialogPrimitive.Close;
|
||||
|
||||
const DialogOverlay = React.forwardRef<
|
||||
React.ElementRef<typeof DialogPrimitive.Overlay>,
|
||||
React.ComponentPropsWithoutRef<typeof DialogPrimitive.Overlay>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<DialogPrimitive.Overlay
|
||||
ref={ref}
|
||||
className={cn(
|
||||
"fixed inset-0 z-50 bg-black/80 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
));
|
||||
DialogOverlay.displayName = DialogPrimitive.Overlay.displayName;
|
||||
|
||||
const DialogContent = React.forwardRef<
|
||||
React.ElementRef<typeof DialogPrimitive.Content>,
|
||||
React.ComponentPropsWithoutRef<typeof DialogPrimitive.Content>
|
||||
>(({ className, children, ...props }, ref) => (
|
||||
<DialogPortal>
|
||||
<DialogOverlay />
|
||||
<DialogPrimitive.Content
|
||||
ref={ref}
|
||||
className={cn(
|
||||
"fixed left-[50%] top-[50%] z-50 grid w-full max-w-lg translate-x-[-50%] translate-y-[-50%] gap-4 border bg-background p-6 shadow-lg duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%] sm:rounded-lg",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
{children}
|
||||
<DialogPrimitive.Close className="absolute right-4 top-4 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none data-[state=open]:bg-accent data-[state=open]:text-muted-foreground">
|
||||
<X className="h-4 w-4" />
|
||||
<span className="sr-only">Close</span>
|
||||
</DialogPrimitive.Close>
|
||||
</DialogPrimitive.Content>
|
||||
</DialogPortal>
|
||||
));
|
||||
DialogContent.displayName = DialogPrimitive.Content.displayName;
|
||||
|
||||
const DialogHeader = ({ className, ...props }: React.HTMLAttributes<HTMLDivElement>) => (
|
||||
<div className={cn("flex flex-col space-y-1.5 text-center sm:text-left", className)} {...props} />
|
||||
);
|
||||
DialogHeader.displayName = "DialogHeader";
|
||||
|
||||
const DialogFooter = ({ className, ...props }: React.HTMLAttributes<HTMLDivElement>) => (
|
||||
<div
|
||||
className={cn("flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2", className)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
DialogFooter.displayName = "DialogFooter";
|
||||
|
||||
const DialogTitle = React.forwardRef<
|
||||
React.ElementRef<typeof DialogPrimitive.Title>,
|
||||
React.ComponentPropsWithoutRef<typeof DialogPrimitive.Title>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<DialogPrimitive.Title
|
||||
ref={ref}
|
||||
className={cn("text-lg font-semibold leading-none tracking-tight", className)}
|
||||
{...props}
|
||||
/>
|
||||
));
|
||||
DialogTitle.displayName = DialogPrimitive.Title.displayName;
|
||||
|
||||
const DialogDescription = React.forwardRef<
|
||||
React.ElementRef<typeof DialogPrimitive.Description>,
|
||||
React.ComponentPropsWithoutRef<typeof DialogPrimitive.Description>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<DialogPrimitive.Description
|
||||
ref={ref}
|
||||
className={cn("text-sm text-muted-foreground", className)}
|
||||
{...props}
|
||||
/>
|
||||
));
|
||||
DialogDescription.displayName = DialogPrimitive.Description.displayName;
|
||||
|
||||
export {
|
||||
Dialog,
|
||||
DialogPortal,
|
||||
DialogOverlay,
|
||||
DialogClose,
|
||||
DialogTrigger,
|
||||
DialogContent,
|
||||
DialogHeader,
|
||||
DialogFooter,
|
||||
DialogTitle,
|
||||
DialogDescription,
|
||||
};
|
||||
96
src/components/ui/table.tsx
Normal file
96
src/components/ui/table.tsx
Normal file
@@ -0,0 +1,96 @@
|
||||
import * as React from "react";
|
||||
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
const Table = React.forwardRef<HTMLTableElement, React.HTMLAttributes<HTMLTableElement>>(
|
||||
({ className, ...props }, ref) => (
|
||||
<div className="relative w-full overflow-auto">
|
||||
<table
|
||||
ref={ref}
|
||||
className={cn("w-full caption-bottom text-sm", className)}
|
||||
{...props}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
);
|
||||
Table.displayName = "Table";
|
||||
|
||||
const TableHeader = React.forwardRef<
|
||||
HTMLTableSectionElement,
|
||||
React.HTMLAttributes<HTMLTableSectionElement>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<thead ref={ref} className={cn("[&_tr]:border-b", className)} {...props} />
|
||||
));
|
||||
TableHeader.displayName = "TableHeader";
|
||||
|
||||
const TableBody = React.forwardRef<
|
||||
HTMLTableSectionElement,
|
||||
React.HTMLAttributes<HTMLTableSectionElement>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<tbody ref={ref} className={cn("[&_tr:last-child]:border-0", className)} {...props} />
|
||||
));
|
||||
TableBody.displayName = "TableBody";
|
||||
|
||||
const TableFooter = React.forwardRef<
|
||||
HTMLTableSectionElement,
|
||||
React.HTMLAttributes<HTMLTableSectionElement>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<tfoot
|
||||
ref={ref}
|
||||
className={cn("border-t bg-muted/50 font-medium [&>tr]:last:border-b-0", className)}
|
||||
{...props}
|
||||
/>
|
||||
));
|
||||
TableFooter.displayName = "TableFooter";
|
||||
|
||||
const TableRow = React.forwardRef<HTMLTableRowElement, React.HTMLAttributes<HTMLTableRowElement>>(
|
||||
({ className, ...props }, ref) => (
|
||||
<tr
|
||||
ref={ref}
|
||||
className={cn(
|
||||
"border-b transition-colors hover:bg-muted/50 data-[state=selected]:bg-muted",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
);
|
||||
TableRow.displayName = "TableRow";
|
||||
|
||||
const TableHead = React.forwardRef<
|
||||
HTMLTableCellElement,
|
||||
React.ThHTMLAttributes<HTMLTableCellElement>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<th
|
||||
ref={ref}
|
||||
className={cn(
|
||||
"h-12 px-4 text-left align-middle font-medium text-muted-foreground [&:has([role=checkbox])]:pr-0",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
));
|
||||
TableHead.displayName = "TableHead";
|
||||
|
||||
const TableCell = React.forwardRef<
|
||||
HTMLTableCellElement,
|
||||
React.TdHTMLAttributes<HTMLTableCellElement>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<td
|
||||
ref={ref}
|
||||
className={cn("p-4 align-middle [&:has([role=checkbox])]:pr-0", className)}
|
||||
{...props}
|
||||
/>
|
||||
));
|
||||
TableCell.displayName = "TableCell";
|
||||
|
||||
const TableCaption = React.forwardRef<
|
||||
HTMLTableCaptionElement,
|
||||
React.HTMLAttributes<HTMLTableCaptionElement>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<caption ref={ref} className={cn("mt-4 text-sm text-muted-foreground", className)} {...props} />
|
||||
));
|
||||
TableCaption.displayName = "TableCaption";
|
||||
|
||||
export { Table, TableHeader, TableBody, TableFooter, TableHead, TableRow, TableCell, TableCaption };
|
||||
|
||||
@@ -18,6 +18,7 @@ export const ERROR_CODES = {
|
||||
INVALID_PASSWORD: "AUTH_INVALID_PASSWORD",
|
||||
PASSWORD_CHANGE_ERROR: "AUTH_PASSWORD_CHANGE_ERROR",
|
||||
FETCH_ERROR: "AUTH_FETCH_ERROR",
|
||||
FORBIDDEN: "AUTH_FORBIDDEN",
|
||||
},
|
||||
KOMGA: {
|
||||
MISSING_CONFIG: "KOMGA_MISSING_CONFIG",
|
||||
@@ -95,6 +96,15 @@ export const ERROR_CODES = {
|
||||
NETWORK_ERROR: "CLIENT_NETWORK_ERROR",
|
||||
REQUEST_FAILED: "CLIENT_REQUEST_FAILED",
|
||||
},
|
||||
ADMIN: {
|
||||
FETCH_USERS_ERROR: "ADMIN_FETCH_USERS_ERROR",
|
||||
UPDATE_USER_ERROR: "ADMIN_UPDATE_USER_ERROR",
|
||||
DELETE_USER_ERROR: "ADMIN_DELETE_USER_ERROR",
|
||||
FETCH_STATS_ERROR: "ADMIN_FETCH_STATS_ERROR",
|
||||
CANNOT_DELETE_SELF: "ADMIN_CANNOT_DELETE_SELF",
|
||||
RESET_PASSWORD_ERROR: "ADMIN_RESET_PASSWORD_ERROR",
|
||||
CANNOT_RESET_OWN_PASSWORD: "ADMIN_CANNOT_RESET_OWN_PASSWORD",
|
||||
},
|
||||
} as const;
|
||||
|
||||
type Values<T> = T[keyof T];
|
||||
|
||||
@@ -62,6 +62,7 @@
|
||||
"title": "Settings",
|
||||
"preferences": "Preferences"
|
||||
},
|
||||
"admin": "Administration",
|
||||
"logout": "Sign out"
|
||||
},
|
||||
"settings": {
|
||||
|
||||
@@ -62,6 +62,7 @@
|
||||
"title": "Configuration",
|
||||
"preferences": "Préférences"
|
||||
},
|
||||
"admin": "Administration",
|
||||
"logout": "Se déconnecter"
|
||||
},
|
||||
"settings": {
|
||||
|
||||
@@ -15,3 +15,22 @@ export async function getCurrentUser(): Promise<UserData | null> {
|
||||
authenticated: true,
|
||||
};
|
||||
}
|
||||
|
||||
export async function isAdmin(): Promise<boolean> {
|
||||
const user = await getCurrentUser();
|
||||
return user?.roles.includes("ROLE_ADMIN") ?? false;
|
||||
}
|
||||
|
||||
export async function requireAdmin(): Promise<UserData> {
|
||||
const user = await getCurrentUser();
|
||||
|
||||
if (!user) {
|
||||
throw new Error("Unauthenticated");
|
||||
}
|
||||
|
||||
if (!user.roles.includes("ROLE_ADMIN")) {
|
||||
throw new Error("Forbidden: Admin access required");
|
||||
}
|
||||
|
||||
return user;
|
||||
}
|
||||
|
||||
208
src/lib/services/admin.service.ts
Normal file
208
src/lib/services/admin.service.ts
Normal file
@@ -0,0 +1,208 @@
|
||||
import prisma from "@/lib/prisma";
|
||||
import { requireAdmin } from "../auth-utils";
|
||||
import { ERROR_CODES } from "../../constants/errorCodes";
|
||||
import { AppError } from "../../utils/errors";
|
||||
|
||||
export interface AdminUserData {
|
||||
id: string;
|
||||
email: string;
|
||||
roles: string[];
|
||||
createdAt: Date;
|
||||
updatedAt: Date;
|
||||
_count?: {
|
||||
favorites: number;
|
||||
};
|
||||
hasKomgaConfig: boolean;
|
||||
hasPreferences: boolean;
|
||||
}
|
||||
|
||||
export class AdminService {
|
||||
static async getAllUsers(): Promise<AdminUserData[]> {
|
||||
try {
|
||||
await requireAdmin();
|
||||
|
||||
const users = await prisma.user.findMany({
|
||||
select: {
|
||||
id: true,
|
||||
email: true,
|
||||
roles: true,
|
||||
createdAt: true,
|
||||
updatedAt: true,
|
||||
_count: {
|
||||
select: {
|
||||
favorites: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
orderBy: {
|
||||
createdAt: "desc",
|
||||
},
|
||||
});
|
||||
|
||||
// Vérifier les configs pour chaque user
|
||||
const usersWithConfigs = await Promise.all(
|
||||
users.map(async (user) => {
|
||||
const [komgaConfig, preferences] = await Promise.all([
|
||||
prisma.komgaConfig.findUnique({
|
||||
where: { userId: user.id },
|
||||
select: { id: true },
|
||||
}),
|
||||
prisma.preferences.findUnique({
|
||||
where: { userId: user.id },
|
||||
select: { id: true },
|
||||
}),
|
||||
]);
|
||||
|
||||
return {
|
||||
...user,
|
||||
hasKomgaConfig: !!komgaConfig,
|
||||
hasPreferences: !!preferences,
|
||||
};
|
||||
})
|
||||
);
|
||||
|
||||
return usersWithConfigs;
|
||||
} catch (error) {
|
||||
if (error instanceof Error && error.message.includes("Forbidden")) {
|
||||
throw new AppError(ERROR_CODES.AUTH.FORBIDDEN);
|
||||
}
|
||||
if (error instanceof AppError) {
|
||||
throw error;
|
||||
}
|
||||
throw new AppError(ERROR_CODES.ADMIN.FETCH_USERS_ERROR, {}, error);
|
||||
}
|
||||
}
|
||||
|
||||
static async updateUserRoles(userId: string, roles: string[]): Promise<void> {
|
||||
try {
|
||||
await requireAdmin();
|
||||
|
||||
// Vérifier que l'utilisateur existe
|
||||
const user = await prisma.user.findUnique({
|
||||
where: { id: userId },
|
||||
});
|
||||
|
||||
if (!user) {
|
||||
throw new AppError(ERROR_CODES.AUTH.USER_NOT_FOUND);
|
||||
}
|
||||
|
||||
// Mettre à jour les rôles
|
||||
await prisma.user.update({
|
||||
where: { id: userId },
|
||||
data: { roles },
|
||||
});
|
||||
} catch (error) {
|
||||
if (error instanceof Error && error.message.includes("Forbidden")) {
|
||||
throw new AppError(ERROR_CODES.AUTH.FORBIDDEN);
|
||||
}
|
||||
if (error instanceof AppError) {
|
||||
throw error;
|
||||
}
|
||||
throw new AppError(ERROR_CODES.ADMIN.UPDATE_USER_ERROR, {}, error);
|
||||
}
|
||||
}
|
||||
|
||||
static async deleteUser(userId: string): Promise<void> {
|
||||
try {
|
||||
const admin = await requireAdmin();
|
||||
|
||||
// Empêcher la suppression de son propre compte
|
||||
if (admin.id === userId) {
|
||||
throw new AppError(ERROR_CODES.ADMIN.CANNOT_DELETE_SELF);
|
||||
}
|
||||
|
||||
// Vérifier que l'utilisateur existe
|
||||
const user = await prisma.user.findUnique({
|
||||
where: { id: userId },
|
||||
});
|
||||
|
||||
if (!user) {
|
||||
throw new AppError(ERROR_CODES.AUTH.USER_NOT_FOUND);
|
||||
}
|
||||
|
||||
// Supprimer l'utilisateur (cascade supprimera les relations)
|
||||
await prisma.user.delete({
|
||||
where: { id: userId },
|
||||
});
|
||||
} catch (error) {
|
||||
if (error instanceof Error && error.message.includes("Forbidden")) {
|
||||
throw new AppError(ERROR_CODES.AUTH.FORBIDDEN);
|
||||
}
|
||||
if (error instanceof AppError) {
|
||||
throw error;
|
||||
}
|
||||
throw new AppError(ERROR_CODES.ADMIN.DELETE_USER_ERROR, {}, error);
|
||||
}
|
||||
}
|
||||
|
||||
static async resetUserPassword(userId: string, newPassword: string): Promise<void> {
|
||||
try {
|
||||
const admin = await requireAdmin();
|
||||
|
||||
// Empêcher la modification de son propre mot de passe via cette méthode
|
||||
if (admin.id === userId) {
|
||||
throw new AppError(ERROR_CODES.ADMIN.CANNOT_RESET_OWN_PASSWORD);
|
||||
}
|
||||
|
||||
// Vérifier que l'utilisateur existe
|
||||
const user = await prisma.user.findUnique({
|
||||
where: { id: userId },
|
||||
});
|
||||
|
||||
if (!user) {
|
||||
throw new AppError(ERROR_CODES.AUTH.USER_NOT_FOUND);
|
||||
}
|
||||
|
||||
// Hasher le nouveau mot de passe
|
||||
const bcrypt = await import("bcryptjs");
|
||||
const hashedPassword = await bcrypt.hash(newPassword, 10);
|
||||
|
||||
// Mettre à jour le mot de passe
|
||||
await prisma.user.update({
|
||||
where: { id: userId },
|
||||
data: { password: hashedPassword },
|
||||
});
|
||||
} catch (error) {
|
||||
if (error instanceof Error && error.message.includes("Forbidden")) {
|
||||
throw new AppError(ERROR_CODES.AUTH.FORBIDDEN);
|
||||
}
|
||||
if (error instanceof AppError) {
|
||||
throw error;
|
||||
}
|
||||
throw new AppError(ERROR_CODES.ADMIN.RESET_PASSWORD_ERROR, {}, error);
|
||||
}
|
||||
}
|
||||
|
||||
static async getUserStats() {
|
||||
try {
|
||||
await requireAdmin();
|
||||
|
||||
const [totalUsers, totalAdmins, usersWithKomga, usersWithPreferences] =
|
||||
await Promise.all([
|
||||
prisma.user.count(),
|
||||
prisma.user.count({
|
||||
where: {
|
||||
roles: {
|
||||
has: "ROLE_ADMIN",
|
||||
},
|
||||
},
|
||||
}),
|
||||
prisma.komgaConfig.count(),
|
||||
prisma.preferences.count(),
|
||||
]);
|
||||
|
||||
return {
|
||||
totalUsers,
|
||||
totalAdmins,
|
||||
usersWithKomga,
|
||||
usersWithPreferences,
|
||||
};
|
||||
} catch (error) {
|
||||
if (error instanceof Error && error.message.includes("Forbidden")) {
|
||||
throw new AppError(ERROR_CODES.AUTH.FORBIDDEN);
|
||||
}
|
||||
throw new AppError(ERROR_CODES.ADMIN.FETCH_STATS_ERROR, {}, error);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user