Availability based on permissions
This commit is contained in:
169
frontend/app/(auth)/dashboard/settings/media/_media.tsx
Normal file
169
frontend/app/(auth)/dashboard/settings/media/_media.tsx
Normal file
@@ -0,0 +1,169 @@
|
||||
"use client";
|
||||
|
||||
import { useEffect, useState } from "react";
|
||||
import Image from "next/image";
|
||||
import { Plus } from "lucide-react";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import {
|
||||
Pagination,
|
||||
PaginationContent,
|
||||
PaginationItem,
|
||||
PaginationLink,
|
||||
PaginationNext,
|
||||
PaginationPrevious,
|
||||
} from "@/components/ui/pagination";
|
||||
import { PhotoDialog } from "@/components/photo-dialog";
|
||||
import useFileUpload from "@/hooks/use-file-upload";
|
||||
import useMedia from "@/hooks/use-media";
|
||||
import Media from "@/interfaces/Media";
|
||||
import request from "@/lib/request";
|
||||
import IUser from "@/interfaces/IUser";
|
||||
|
||||
export default function PhotoGallery({ user }: { user: IUser }) {
|
||||
const {
|
||||
data,
|
||||
error: mediaError,
|
||||
isLoading,
|
||||
success,
|
||||
setPage,
|
||||
setLimit,
|
||||
mutate,
|
||||
} = useMedia();
|
||||
console.log(data);
|
||||
const [selectedPhoto, setSelectedPhoto] = useState<Media | null>(null);
|
||||
const [isAddDialogOpen, setIsAddDialogOpen] = useState(false);
|
||||
const { progress, isUploading, error, uploadFile, cancelUpload } =
|
||||
useFileUpload();
|
||||
|
||||
const handleAddPhoto = (newPhoto: Omit<Media, "id">, file: File) => {
|
||||
uploadFile(file, "/media/upload", (response) => {
|
||||
mutate();
|
||||
});
|
||||
};
|
||||
|
||||
const handleUpdatePhoto = async (
|
||||
body: Media | Omit<Media, "id">,
|
||||
file: File,
|
||||
) => {
|
||||
if (selectedPhoto) {
|
||||
const res = await request<Media>(
|
||||
`/media/${selectedPhoto.id}/update`,
|
||||
{
|
||||
method: "PATCH",
|
||||
requiresAuth: true,
|
||||
body,
|
||||
},
|
||||
);
|
||||
if (res.status === "Success") {
|
||||
mutate();
|
||||
}
|
||||
}
|
||||
setSelectedPhoto(null);
|
||||
};
|
||||
|
||||
const handleDeletePhoto = async (id: Media["id"]) => {
|
||||
try {
|
||||
const res = await request<undefined>(`/media/${id}/delete`, {
|
||||
method: "DELETE",
|
||||
requiresAuth: true,
|
||||
});
|
||||
if (res.status === "Success") mutate();
|
||||
} catch (e) {
|
||||
console.log(e);
|
||||
}
|
||||
setSelectedPhoto(null);
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="container mx-auto px-4 py-8">
|
||||
<div className="flex justify-between items-center mb-8">
|
||||
<h1 className="text-3xl font-bold">Gallerie Photo</h1>
|
||||
<Button
|
||||
disabled={isLoading}
|
||||
onClick={() => setIsAddDialogOpen(true)}
|
||||
>
|
||||
<Plus className="mr-2 h-4 w-4" /> Ajouter une photo
|
||||
</Button>
|
||||
</div>
|
||||
<div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-4">
|
||||
{data?.items.map((photo) => (
|
||||
<div
|
||||
key={photo.id}
|
||||
className="aspect-square overflow-hidden rounded-lg shadow-md cursor-pointer"
|
||||
onClick={() => setSelectedPhoto(photo)}
|
||||
>
|
||||
<Image
|
||||
src={photo.url || "/placeholder.svg"}
|
||||
alt={photo.alt}
|
||||
width={300}
|
||||
height={300}
|
||||
className="w-full h-full object-cover"
|
||||
/>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
<Pagination className="mt-8">
|
||||
<PaginationContent>
|
||||
<PaginationItem>
|
||||
<PaginationPrevious
|
||||
href="#"
|
||||
onClick={(e) => {
|
||||
e.preventDefault();
|
||||
setPage((prev) => Math.max(prev - 1, 1));
|
||||
}}
|
||||
className={
|
||||
data?.page === 1
|
||||
? "pointer-events-none opacity-50"
|
||||
: ""
|
||||
}
|
||||
/>
|
||||
</PaginationItem>
|
||||
{[...Array(data?.totalPages)].map((_, i) => (
|
||||
<PaginationItem key={i + 1}>
|
||||
<PaginationLink
|
||||
href="#"
|
||||
onClick={(e) => {
|
||||
e.preventDefault();
|
||||
setPage(i + 1);
|
||||
}}
|
||||
isActive={data?.page === i + 1}
|
||||
>
|
||||
{i + 1}
|
||||
</PaginationLink>
|
||||
</PaginationItem>
|
||||
))}
|
||||
<PaginationItem>
|
||||
<PaginationNext
|
||||
href="#"
|
||||
onClick={(e) => {
|
||||
e.preventDefault();
|
||||
setPage((prev) =>
|
||||
Math.min(prev + 1, data?.totalPages ?? 1),
|
||||
);
|
||||
}}
|
||||
className={
|
||||
data?.page === data?.totalPages
|
||||
? "pointer-events-none opacity-50"
|
||||
: ""
|
||||
}
|
||||
/>
|
||||
</PaginationItem>
|
||||
</PaginationContent>
|
||||
</Pagination>
|
||||
<PhotoDialog
|
||||
isOpen={!!selectedPhoto}
|
||||
photo={selectedPhoto || undefined}
|
||||
onClose={() =>
|
||||
setSelectedPhoto((p) => (isUploading ? p : null))
|
||||
}
|
||||
onDelete={handleDeletePhoto}
|
||||
onSave={handleUpdatePhoto}
|
||||
/>
|
||||
<PhotoDialog
|
||||
isOpen={isAddDialogOpen}
|
||||
onClose={() => setIsAddDialogOpen(false)}
|
||||
onSave={handleAddPhoto}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,168 +1,20 @@
|
||||
"use client";
|
||||
"use server";
|
||||
|
||||
import { useState } from "react";
|
||||
import Image from "next/image";
|
||||
import { Plus } from "lucide-react";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import {
|
||||
Pagination,
|
||||
PaginationContent,
|
||||
PaginationItem,
|
||||
PaginationLink,
|
||||
PaginationNext,
|
||||
PaginationPrevious,
|
||||
} from "@/components/ui/pagination";
|
||||
import { PhotoDialog } from "@/components/photo-dialog";
|
||||
import useFileUpload from "@/hooks/use-file-upload";
|
||||
import useMedia from "@/hooks/use-media";
|
||||
import Media from "@/interfaces/Media";
|
||||
import request from "@/lib/request";
|
||||
import getMe from "@/lib/getMe";
|
||||
import { redirect } from "next/navigation";
|
||||
import PhotoGallery from "./_media";
|
||||
import hasPermissions from "@/lib/hasPermissions";
|
||||
|
||||
export default function PhotoGallery() {
|
||||
const {
|
||||
data,
|
||||
error: mediaError,
|
||||
isLoading,
|
||||
success,
|
||||
setPage,
|
||||
setLimit,
|
||||
mutate,
|
||||
} = useMedia();
|
||||
console.log(data);
|
||||
const [selectedPhoto, setSelectedPhoto] = useState<Media | null>(null);
|
||||
const [isAddDialogOpen, setIsAddDialogOpen] = useState(false);
|
||||
const { progress, isUploading, error, uploadFile, cancelUpload } =
|
||||
useFileUpload();
|
||||
export default async function Page() {
|
||||
const me = await getMe();
|
||||
if (
|
||||
!me ||
|
||||
me.status === "Error" ||
|
||||
!me.data ||
|
||||
!hasPermissions(me.data.roles, { media: ["get"] })
|
||||
) {
|
||||
redirect("/dashboard");
|
||||
}
|
||||
|
||||
const handleAddPhoto = (newPhoto: Omit<Media, "id">, file: File) => {
|
||||
uploadFile(file, "/media/upload", (response) => {
|
||||
mutate();
|
||||
});
|
||||
};
|
||||
|
||||
const handleUpdatePhoto = async (
|
||||
body: Media | Omit<Media, "id">,
|
||||
file: File,
|
||||
) => {
|
||||
if (selectedPhoto) {
|
||||
const res = await request<Media>(
|
||||
`/media/${selectedPhoto.id}/update`,
|
||||
{
|
||||
method: "PATCH",
|
||||
requiresAuth: true,
|
||||
body,
|
||||
},
|
||||
);
|
||||
if (res.status === "Success") {
|
||||
mutate();
|
||||
}
|
||||
}
|
||||
setSelectedPhoto(null);
|
||||
};
|
||||
|
||||
const handleDeletePhoto = async (id: Media["id"]) => {
|
||||
try {
|
||||
const res = await request<undefined>(`/media/${id}/delete`, {
|
||||
method: "DELETE",
|
||||
requiresAuth: true,
|
||||
});
|
||||
if (res.status === "Success") mutate();
|
||||
} catch (e) {
|
||||
console.log(e);
|
||||
}
|
||||
setSelectedPhoto(null);
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="container mx-auto px-4 py-8">
|
||||
<div className="flex justify-between items-center mb-8">
|
||||
<h1 className="text-3xl font-bold">Gallerie Photo</h1>
|
||||
<Button
|
||||
disabled={isLoading}
|
||||
onClick={() => setIsAddDialogOpen(true)}
|
||||
>
|
||||
<Plus className="mr-2 h-4 w-4" /> Ajouter une photo
|
||||
</Button>
|
||||
</div>
|
||||
<div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-4">
|
||||
{data?.items.map((photo) => (
|
||||
<div
|
||||
key={photo.id}
|
||||
className="aspect-square overflow-hidden rounded-lg shadow-md cursor-pointer"
|
||||
onClick={() => setSelectedPhoto(photo)}
|
||||
>
|
||||
<Image
|
||||
src={photo.url || "/placeholder.svg"}
|
||||
alt={photo.alt}
|
||||
width={300}
|
||||
height={300}
|
||||
className="w-full h-full object-cover"
|
||||
/>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
<Pagination className="mt-8">
|
||||
<PaginationContent>
|
||||
<PaginationItem>
|
||||
<PaginationPrevious
|
||||
href="#"
|
||||
onClick={(e) => {
|
||||
e.preventDefault();
|
||||
setPage((prev) => Math.max(prev - 1, 1));
|
||||
}}
|
||||
className={
|
||||
data?.page === 1
|
||||
? "pointer-events-none opacity-50"
|
||||
: ""
|
||||
}
|
||||
/>
|
||||
</PaginationItem>
|
||||
{[...Array(data?.totalPages)].map((_, i) => (
|
||||
<PaginationItem key={i + 1}>
|
||||
<PaginationLink
|
||||
href="#"
|
||||
onClick={(e) => {
|
||||
e.preventDefault();
|
||||
setPage(i + 1);
|
||||
}}
|
||||
isActive={data?.page === i + 1}
|
||||
>
|
||||
{i + 1}
|
||||
</PaginationLink>
|
||||
</PaginationItem>
|
||||
))}
|
||||
<PaginationItem>
|
||||
<PaginationNext
|
||||
href="#"
|
||||
onClick={(e) => {
|
||||
e.preventDefault();
|
||||
setPage((prev) =>
|
||||
Math.min(prev + 1, data?.totalPages ?? 1),
|
||||
);
|
||||
}}
|
||||
className={
|
||||
data?.page === data?.totalPages
|
||||
? "pointer-events-none opacity-50"
|
||||
: ""
|
||||
}
|
||||
/>
|
||||
</PaginationItem>
|
||||
</PaginationContent>
|
||||
</Pagination>
|
||||
<PhotoDialog
|
||||
isOpen={!!selectedPhoto}
|
||||
photo={selectedPhoto || undefined}
|
||||
onClose={() =>
|
||||
setSelectedPhoto((p) => (isUploading ? p : null))
|
||||
}
|
||||
onDelete={handleDeletePhoto}
|
||||
onSave={handleUpdatePhoto}
|
||||
/>
|
||||
<PhotoDialog
|
||||
isOpen={isAddDialogOpen}
|
||||
onClose={() => setIsAddDialogOpen(false)}
|
||||
onSave={handleAddPhoto}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
return <PhotoGallery user={me.data} />;
|
||||
}
|
||||
|
||||
247
frontend/app/(auth)/dashboard/settings/roles/_roles.tsx
Normal file
247
frontend/app/(auth)/dashboard/settings/roles/_roles.tsx
Normal file
@@ -0,0 +1,247 @@
|
||||
"use client";
|
||||
|
||||
import { useState } from "react";
|
||||
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
|
||||
import { Checkbox } from "@/components/ui/checkbox";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
DialogTrigger,
|
||||
DialogFooter,
|
||||
} from "@/components/ui/dialog";
|
||||
import { ChevronDown, ChevronRight, Plus, Trash2 } from "lucide-react";
|
||||
import { toTitleCase } from "@/lib/utils";
|
||||
import { useApi } from "@/hooks/use-api";
|
||||
import request from "@/lib/request";
|
||||
import IUser from "@/interfaces/IUser";
|
||||
import hasPermissions from "@/lib/hasPermissions";
|
||||
|
||||
type Action = string;
|
||||
|
||||
interface Permission {
|
||||
resource: string;
|
||||
action: Action;
|
||||
}
|
||||
|
||||
interface Role {
|
||||
id: string;
|
||||
name: string;
|
||||
permissions?: Permission[];
|
||||
}
|
||||
|
||||
interface PermissionsGrouped {
|
||||
[key: string]: string[];
|
||||
}
|
||||
|
||||
export default function RolesAndPermissions({ user }: { user: IUser }) {
|
||||
const [newRoleName, setNewRoleName] = useState<string>("");
|
||||
const [isDialogOpen, setIsDialogOpen] = useState<boolean>(false);
|
||||
|
||||
const { data: permissions } = useApi<PermissionsGrouped>(
|
||||
"/permissions/grouped",
|
||||
{},
|
||||
true,
|
||||
);
|
||||
|
||||
const { data: roles, mutate: rolesMutate } = useApi<Role[]>(
|
||||
"/roles",
|
||||
{},
|
||||
true,
|
||||
);
|
||||
|
||||
const addNewRole = async () => {
|
||||
if (newRoleName.trim() === "") return;
|
||||
|
||||
const res = await request("/roles/new", {
|
||||
requiresAuth: true,
|
||||
method: "POST",
|
||||
body: { name: newRoleName },
|
||||
});
|
||||
|
||||
if (res.status === "Success") rolesMutate();
|
||||
|
||||
setNewRoleName("");
|
||||
setIsDialogOpen(false);
|
||||
};
|
||||
|
||||
const deleteRole = async (id: string) => {
|
||||
const res = await request(`/roles/${id}/delete`, {
|
||||
method: "DELETE",
|
||||
requiresAuth: true,
|
||||
});
|
||||
if (res.status === "Success") rolesMutate();
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="container mx-auto p-4 space-y-6">
|
||||
<div className="flex justify-between items-center">
|
||||
<h1 className="text-2xl font-bold">Rôles et Permissions</h1>
|
||||
{hasPermissions(user.roles, { roles: ["insert"] }) && (
|
||||
<Dialog open={isDialogOpen} onOpenChange={setIsDialogOpen}>
|
||||
<DialogTrigger asChild>
|
||||
<Button>
|
||||
<Plus className="mr-2 h-4 w-4" /> Nouveau rôle
|
||||
</Button>
|
||||
</DialogTrigger>
|
||||
<DialogContent>
|
||||
<DialogHeader>
|
||||
<DialogTitle>Nouveau rôle</DialogTitle>
|
||||
</DialogHeader>
|
||||
<div className="py-4">
|
||||
<Input
|
||||
placeholder="Nom du rôle"
|
||||
value={newRoleName}
|
||||
onChange={(e) =>
|
||||
setNewRoleName(e.target.value)
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
<DialogFooter>
|
||||
<Button
|
||||
onClick={addNewRole}
|
||||
disabled={newRoleName.trim() === ""}
|
||||
>
|
||||
Ajouter
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
)}
|
||||
</div>
|
||||
{permissions &&
|
||||
roles &&
|
||||
roles.map((role, index) => (
|
||||
<RoleCard
|
||||
user={user}
|
||||
key={index}
|
||||
role={role}
|
||||
permissions={permissions}
|
||||
onDelete={() => deleteRole(role.id)}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
interface RoleCardProps {
|
||||
user: IUser;
|
||||
role: Role;
|
||||
onDelete: () => void;
|
||||
permissions: PermissionsGrouped;
|
||||
}
|
||||
|
||||
function RoleCard({ role, onDelete, permissions, user }: RoleCardProps) {
|
||||
return (
|
||||
<Card>
|
||||
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
|
||||
<CardTitle>{toTitleCase(role.name)}</CardTitle>
|
||||
<Button
|
||||
disabled={
|
||||
!hasPermissions(user.roles, { roles: ["delete"] })
|
||||
}
|
||||
variant="destructive"
|
||||
size="icon"
|
||||
onClick={onDelete}
|
||||
>
|
||||
<Trash2 className="h-4 w-4" />
|
||||
</Button>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
{Object.entries(permissions).map(([res, actions]) => {
|
||||
return (
|
||||
<ResourceSection
|
||||
disabled={
|
||||
!hasPermissions(user.roles, {
|
||||
permissions: ["update"],
|
||||
roles: ["update"],
|
||||
})
|
||||
}
|
||||
key={res}
|
||||
resource={res}
|
||||
defaultActions={actions}
|
||||
role={role}
|
||||
/>
|
||||
);
|
||||
})}
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
interface ResourceSectionProps {
|
||||
disabled?: boolean;
|
||||
resource: string;
|
||||
defaultActions: string[];
|
||||
role: Role;
|
||||
}
|
||||
|
||||
function ResourceSection({
|
||||
resource,
|
||||
defaultActions,
|
||||
role,
|
||||
disabled = false,
|
||||
}: ResourceSectionProps) {
|
||||
const [isExpanded, setIsExpanded] = useState<boolean>(false);
|
||||
|
||||
const a = (role.permissions ?? [])
|
||||
.map((p) => (p.resource === resource ? p.action : null))
|
||||
.filter((a) => a !== null);
|
||||
|
||||
const ActionCheckbox = ({ action }: { action: Action }) => {
|
||||
const [checked, setChecked] = useState(a.includes(action));
|
||||
return (
|
||||
<div key={action} className="flex items-center space-x-2">
|
||||
<Checkbox
|
||||
disabled={disabled}
|
||||
onCheckedChange={async (e) => {
|
||||
if (typeof e === "boolean") {
|
||||
const res = await request(
|
||||
`/roles/${role.id}/permissions/${resource}/${action}/${e ? "add" : "remove"}`,
|
||||
{ method: "PATCH", requiresAuth: true },
|
||||
);
|
||||
if (res.status === "Success") setChecked(e);
|
||||
}
|
||||
}}
|
||||
checked={checked}
|
||||
id={`${resource}-${action}`}
|
||||
/>
|
||||
<label
|
||||
htmlFor={`${resource}-${action}`}
|
||||
className="text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"
|
||||
>
|
||||
{action}
|
||||
</label>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="mb-4">
|
||||
<button
|
||||
className="flex items-center text-lg font-semibold mb-2"
|
||||
onClick={() => setIsExpanded(!isExpanded)}
|
||||
>
|
||||
{isExpanded ? (
|
||||
<ChevronDown className="mr-2" />
|
||||
) : (
|
||||
<ChevronRight className="mr-2" />
|
||||
)}
|
||||
{toTitleCase(resource)}
|
||||
</button>
|
||||
{isExpanded && (
|
||||
<div className="grid grid-cols-2 sm:grid-cols-4 gap-2 ml-6">
|
||||
{defaultActions.map((action) => (
|
||||
<ActionCheckbox
|
||||
key={`${resource}:${action}`}
|
||||
action={action}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,223 +1,21 @@
|
||||
"use client";
|
||||
import getMe from "@/lib/getMe";
|
||||
import hasPermissions from "@/lib/hasPermissions";
|
||||
import { redirect } from "next/navigation";
|
||||
import RolesAndPermissions from "./_roles";
|
||||
|
||||
import { useState } from "react";
|
||||
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
|
||||
import { Checkbox } from "@/components/ui/checkbox";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
DialogTrigger,
|
||||
DialogFooter,
|
||||
} from "@/components/ui/dialog";
|
||||
import { ChevronDown, ChevronRight, Plus, Trash2 } from "lucide-react";
|
||||
import { toTitleCase } from "@/lib/utils";
|
||||
import { useApi } from "@/hooks/use-api";
|
||||
import request from "@/lib/request";
|
||||
export default async function Page() {
|
||||
const me = await getMe();
|
||||
if (
|
||||
!me ||
|
||||
me.status === "Error" ||
|
||||
!me.data ||
|
||||
!hasPermissions(me.data.roles, {
|
||||
roles: ["get"],
|
||||
permissions: ["get"],
|
||||
})
|
||||
) {
|
||||
redirect("/dashboard");
|
||||
}
|
||||
|
||||
type Action = string;
|
||||
|
||||
interface Permission {
|
||||
resource: string;
|
||||
action: Action;
|
||||
}
|
||||
|
||||
interface Role {
|
||||
id: string;
|
||||
name: string;
|
||||
permissions?: Permission[];
|
||||
}
|
||||
|
||||
interface PermissionsGrouped {
|
||||
[key: string]: string[];
|
||||
}
|
||||
|
||||
export default function RolesAndPermissions() {
|
||||
const [newRoleName, setNewRoleName] = useState<string>("");
|
||||
const [isDialogOpen, setIsDialogOpen] = useState<boolean>(false);
|
||||
|
||||
const { data: permissions } = useApi<PermissionsGrouped>(
|
||||
"/permissions/grouped",
|
||||
{},
|
||||
true,
|
||||
);
|
||||
|
||||
const { data: roles, mutate: rolesMutate } = useApi<Role[]>(
|
||||
"/roles",
|
||||
{},
|
||||
true,
|
||||
);
|
||||
|
||||
const addNewRole = async () => {
|
||||
if (newRoleName.trim() === "") return;
|
||||
|
||||
const res = await request("/roles/new", {
|
||||
requiresAuth: true,
|
||||
method: "POST",
|
||||
body: { name: newRoleName },
|
||||
});
|
||||
|
||||
if (res.status === "Success") rolesMutate();
|
||||
|
||||
setNewRoleName("");
|
||||
setIsDialogOpen(false);
|
||||
};
|
||||
|
||||
const deleteRole = async (id: string) => {
|
||||
const res = await request(`/roles/${id}/delete`, {
|
||||
method: "DELETE",
|
||||
requiresAuth: true,
|
||||
});
|
||||
if (res.status === "Success") rolesMutate();
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="container mx-auto p-4 space-y-6">
|
||||
<div className="flex justify-between items-center">
|
||||
<h1 className="text-2xl font-bold">Rôles et Permissions</h1>
|
||||
<Dialog open={isDialogOpen} onOpenChange={setIsDialogOpen}>
|
||||
<DialogTrigger asChild>
|
||||
<Button>
|
||||
<Plus className="mr-2 h-4 w-4" /> Nouveau rôle
|
||||
</Button>
|
||||
</DialogTrigger>
|
||||
<DialogContent>
|
||||
<DialogHeader>
|
||||
<DialogTitle>Nouveau rôle</DialogTitle>
|
||||
</DialogHeader>
|
||||
<div className="py-4">
|
||||
<Input
|
||||
placeholder="Nom du rôle"
|
||||
value={newRoleName}
|
||||
onChange={(e) => setNewRoleName(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
<DialogFooter>
|
||||
<Button
|
||||
onClick={addNewRole}
|
||||
disabled={newRoleName.trim() === ""}
|
||||
>
|
||||
Ajouter
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</div>
|
||||
{permissions &&
|
||||
roles &&
|
||||
roles.map((role, index) => (
|
||||
<RoleCard
|
||||
key={index}
|
||||
role={role}
|
||||
permissions={permissions}
|
||||
onDelete={() => deleteRole(role.id)}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
interface RoleCardProps {
|
||||
role: Role;
|
||||
onDelete: () => void;
|
||||
permissions: PermissionsGrouped;
|
||||
}
|
||||
|
||||
function RoleCard({ role, onDelete, permissions }: RoleCardProps) {
|
||||
return (
|
||||
<Card>
|
||||
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
|
||||
<CardTitle>{toTitleCase(role.name)}</CardTitle>
|
||||
<Button variant="destructive" size="icon" onClick={onDelete}>
|
||||
<Trash2 className="h-4 w-4" />
|
||||
</Button>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
{Object.entries(permissions).map(([res, actions]) => {
|
||||
return (
|
||||
<ResourceSection
|
||||
key={res}
|
||||
resource={res}
|
||||
defaultActions={actions}
|
||||
role={role}
|
||||
/>
|
||||
);
|
||||
})}
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
interface ResourceSectionProps {
|
||||
resource: string;
|
||||
defaultActions: string[];
|
||||
role: Role;
|
||||
}
|
||||
|
||||
function ResourceSection({
|
||||
resource,
|
||||
defaultActions,
|
||||
role,
|
||||
}: ResourceSectionProps) {
|
||||
const [isExpanded, setIsExpanded] = useState<boolean>(false);
|
||||
|
||||
const a = (role.permissions ?? [])
|
||||
.map((p) => (p.resource === resource ? p.action : null))
|
||||
.filter((a) => a !== null);
|
||||
|
||||
const ActionCheckbox = ({ action }: { action: Action }) => {
|
||||
const [checked, setChecked] = useState(a.includes(action));
|
||||
return (
|
||||
<div key={action} className="flex items-center space-x-2">
|
||||
<Checkbox
|
||||
onCheckedChange={async (e) => {
|
||||
if (typeof e === "boolean") {
|
||||
const res = await request(
|
||||
`/roles/${role.id}/permissions/${resource}/${action}/${e ? "add" : "remove"}`,
|
||||
{ method: "PATCH", requiresAuth: true },
|
||||
);
|
||||
if (res.status === "Success") setChecked(e);
|
||||
}
|
||||
}}
|
||||
checked={checked}
|
||||
id={`${resource}-${action}`}
|
||||
/>
|
||||
<label
|
||||
htmlFor={`${resource}-${action}`}
|
||||
className="text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"
|
||||
>
|
||||
{action}
|
||||
</label>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="mb-4">
|
||||
<button
|
||||
className="flex items-center text-lg font-semibold mb-2"
|
||||
onClick={() => setIsExpanded(!isExpanded)}
|
||||
>
|
||||
{isExpanded ? (
|
||||
<ChevronDown className="mr-2" />
|
||||
) : (
|
||||
<ChevronRight className="mr-2" />
|
||||
)}
|
||||
{toTitleCase(resource)}
|
||||
</button>
|
||||
{isExpanded && (
|
||||
<div className="grid grid-cols-2 sm:grid-cols-4 gap-2 ml-6">
|
||||
{defaultActions.map((action) => (
|
||||
<ActionCheckbox
|
||||
key={`${resource}:${action}`}
|
||||
action={action}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
return <RolesAndPermissions user={me.data} />;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,70 @@
|
||||
"use client";
|
||||
|
||||
import { useState } from "react";
|
||||
import { ShortcodeTable } from "@/components/shortcodes-table";
|
||||
import type IShortcode from "@/interfaces/IShortcode";
|
||||
import { useApi } from "@/hooks/use-api";
|
||||
import request from "@/lib/request";
|
||||
import { Loader2 } from "lucide-react";
|
||||
import IUser from "@/interfaces/IUser";
|
||||
|
||||
export default function ShortcodesPage({ user }: { user: IUser }) {
|
||||
const {
|
||||
data: shortcodes,
|
||||
error,
|
||||
isLoading,
|
||||
mutate,
|
||||
success,
|
||||
} = useApi<IShortcode[]>("/shortcodes", undefined, true);
|
||||
|
||||
console.log(shortcodes);
|
||||
|
||||
const handleUpdate = async (updatedShortcode: IShortcode) => {
|
||||
const res = await request<IShortcode>(
|
||||
`/shortcodes/${updatedShortcode.code}/update`,
|
||||
{
|
||||
method: "PATCH",
|
||||
requiresAuth: true,
|
||||
body: updatedShortcode,
|
||||
},
|
||||
);
|
||||
mutate();
|
||||
// Implement update logic here
|
||||
console.log("Update shortcode:", updatedShortcode);
|
||||
};
|
||||
|
||||
const handleDelete = async (code: string) => {
|
||||
const res = await request<undefined>(`/shortcodes/${code}/delete`, {
|
||||
requiresAuth: true,
|
||||
method: "DELETE",
|
||||
});
|
||||
mutate();
|
||||
};
|
||||
|
||||
const handleAdd = async (newShortcode: Omit<IShortcode, "id">) => {
|
||||
const res = await request<IShortcode>(`/shortcodes/new`, {
|
||||
body: newShortcode,
|
||||
method: "POST",
|
||||
requiresAuth: true,
|
||||
});
|
||||
console.log(res);
|
||||
mutate();
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="container mx-auto px-4 py-10">
|
||||
<h1 className="text-2xl font-bold mb-5">Shortcodes</h1>
|
||||
{isLoading && (
|
||||
<Loader2 className="flex w-full min-w-0 flex-col gap-1 justify-center animate-spin" />
|
||||
)}
|
||||
{error && <p>{error}</p>}
|
||||
<ShortcodeTable
|
||||
user={user}
|
||||
shortcodes={shortcodes ?? []}
|
||||
onUpdate={handleUpdate}
|
||||
onDelete={handleDelete}
|
||||
onAdd={handleAdd}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,68 +1,20 @@
|
||||
"use client";
|
||||
import getMe from "@/lib/getMe";
|
||||
import hasPermissions from "@/lib/hasPermissions";
|
||||
import { redirect } from "next/navigation";
|
||||
import ShortcodesPage from "./_shortcodes";
|
||||
|
||||
import { useState } from "react";
|
||||
import { ShortcodeTable } from "@/components/shortcodes-table";
|
||||
import type IShortcode from "@/interfaces/IShortcode";
|
||||
import { useApi } from "@/hooks/use-api";
|
||||
import request from "@/lib/request";
|
||||
import { Loader2 } from "lucide-react";
|
||||
export default async function Page() {
|
||||
const me = await getMe();
|
||||
if (
|
||||
!me ||
|
||||
me.status === "Error" ||
|
||||
!me.data ||
|
||||
!hasPermissions(me.data.roles, {
|
||||
shortcodes: ["get"],
|
||||
})
|
||||
) {
|
||||
redirect("/dashboard");
|
||||
}
|
||||
|
||||
export default function ShortcodesPage() {
|
||||
const {
|
||||
data: shortcodes,
|
||||
error,
|
||||
isLoading,
|
||||
mutate,
|
||||
success,
|
||||
} = useApi<IShortcode[]>("/shortcodes", undefined, true);
|
||||
|
||||
console.log(shortcodes);
|
||||
|
||||
const handleUpdate = async (updatedShortcode: IShortcode) => {
|
||||
const res = await request<IShortcode>(
|
||||
`/shortcodes/${updatedShortcode.code}/update`,
|
||||
{
|
||||
method: "PATCH",
|
||||
requiresAuth: true,
|
||||
body: updatedShortcode,
|
||||
},
|
||||
);
|
||||
mutate();
|
||||
// Implement update logic here
|
||||
console.log("Update shortcode:", updatedShortcode);
|
||||
};
|
||||
|
||||
const handleDelete = async (code: string) => {
|
||||
const res = await request<undefined>(`/shortcodes/${code}/delete`, {
|
||||
requiresAuth: true,
|
||||
method: "DELETE",
|
||||
});
|
||||
mutate();
|
||||
};
|
||||
|
||||
const handleAdd = async (newShortcode: Omit<IShortcode, "id">) => {
|
||||
const res = await request<IShortcode>(`/shortcodes/new`, {
|
||||
body: newShortcode,
|
||||
method: "POST",
|
||||
requiresAuth: true,
|
||||
});
|
||||
console.log(res);
|
||||
mutate();
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="container mx-auto px-4 py-10">
|
||||
<h1 className="text-2xl font-bold mb-5">Shortcodes</h1>
|
||||
{isLoading && (
|
||||
<Loader2 className="flex w-full min-w-0 flex-col gap-1 justify-center animate-spin" />
|
||||
)}
|
||||
{error && <p>{error}</p>}
|
||||
<ShortcodeTable
|
||||
shortcodes={shortcodes ?? []}
|
||||
onUpdate={handleUpdate}
|
||||
onDelete={handleDelete}
|
||||
onAdd={handleAdd}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
return <ShortcodesPage user={me.data} />;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user