Started implementing the roles permissions

This commit is contained in:
Tiago Ribeiro
2024-10-10 19:13:18 +01:00
parent c43ab9a911
commit 55204e2ce1
67 changed files with 1357 additions and 1134 deletions

View File

@@ -0,0 +1,326 @@
import Layout from "@/components/High/Layout";
import Checkbox from "@/components/Low/Checkbox";
import Separator from "@/components/Low/Separator";
import { useEntityPermission } from "@/hooks/useEntityPermissions";
import {EntityWithRoles, Role} from "@/interfaces/entity";
import {User} from "@/interfaces/user";
import {sessionOptions} from "@/lib/session";
import { RolePermission } from "@/resources/entityPermissions";
import { findBy, mapBy, redirect, serialize } from "@/utils";
import { requestUser } from "@/utils/api";
import {getEntityWithRoles} from "@/utils/entities.be";
import {shouldRedirectHome} from "@/utils/navigation.disabled";
import {doesEntityAllow} from "@/utils/permissions";
import {countEntityUsers} from "@/utils/users.be";
import axios from "axios";
import {withIronSessionSsr} from "iron-session/next";
import Head from "next/head";
import Link from "next/link";
import {useRouter} from "next/router";
import {Divider} from "primereact/divider";
import {useState} from "react";
import {
BsCheck,
BsChevronLeft,
BsTag,
BsTrash,
} from "react-icons/bs";
import {toast} from "react-toastify";
type PermissionLayout = {label: string, key: RolePermission}
const USER_MANAGEMENT: PermissionLayout[] = [
{label: "View Students", key: "view_students"},
{label: "View Teachers", key: "view_teachers"},
{label: "View Corporate Accounts", key: "view_corporates"},
{label: "View Master Corporate Accounts", key: "view_mastercorporates"},
{label: "Edit Students", key: "edit_students"},
{label: "Edit Teachers", key: "edit_teachers"},
{label: "Edit Corporate Accounts", key: "edit_corporates"},
{label: "Edit Master Corporate Accounts", key: "edit_mastercorporates"},
{label: "Delete Students", key: "delete_students"},
{label: "Delete Teachers", key: "delete_teachers"},
{label: "Delete Corporate Accounts", key: "delete_corporates"},
{label: "Delete Master Corporate Accounts", key: "delete_mastercorporates"},
]
const EXAM_MANAGEMENT: PermissionLayout[] = [
{label: "Generate Reading", key: "generate_reading"},
{label: "Delete Reading", key: "delete_reading"},
{label: "Generate Listening", key: "generate_listening"},
{label: "Delete Listening", key: "delete_listening"},
{label: "Generate Writing", key: "generate_writing"},
{label: "Delete Writing", key: "delete_writing"},
{label: "Generate Speaking", key: "generate_speaking"},
{label: "Delete Speaking", key: "delete_speaking"},
{label: "Generate Level", key: "generate_level"},
{label: "Delete Level", key: "delete_level"},
]
const CLASSROOM_MANAGEMENT: PermissionLayout[] = [
{label: "View Classrooms", key: "view_classrooms"},
{label: "Create Classrooms", key: "create_classroom"},
{label: "Rename Classrooms", key: "rename_classrooms"},
{label: "Add to Classroom", key: "add_to_classroom"},
{label: "Remove from Classroom", key: "remove_from_classroom"},
{label: "Delete Classroom", key: "delete_classroom"},
]
const ENTITY_MANAGEMENT: PermissionLayout[] = [
{label: "View Entities", key: "view_entities"},
{label: "Rename Entity", key: "rename_entity"},
{label: "Add to Entity", key: "add_to_entity"},
{label: "Remove from Entity", key: "remove_from_entity"},
{label: "Delete Entity", key: "delete_entity"},
{label: "View Entity Roles", key: "view_entity_roles"},
{label: "Create Entity Role", key: "create_entity_role"},
{label: "Rename Entity Role", key: "rename_entity_role"},
{label: "Edit Role Permissions", key: "edit_role_permissions"},
{label: "Assign Role to User", key: "assign_to_role"},
{label: "Delete Entity Role", key: "delete_entity_role"},
]
export const getServerSideProps = withIronSessionSsr(async ({req, res, params}) => {
const user = await requestUser(req, res)
if (!user) return redirect("/login")
if (shouldRedirectHome(user)) return redirect("/")
const {id, role} = params as {id: string, role: string};
if (!mapBy(user.entities, 'id').includes(id) && !["admin", "developer"].includes(user.type)) return redirect("/entities")
const entity = await getEntityWithRoles(id);
if (!entity) return redirect("/entities")
const entityRole = findBy(entity.roles, 'id', role)
if (!entityRole) return redirect(`/entities/${id}/roles`)
if (!doesEntityAllow(user, entity, "view_entity_roles")) return redirect(`/entities/${id}`)
const userCount = await countEntityUsers(id, { "entities.role": role });
return {
props: serialize({
user,
entity,
role: entityRole,
userCount,
}),
};
}, sessionOptions);
interface Props {
user: User;
entity: EntityWithRoles;
role: Role;
userCount: number;
}
export default function Role({user, entity, role, userCount}: Props) {
const [permissions, setPermissions] = useState(role.permissions)
const [isLoading, setIsLoading] = useState(false);
const router = useRouter();
const canEditPermissions = useEntityPermission(user, entity, "edit_role_permissions")
const canRenameRole = useEntityPermission(user, entity, "rename_entity_role")
const canDeleteRole = useEntityPermission(user, entity, "delete_entity_role")
const renameRole = () => {
if (!canRenameRole) return;
const label = prompt("Rename this role:", role.label);
if (!label) return;
setIsLoading(true);
axios
.patch(`/api/roles/${role.id}`, {label})
.then(() => {
toast.success("The role has been updated successfully!");
router.replace(router.asPath);
})
.catch((e) => {
console.error(e);
toast.error("Something went wrong!");
})
.finally(() => setIsLoading(false));
};
const deleteRole = () => {
if (!canDeleteRole || role.isDefault) return;
if (!confirm("Are you sure you want to delete this role?")) return;
setIsLoading(true);
axios
.delete(`/api/roles/${role.id}`)
.then(() => {
toast.success("This role has been successfully deleted!");
router.replace(`/entities/${entity.id}/roles`);
})
.catch((e) => {
console.error(e);
toast.error("Something went wrong!");
})
.finally(() => setIsLoading(false));
};
const editPermissions = () => {
if (!canEditPermissions) return
setIsLoading(true);
axios
.patch(`/api/roles/${role.id}`, {permissions})
.then(() => {
toast.success("This role has been successfully updated!");
router.replace(router.asPath);
})
.catch((e) => {
console.error(e);
toast.error("Something went wrong!");
})
.finally(() => setIsLoading(false));
}
const togglePermissions = (p: string) => setPermissions(prev => prev.includes(p) ? prev.filter(x => x !== p) : [...prev, p])
return (
<>
<Head>
<title>{ role.label } | {entity.label} | EnCoach</title>
<meta
name="description"
content="A training platform for the IELTS exam provided by the Muscat Training Institute and developed by eCrop."
/>
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link rel="icon" href="/favicon.ico" />
</Head>
<Layout user={user}>
<section className="flex flex-col gap-0">
<div className="flex flex-col gap-3">
<div className="flex items-end justify-between">
<div className="flex items-center gap-2">
<Link
href={`/entities/${entity.id}/roles`}
className="text-mti-purple hover:text-mti-purple-dark transition ease-in-out duration-300 text-xl">
<BsChevronLeft />
</Link>
<h2 className="font-bold text-2xl">{role.label} Role ({ userCount } users)</h2>
</div>
</div>
<div className="flex items-center justify-between w-full">
<div className="flex items-center gap-2">
<button
onClick={renameRole}
disabled={isLoading || !canRenameRole}
className="flex items-center gap-1 px-2 py-2 border rounded-full hover:bg-neutral-100 disabled:hover:bg-transparent disabled:opacity-50 disabled:cursor-not-allowed cursor-pointer transition ease-in-out duration-300">
<BsTag />
<span className="text-xs">Rename Role</span>
</button>
<button
onClick={deleteRole}
disabled={isLoading || !canDeleteRole || role.isDefault}
className="flex items-center gap-1 px-2 py-2 border border-mti-rose rounded-full bg-mti-rose-light text-white hover:bg-mti-rose-dark disabled:hover:bg-mti-rose-light disabled:opacity-50 disabled:cursor-not-allowed cursor-pointer transition ease-in-out duration-300">
<BsTrash />
<span className="text-xs">Delete Role</span>
</button>
</div>
<button
onClick={editPermissions}
disabled={isLoading || !canEditPermissions}
className="flex items-center gap-1 px-2 py-2 border rounded-full border-mti-green bg-mti-green-light text-white hover:bg-mti-green-dark disabled:hover:bg-mti-green-light disabled:opacity-50 disabled:cursor-not-allowed cursor-pointer transition ease-in-out duration-300">
<BsCheck />
<span className="text-xs">Save Changes</span>
</button>
</div>
</div>
<Divider />
<section className="grid grid-cols-2 gap-16">
<div className="flex flex-col gap-4">
<div className="w-full flex items-center justify-between">
<b>User Management</b>
<Checkbox
isChecked={mapBy(USER_MANAGEMENT, 'key').every(k => permissions.includes(k))}
onChange={() => mapBy(USER_MANAGEMENT, 'key').forEach(togglePermissions)}
>
Select all
</Checkbox>
</div>
<Separator />
<div className="grid grid-cols-2 gap-4">
{USER_MANAGEMENT.map(({label, key}) => (
<Checkbox disabled={!canEditPermissions} key={key} isChecked={permissions.includes(key)} onChange={() => togglePermissions(key)}>
{ label }
</Checkbox>
)) }
</div>
</div>
<div className="flex flex-col gap-4">
<div className="w-full flex items-center justify-between">
<b>Exam Management</b>
<Checkbox
isChecked={mapBy(EXAM_MANAGEMENT, 'key').every(k => permissions.includes(k))}
onChange={() => mapBy(EXAM_MANAGEMENT, 'key').forEach(togglePermissions)}
>
Select all
</Checkbox>
</div>
<Separator />
<div className="grid grid-cols-2 gap-4">
{EXAM_MANAGEMENT.map(({label, key}) => (
<Checkbox disabled={!canEditPermissions} key={key} isChecked={permissions.includes(key)} onChange={() => togglePermissions(key)}>
{ label }
</Checkbox>
)) }
</div>
</div>
<div className="flex flex-col gap-4">
<div className="w-full flex items-center justify-between">
<b>Clasroom Management</b>
<Checkbox
isChecked={mapBy(CLASSROOM_MANAGEMENT, 'key').every(k => permissions.includes(k))}
onChange={() => mapBy(CLASSROOM_MANAGEMENT, 'key').forEach(togglePermissions)}
>
Select all
</Checkbox>
</div>
<Separator />
<div className="grid grid-cols-2 gap-4">
{CLASSROOM_MANAGEMENT.map(({label, key}) => (
<Checkbox disabled={!canEditPermissions} key={key} isChecked={permissions.includes(key)} onChange={() => togglePermissions(key)}>
{ label }
</Checkbox>
)) }
</div>
</div>
<div className="flex flex-col gap-4">
<div className="w-full flex items-center justify-between">
<b>Entity Management</b>
<Checkbox
isChecked={mapBy(ENTITY_MANAGEMENT, 'key').every(k => permissions.includes(k))}
onChange={() => mapBy(ENTITY_MANAGEMENT, 'key').forEach(togglePermissions)}
>
Select all
</Checkbox>
</div>
<Separator />
<div className="grid grid-cols-2 gap-4">
{ENTITY_MANAGEMENT.map(({label, key}) => (
<Checkbox disabled={!canEditPermissions} key={key} isChecked={permissions.includes(key)} onChange={() => togglePermissions(key)}>
{ label }
</Checkbox>
)) }
</div>
</div>
</section>
</section>
</Layout>
</>
);
}

View File

@@ -0,0 +1,158 @@
/* eslint-disable @next/next/no-img-element */
import CardList from "@/components/High/CardList";
import Layout from "@/components/High/Layout";
import Tooltip from "@/components/Low/Tooltip";
import { useEntityPermission } from "@/hooks/useEntityPermissions";
import {useListSearch} from "@/hooks/useListSearch";
import usePagination from "@/hooks/usePagination";
import {Entity, EntityWithRoles, Role} from "@/interfaces/entity";
import {GroupWithUsers, User} from "@/interfaces/user";
import {sessionOptions} from "@/lib/session";
import {USER_TYPE_LABELS} from "@/resources/user";
import { redirect, serialize } from "@/utils";
import { requestUser } from "@/utils/api";
import {getEntityWithRoles} from "@/utils/entities.be";
import {convertToUsers, getGroup} from "@/utils/groups.be";
import {shouldRedirectHome} from "@/utils/navigation.disabled";
import {checkAccess, doesEntityAllow, getTypesOfUser} from "@/utils/permissions";
import {getUserName} from "@/utils/users";
import {getEntityUsers, getLinkedUsers, getSpecificUsers} from "@/utils/users.be";
import axios from "axios";
import clsx from "clsx";
import {withIronSessionSsr} from "iron-session/next";
import moment from "moment";
import Head from "next/head";
import Link from "next/link";
import {useRouter} from "next/router";
import {Divider} from "primereact/divider";
import {useEffect, useMemo, useState} from "react";
import {
BsChevronLeft,
BsClockFill,
BsEnvelopeFill,
BsFillPersonVcardFill,
BsPlus,
BsSquare,
BsStopwatchFill,
BsTag,
BsTrash,
BsX,
} from "react-icons/bs";
import {toast, ToastContainer} from "react-toastify";
export const getServerSideProps = withIronSessionSsr(async ({req, res, params}) => {
const user = await requestUser(req, res)
if (!user) return redirect("/login")
if (shouldRedirectHome(user)) return redirect("/")
const {id} = params as {id: string};
const entity = await getEntityWithRoles(id);
if (!entity) return redirect("/entities")
if (!doesEntityAllow(user, entity, "view_entity_roles")) return redirect(`/entities/${id}`)
const users = await getEntityUsers(id);
return {
props: serialize({
user,
entity,
roles: entity.roles,
users,
}),
};
}, sessionOptions);
interface Props {
user: User;
entity: EntityWithRoles;
roles: Role[];
users: User[];
}
export default function Home({user, entity, roles, users}: Props) {
const router = useRouter();
const canCreateRole = useEntityPermission(user, entity, "create_entity_role")
const createRole = () => {
if (!canCreateRole) return
const label = prompt("What is the name of this new role?")
if (!label) return
axios.post<Role>('/api/roles', {label, permissions: [], entityID: entity.id})
.then((result) => {
toast.success(`'${label}' role created successfully!`)
router.push(`/entities/${entity.id}/roles/${result.data.id}`)
})
.catch(() => {
toast.error("Something went wrong!")
})
}
const firstCard = () => (
<button
onClick={createRole}
className="p-4 border hover:text-mti-purple rounded-xl flex flex-col items-center justify-center gap-0 hover:border-mti-purple transition ease-in-out duration-300 text-left cursor-pointer">
<BsPlus size={40} />
<span className="font-semibold">Create Role</span>
</button>
);
const renderCard = (role: Role) => {
const usersWithRole = users.filter((x) => x.entities.map((x) => x.role).includes(role.id));
return (
<Link
href={`/entities/${entity.id}/roles/${role.id}`}
key={role.id}
className={clsx(
"p-4 pr-6 h-fit relative border rounded-xl flex flex-col gap-3 text-left cursor-pointer",
"hover:border-mti-purple transition ease-in-out duration-300",
)}>
<div className="flex flex-col">
<span className="font-semibold">{role.label}</span>
<span className="opacity-80 text-sm">{usersWithRole.length} members</span>
</div>
<b>{role.permissions.length} Permissions</b>
</Link>
);
};
return (
<>
<Head>
<title>{entity.label} | EnCoach</title>
<meta
name="description"
content="A training platform for the IELTS exam provided by the Muscat Training Institute and developed by eCrop."
/>
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link rel="icon" href="/favicon.ico" />
</Head>
<ToastContainer />
<Layout user={user}>
<section className="flex flex-col gap-0">
<div className="flex flex-col gap-3">
<div className="flex items-end justify-between">
<div className="flex items-center gap-2">
<Link
href={`/entities/${entity.id}`}
className="text-mti-purple hover:text-mti-purple-dark transition ease-in-out duration-300 text-xl">
<BsChevronLeft />
</Link>
<h2 className="font-bold text-2xl">{entity.label}</h2>
</div>
</div>
</div>
<Divider />
<span className="font-semibold text-xl mb-4">Roles</span>
<CardList list={roles} searchFields={[["label"]]} renderCard={renderCard} firstCard={canCreateRole ? firstCard : undefined} />
</section>
</Layout>
</>
);
}