mirror of
https://github.com/prowler-cloud/prowler.git
synced 2026-07-21 03:21:56 +00:00
chore: add role column to the table users
This commit is contained in:
@@ -14,10 +14,10 @@ export const getUsers = async ({
|
||||
}) => {
|
||||
const session = await auth();
|
||||
|
||||
if (isNaN(Number(page)) || page < 1) redirect("/users");
|
||||
if (isNaN(Number(page)) || page < 1) redirect("/users?include=roles");
|
||||
|
||||
const keyServer = process.env.API_BASE_URL;
|
||||
const url = new URL(`${keyServer}/users`);
|
||||
const url = new URL(`${keyServer}/users?include=roles`);
|
||||
|
||||
if (page) url.searchParams.append("page[number]", page.toString());
|
||||
if (query) url.searchParams.append("filter[search]", query);
|
||||
@@ -94,6 +94,58 @@ export const updateUser = async (formData: FormData) => {
|
||||
revalidatePath("/users");
|
||||
return parseStringify(data);
|
||||
} catch (error) {
|
||||
// eslint-disable-next-line no-console
|
||||
console.error(error);
|
||||
return {
|
||||
error: getErrorMessage(error),
|
||||
};
|
||||
}
|
||||
};
|
||||
|
||||
export const updateUserRole = async (formData: FormData) => {
|
||||
const session = await auth();
|
||||
const keyServer = process.env.API_BASE_URL;
|
||||
|
||||
const userId = formData.get("userId") as string;
|
||||
const roleId = formData.get("roleId") as string;
|
||||
|
||||
// Validate required fields
|
||||
if (!userId || !roleId) {
|
||||
return { error: "userId and roleId are required" };
|
||||
}
|
||||
|
||||
const url = new URL(`${keyServer}/users/${userId}/relationships/roles`);
|
||||
|
||||
const requestBody = {
|
||||
data: [
|
||||
{
|
||||
type: "role",
|
||||
id: roleId,
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
try {
|
||||
const response = await fetch(url.toString(), {
|
||||
method: "PATCH",
|
||||
headers: {
|
||||
"Content-Type": "application/vnd.api+json",
|
||||
Accept: "application/vnd.api+json",
|
||||
Authorization: `Bearer ${session?.accessToken}`,
|
||||
},
|
||||
body: JSON.stringify(requestBody),
|
||||
});
|
||||
|
||||
const data = await response.json();
|
||||
|
||||
if (!response.ok) {
|
||||
return { error: data.errors || "An error occurred" };
|
||||
}
|
||||
|
||||
revalidatePath("/users"); // Update the path as needed
|
||||
return parseStringify(data);
|
||||
} catch (error) {
|
||||
// eslint-disable-next-line no-console
|
||||
console.error(error);
|
||||
return {
|
||||
error: getErrorMessage(error),
|
||||
|
||||
@@ -60,7 +60,7 @@ const SSRDataTable = async ({
|
||||
const rolesData = await getRoles({});
|
||||
|
||||
// Create a dictionary for roles by invitation ID
|
||||
const roleDict = rolesData?.data?.reduce(
|
||||
const roleDict = (rolesData?.data || []).reduce(
|
||||
(acc: Record<string, Role>, role: Role) => {
|
||||
role.relationships.invitations.data.forEach((invitation: any) => {
|
||||
acc[invitation.id] = role;
|
||||
@@ -73,7 +73,7 @@ const SSRDataTable = async ({
|
||||
// Generate the array of roles with all the roles available
|
||||
const roles = Array.from(
|
||||
new Map(
|
||||
rolesData.data.map((role: any) => [
|
||||
(rolesData?.data || []).map((role: Role) => [
|
||||
role.id,
|
||||
{ id: role.id, name: role.attributes?.name || "Unnamed Role" },
|
||||
]),
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { Spacer } from "@nextui-org/react";
|
||||
import { Suspense } from "react";
|
||||
|
||||
import { getRoles } from "@/actions/roles";
|
||||
import { getUsers } from "@/actions/users/users";
|
||||
import { FilterControls } from "@/components/filters";
|
||||
import { filterUsers } from "@/components/filters/data-filters";
|
||||
@@ -8,7 +9,7 @@ import { Header } from "@/components/ui";
|
||||
import { DataTable, DataTableFilterCustom } from "@/components/ui/table";
|
||||
import { AddUserButton } from "@/components/users";
|
||||
import { ColumnsUser, SkeletonTableUser } from "@/components/users/table";
|
||||
import { SearchParamsProps } from "@/types";
|
||||
import { Role, SearchParamsProps, UserProps } from "@/types";
|
||||
|
||||
export default async function Users({
|
||||
searchParams,
|
||||
@@ -52,11 +53,49 @@ const SSRDataTable = async ({
|
||||
const query = (filters["filter[search]"] as string) || "";
|
||||
|
||||
const usersData = await getUsers({ query, page, sort, filters });
|
||||
const rolesData = await getRoles({});
|
||||
|
||||
// Create a dictionary for roles by user ID
|
||||
const roleDict = (usersData?.included || []).reduce(
|
||||
(acc: Record<string, any>, item: Role) => {
|
||||
if (item.type === "role") {
|
||||
acc[item.id] = item.attributes;
|
||||
}
|
||||
return acc;
|
||||
},
|
||||
{} as Record<string, Role>,
|
||||
);
|
||||
|
||||
// Generate the array of roles with all the roles available
|
||||
const roles = Array.from(
|
||||
new Map(
|
||||
(rolesData?.data || []).map((role: Role) => [
|
||||
role.id,
|
||||
{ id: role.id, name: role.attributes?.name || "Unnamed Role" },
|
||||
]),
|
||||
).values(),
|
||||
);
|
||||
|
||||
// Expand the users with their roles
|
||||
const expandedUsers = (usersData?.data || []).map((user: UserProps) => {
|
||||
// Check if the user has a role
|
||||
const roleId = user?.relationships?.roles?.data?.[0]?.id;
|
||||
const role = roleDict?.[roleId] || null;
|
||||
|
||||
return {
|
||||
...user,
|
||||
attributes: {
|
||||
...(user?.attributes || {}),
|
||||
role,
|
||||
},
|
||||
roles,
|
||||
};
|
||||
});
|
||||
|
||||
return (
|
||||
<DataTable
|
||||
columns={ColumnsUser}
|
||||
data={usersData?.data || []}
|
||||
data={expandedUsers || []}
|
||||
metadata={usersData?.meta}
|
||||
/>
|
||||
);
|
||||
|
||||
@@ -40,7 +40,6 @@ export const EditForm = ({
|
||||
const isLoading = form.formState.isSubmitting;
|
||||
|
||||
const onSubmitClient = async (values: z.infer<typeof formSchema>) => {
|
||||
console.log(values, " from edit form");
|
||||
const formData = new FormData();
|
||||
|
||||
Object.entries(values).forEach(
|
||||
|
||||
@@ -127,7 +127,7 @@ export const ColumnGetScans: ColumnDef<ScanProps>[] = [
|
||||
header: ({ column }) => (
|
||||
<DataTableColumnHeader
|
||||
column={column}
|
||||
title={"Next execution"}
|
||||
title={"Next scan"}
|
||||
param="next_scan_at"
|
||||
/>
|
||||
),
|
||||
|
||||
@@ -80,20 +80,10 @@ export const DataTableColumnHeader = <TData, TValue>({
|
||||
|
||||
return (
|
||||
<Button
|
||||
className="h-10 w-fit max-w-[110px] whitespace-nowrap bg-transparent px-0 text-left align-middle text-tiny font-semibold text-foreground-500 outline-none dark:text-slate-400"
|
||||
className="flex h-10 w-full items-center justify-between whitespace-nowrap bg-transparent px-0 text-left align-middle text-tiny font-semibold text-foreground-500 outline-none dark:text-slate-400"
|
||||
onClick={getToggleSortingHandler}
|
||||
>
|
||||
<span
|
||||
className="block whitespace-normal break-normal"
|
||||
style={{
|
||||
display: "-webkit-box",
|
||||
WebkitBoxOrient: "vertical",
|
||||
WebkitLineClamp: 2,
|
||||
width: "90px",
|
||||
}}
|
||||
>
|
||||
{title}
|
||||
</span>
|
||||
<span className="block whitespace-normal break-normal">{title}</span>
|
||||
{renderSortIcon()}
|
||||
</Button>
|
||||
);
|
||||
|
||||
@@ -1,11 +1,13 @@
|
||||
"use client";
|
||||
|
||||
import { zodResolver } from "@hookform/resolvers/zod";
|
||||
import { Select, SelectItem } from "@nextui-org/react";
|
||||
import { ShieldIcon, UserIcon } from "lucide-react";
|
||||
import { Dispatch, SetStateAction } from "react";
|
||||
import { useForm } from "react-hook-form";
|
||||
import { Controller, useForm } from "react-hook-form";
|
||||
import * as z from "zod";
|
||||
|
||||
import { updateUser } from "@/actions/users/users";
|
||||
import { updateUser, updateUserRole } from "@/actions/users/users";
|
||||
import { SaveIcon } from "@/components/icons";
|
||||
import { useToast } from "@/components/ui";
|
||||
import { CustomButton, CustomInput } from "@/components/ui/custom";
|
||||
@@ -17,12 +19,16 @@ export const EditForm = ({
|
||||
userName,
|
||||
userEmail,
|
||||
userCompanyName,
|
||||
roles = [],
|
||||
currentRole = "",
|
||||
setIsOpen,
|
||||
}: {
|
||||
userId: string;
|
||||
userName?: string;
|
||||
userEmail?: string;
|
||||
userCompanyName?: string;
|
||||
roles: Array<{ id: string; name: string }>;
|
||||
currentRole?: string;
|
||||
setIsOpen: Dispatch<SetStateAction<boolean>>;
|
||||
}) => {
|
||||
const formSchema = editUserFormSchema();
|
||||
@@ -34,6 +40,7 @@ export const EditForm = ({
|
||||
name: userName,
|
||||
email: userEmail,
|
||||
company_name: userCompanyName,
|
||||
role: roles.find((role) => role.name === currentRole)?.id || "",
|
||||
},
|
||||
});
|
||||
|
||||
@@ -44,7 +51,7 @@ export const EditForm = ({
|
||||
const onSubmitClient = async (values: z.infer<typeof formSchema>) => {
|
||||
const formData = new FormData();
|
||||
|
||||
// Check if the value is not undefined before appending to FormData
|
||||
// Update basic user data
|
||||
if (values.name !== undefined) {
|
||||
formData.append("name", values.name);
|
||||
}
|
||||
@@ -58,6 +65,26 @@ export const EditForm = ({
|
||||
// Always include userId
|
||||
formData.append("userId", userId);
|
||||
|
||||
// Handle role updates separately
|
||||
if (values.role !== roles.find((role) => role.name === currentRole)?.id) {
|
||||
const roleFormData = new FormData();
|
||||
roleFormData.append("userId", userId);
|
||||
roleFormData.append("roleId", values.role || "");
|
||||
|
||||
const roleUpdateResponse = await updateUserRole(roleFormData);
|
||||
|
||||
if (roleUpdateResponse?.errors && roleUpdateResponse.errors.length > 0) {
|
||||
const error = roleUpdateResponse.errors[0];
|
||||
toast({
|
||||
variant: "destructive",
|
||||
title: "Role Update Failed",
|
||||
description: `${error.detail}`,
|
||||
});
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
// Update other user attributes
|
||||
const data = await updateUser(formData);
|
||||
|
||||
if (data?.errors && data.errors.length > 0) {
|
||||
@@ -84,22 +111,49 @@ export const EditForm = ({
|
||||
onSubmit={form.handleSubmit(onSubmitClient)}
|
||||
className="flex flex-col space-y-4"
|
||||
>
|
||||
<div className="text-md">
|
||||
Current name: <span className="font-bold">{userName}</span>
|
||||
<div className="flex flex-row justify-center space-x-4 rounded-lg bg-gray-50 p-3">
|
||||
<div className="flex items-center text-small text-gray-600">
|
||||
<UserIcon className="mr-2 h-4 w-4" />
|
||||
<span className="text-gray-500">Name:</span>
|
||||
<span className="ml-2 font-semibold text-gray-900">{userName}</span>
|
||||
</div>
|
||||
<div className="flex items-center text-small text-gray-600">
|
||||
<ShieldIcon className="mr-2 h-4 w-4" />
|
||||
<span className="text-gray-500">Role:</span>
|
||||
<span className="ml-2 font-semibold text-gray-900">
|
||||
{currentRole}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
<div>
|
||||
<CustomInput
|
||||
control={form.control}
|
||||
name="name"
|
||||
type="text"
|
||||
label="Name"
|
||||
labelPlacement="outside"
|
||||
placeholder={userName}
|
||||
variant="bordered"
|
||||
isRequired={false}
|
||||
isInvalid={!!form.formState.errors.name}
|
||||
/>
|
||||
<div className="flex flex-row gap-4">
|
||||
<div className="w-1/2">
|
||||
<CustomInput
|
||||
control={form.control}
|
||||
name="name"
|
||||
type="text"
|
||||
label="Name"
|
||||
labelPlacement="outside"
|
||||
placeholder={userName}
|
||||
variant="bordered"
|
||||
isRequired={false}
|
||||
isInvalid={!!form.formState.errors.name}
|
||||
/>
|
||||
</div>
|
||||
<div className="w-1/2">
|
||||
<CustomInput
|
||||
control={form.control}
|
||||
name="company_name"
|
||||
type="text"
|
||||
label="Company Name"
|
||||
labelPlacement="outside"
|
||||
placeholder={userCompanyName}
|
||||
variant="bordered"
|
||||
isRequired={false}
|
||||
isInvalid={!!form.formState.errors.company_name}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<CustomInput
|
||||
control={form.control}
|
||||
@@ -113,18 +167,36 @@ export const EditForm = ({
|
||||
isInvalid={!!form.formState.errors.email}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<CustomInput
|
||||
<Controller
|
||||
name="role"
|
||||
control={form.control}
|
||||
name="company_name"
|
||||
type="text"
|
||||
label="Company Name"
|
||||
labelPlacement="outside"
|
||||
placeholder={userCompanyName}
|
||||
variant="bordered"
|
||||
isRequired={false}
|
||||
isInvalid={!!form.formState.errors.company_name}
|
||||
render={({ field }) => (
|
||||
<Select
|
||||
{...field}
|
||||
label="Role"
|
||||
labelPlacement="outside"
|
||||
placeholder="Select a role"
|
||||
variant="bordered"
|
||||
selectedKeys={[field.value || ""]}
|
||||
onSelectionChange={(selected) => {
|
||||
const selectedKey = Array.from(selected).pop();
|
||||
field.onChange(selectedKey || "");
|
||||
}}
|
||||
>
|
||||
{roles.map((role: { id: string; name: string }) => (
|
||||
<SelectItem key={role.id}>{role.name}</SelectItem>
|
||||
))}
|
||||
</Select>
|
||||
)}
|
||||
/>
|
||||
|
||||
{form.formState.errors.role && (
|
||||
<p className="mt-2 text-sm text-red-600">
|
||||
{form.formState.errors.role.message}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
<input type="hidden" name="userId" value={userId} />
|
||||
|
||||
|
||||
@@ -33,6 +33,14 @@ export const ColumnsUser: ColumnDef<UserProps>[] = [
|
||||
return <p className="font-semibold">{email}</p>;
|
||||
},
|
||||
},
|
||||
{
|
||||
accessorKey: "role",
|
||||
header: () => <div className="text-left">Role</div>,
|
||||
cell: ({ row }) => {
|
||||
const { role } = getUserData(row);
|
||||
return <p className="font-semibold">{role?.name || "No Role"}</p>;
|
||||
},
|
||||
},
|
||||
{
|
||||
accessorKey: "company_name",
|
||||
header: ({ column }) => (
|
||||
@@ -47,7 +55,6 @@ export const ColumnsUser: ColumnDef<UserProps>[] = [
|
||||
return <p className="font-semibold">{company_name}</p>;
|
||||
},
|
||||
},
|
||||
|
||||
{
|
||||
accessorKey: "date_joined",
|
||||
header: ({ column }) => (
|
||||
@@ -68,7 +75,8 @@ export const ColumnsUser: ColumnDef<UserProps>[] = [
|
||||
header: () => <div className="text-right">Actions</div>,
|
||||
id: "actions",
|
||||
cell: ({ row }) => {
|
||||
return <DataTableRowActions row={row} />;
|
||||
const roles = row.original.roles;
|
||||
return <DataTableRowActions row={row} roles={roles} />;
|
||||
},
|
||||
},
|
||||
];
|
||||
|
||||
@@ -21,34 +21,39 @@ import { CustomAlertModal } from "@/components/ui/custom";
|
||||
|
||||
import { DeleteForm, EditForm } from "../forms";
|
||||
|
||||
interface DataTableRowActionsProps<ProviderProps> {
|
||||
row: Row<ProviderProps>;
|
||||
interface DataTableRowActionsProps<UserProps> {
|
||||
row: Row<UserProps>;
|
||||
roles?: { id: string; name: string }[];
|
||||
}
|
||||
const iconClasses =
|
||||
"text-2xl text-default-500 pointer-events-none flex-shrink-0";
|
||||
|
||||
export function DataTableRowActions<ProviderProps>({
|
||||
export function DataTableRowActions<UserProps>({
|
||||
row,
|
||||
}: DataTableRowActionsProps<ProviderProps>) {
|
||||
roles,
|
||||
}: DataTableRowActionsProps<UserProps>) {
|
||||
const [isEditOpen, setIsEditOpen] = useState(false);
|
||||
const [isDeleteOpen, setIsDeleteOpen] = useState(false);
|
||||
const userId = (row.original as { id: string }).id;
|
||||
const userName = (row.original as any).attributes?.name;
|
||||
const userEmail = (row.original as any).attributes?.email;
|
||||
const userCompanyName = (row.original as any).attributes?.company_name;
|
||||
const userRole = (row.original as any).attributes?.role?.name;
|
||||
|
||||
return (
|
||||
<>
|
||||
<CustomAlertModal
|
||||
isOpen={isEditOpen}
|
||||
onOpenChange={setIsEditOpen}
|
||||
title="Edit user"
|
||||
description={"Edit the user details"}
|
||||
title="Edit user details"
|
||||
>
|
||||
<EditForm
|
||||
userId={userId}
|
||||
userName={userName}
|
||||
userEmail={userEmail}
|
||||
userCompanyName={userCompanyName}
|
||||
currentRole={userRole}
|
||||
roles={roles || []}
|
||||
setIsOpen={setIsEditOpen}
|
||||
/>
|
||||
</CustomAlertModal>
|
||||
|
||||
@@ -325,6 +325,9 @@ export interface UserProfileProps {
|
||||
email: string;
|
||||
company_name: string;
|
||||
date_joined: string;
|
||||
role: {
|
||||
name: string;
|
||||
};
|
||||
};
|
||||
relationships: {
|
||||
memberships: {
|
||||
@@ -351,6 +354,9 @@ export interface UserProps {
|
||||
email: string;
|
||||
company_name: string;
|
||||
date_joined: string;
|
||||
role: {
|
||||
name: string;
|
||||
};
|
||||
};
|
||||
relationships: {
|
||||
memberships: {
|
||||
@@ -362,7 +368,20 @@ export interface UserProps {
|
||||
id: string;
|
||||
}>;
|
||||
};
|
||||
roles: {
|
||||
meta: {
|
||||
count: number;
|
||||
};
|
||||
data: Array<{
|
||||
type: "role";
|
||||
id: string;
|
||||
}>;
|
||||
};
|
||||
};
|
||||
roles: {
|
||||
id: string;
|
||||
name: string;
|
||||
}[];
|
||||
}
|
||||
|
||||
export interface ProviderProps {
|
||||
|
||||
@@ -200,4 +200,5 @@ export const editUserFormSchema = () =>
|
||||
.optional(),
|
||||
company_name: z.string().optional(),
|
||||
userId: z.string(),
|
||||
role: z.string().optional(),
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user