英文:
How to optimize permissions on my front-end?
问题
我可以帮你优化你的导航链接,只显示那些具有 True 权限的字段。这是你的代码,已经进行了相应的优化:
import React, { useState } from "react";
import { NavLink } from "react-router-dom";
import { useAppContext } from "./AppContext"; // 确保导入正确的上下文
const NavLinks = ({ ToggleSideBar }) => {
const { user } = useAppContext();
const links = [
{
id: 1,
text: "panel",
path: "/",
icon: <IoBarChartSharp />,
menuItems: ["panel"],
},
{
id: 2,
text: "employee",
path: ["/add-employee", "/all-employee"],
icon: <MdQueryStats />,
menuItems: ["add new employee", "all employees"],
},
{
id: 3,
text: "customer",
path: ["/add-customer", "/emp-customers", "/all-customers"],
icon: <FaWpforms />,
menuItems: ["add new customer", "my customers", "all customers"],
},
{
id: 4,
text: "التقارير",
path: ["/profile", "/aw", "/all-jobs", "/add-job"],
icon: <ImProfile />,
menuItems: ["add customer", "customer Roles", "all customers", "الموظف المثالي"],
},
];
const [activeStatus, setActiveStatus] = useState({
firstnavcontainer: false,
secondnavcontainer: false,
thirdnavcontainer: false,
});
const firstFunction = () => {
setActiveStatus({
firstnavcontainer: true,
secondnavcontainer: false,
thirdnavcontainer: false,
});
};
const secondFunction = () => {
setActiveStatus({
...activeStatus,
firstnavcontainer: false,
secondnavcontainer: true,
thirdnavcontainer: false,
});
console.log(activeStatus);
};
const thirdFunction = () => {
setActiveStatus({
...activeStatus,
firstnavcontainer: false,
secondnavcontainer: false,
thirdnavcontainer: true,
});
};
const hasPermission = (permission) => {
// 检查用户是否具有特定权限
return user.permissions[permission] === true;
};
return (
<div className="nav-links">
{links.map((link) => {
const { text, path, id, icon, menuItems } = link;
const hasPermissions = menuItems.some((item) => hasPermission(item.toLowerCase()));
return (
hasPermissions && (
<div key={id} className="nav-item extra">
<ul className="dropdown-menu">
{menuItems.map((item, index) => (
hasPermission(item.toLowerCase()) && (
<NavLink
key={index}
to={path[index]}
className={({ isActive }) =>
isActive ? "dropdownmenu-item red-background" : "dropdownmenu-item"
}
>
<div className="dropdown-itemcontainer">
<span className="dropdown-itemtext">{item}</span>
</div>
</NavLink>
)
))}
</ul>
</div>
)
);
})}
</div>
);
};
export default NavLinks;
这个优化的代码会检查用户的权限并仅显示具有 True 权限的链接。如果用户没有某个权限,相关的链接将不会显示在菜单中。这是一种有效的处理权限的方法。
英文:
I have a navbar and set of permissions coming from the backend I stored them inside user object in my global context, and I can reach them by typinguser.permissions
{addCustomer: false, editAndDeleteCustomer: false, showAllCustomers: false, addEmployee: false, editAndDeleteEmployee: false, …}
How can I optimize my Navlinks by just displaying the True fields?
for example: if addCustomer is false, add customer shouldn't appear in menuItems and so on.
here is my code:
const NavLinks = ({ ToggleSideBar }) => {
const { user } = useAppContext();
const links = [
{
id: 1,
text: "panel",
path: "/",
icon: <IoBarChartSharp />,
menuItems: ["panel"],
},
{
id: 2,
text: "employee",
// path: "all-jobs",
path: ["add-employee", "all-employee"],
icon: <MdQueryStats />,
menuItems: [
"add new employee",
// "أدوار الموظفين",
"all employees",
// "الموظف المثالي",
],
},
{
id: 3,
text: "customer",
// path: "add-job",
path: ["add-customer", "emp-customers", "all-customers"],
icon: <FaWpforms />,
menuItems: [
"add new customer",
// "ارسال عميل",
// "الحسابات المنتظرة",
"my customers",
"all customers",
],
},
{
id: 4,
text: "التقارير",
// path: 'profile',
path: ["profile", "aw", "all-jobs", "add-job"],
icon: <ImProfile />,
menuItems: [
"add customer",
"customer Roles",
"all customers",
"الموظف المثالي",
],
},
];
const [isDropdownOpen2, setIsDropdownOpen2] = useState(false);
const [isDropdownOpen3, setIsDropdownOpen3] = useState(false);
const toggleDropdown2 = () => {
setIsDropdownOpen2(!isDropdownOpen2);
};
const toggleDropdown3 = () => {
setIsDropdownOpen3(!isDropdownOpen3);
};
const [activeStatus, setActiveStatus] = useState({
firstnavcontainer: false,
secondnavcontainer: false,
thirdnavcontainer: false,
});
const firstFunction = () => {
setActiveStatus((prevState) => ({
firstnavcontainer: true,
secondnavcontainer: false,
thirdnavcontainer: false,
}));
};
const secondFunction = () => {
setActiveStatus((prevState) => ({
...prevState,
firstnavcontainer: false,
secondnavcontainer: true,
thirdnavcontainer: false,
}));
console.log(activeStatus);
};
const thirdFunction = () => {
setActiveStatus((prevState) => ({
...prevState,
firstnavcontainer: false,
secondnavcontainer: false,
thirdnavcontainer: true,
}));
};
return (
<div className="nav-links">
{links.map((link) => {
const { text, path, id, icon, menuItems } = link;
return (
<>
{/* first item */}
{id === 1 && (
<div className="nav-item extra" onClick={firstFunction}>
<ul className="dropdown-menu">
{menuItems.map((item, index) => (
<NavLink
to={path[index]}
// onClick={ToggleSideBar}
className={({ isActive }) =>
isActive
? "dropdownmenu-item red-background"
: "dropdownmenu-item"
}
>
<div className="dropdown-itemcontainer">
<span className="dropdown-itemtext">{item}</span>
</div>
</NavLink>
))}
</ul>
</div>
)}
{/* second section */}
{id === 2 && (
<div className="nav-item extra" onClick={secondFunction}>
<button
className={`dropdown-toggle ${
activeStatus.secondnavcontainer ? "red-background" : ""
}`}
>
<div className="dropdownbtn">
<span className="icon">{icon}</span>
<span>{text}</span>
</div>
<BsChevronDown
className="dropdown-icon"
onClick={toggleDropdown2}
/>
</button>
{isDropdownOpen2 && (
<ul className="dropdown-menu">
{menuItems.map((item, index) => (
<NavLink
to={path[index]}
// onClick={ToggleSideBar}
className={({ isActive }) =>
isActive
? "dropdownmenu-item active"
: "dropdownmenu-item"
}
>
<div className="dropdown-itemcontainer">
<span className="dropdown-itemtext">{item}</span>
</div>
</NavLink>
))}
</ul>
)}
</div>
)}
{/* third section */}
{id === 3 && (
<div className="nav-item extra" onClick={thirdFunction}>
<button
className={`dropdown-toggle ${
activeStatus.thirdnavcontainer ? "red-background" : ""
}`}
>
<div className="dropdownbtn">
<span className="icon">{icon}</span>
<span>{text}</span>
</div>
<BsChevronDown
className="dropdown-icon"
onClick={toggleDropdown3}
/>
</button>
{isDropdownOpen3 && (
<ul className="dropdown-menu">
{menuItems.map((item, index) => (
<NavLink
to={path[index]}
// onClick={ToggleSideBar}
className={({ isActive }) =>
isActive
? "dropdownmenu-item active"
: "dropdownmenu-item"
}
>
<div className="dropdown-itemcontainer">
<span className="dropdown-itemtext">{item}</span>
</div>
</NavLink>
))}
</ul>
)}
</div>
)}
</>
);
})}
</div>
);
};
export default NavLinks;
Since It is a permissions-related problem, is there another approach to do this?
答案1
得分: 1
将一个角色/权限或角色/权限数组字段添加到links
数组对象中。这些值应该与user.permissions
对象键匹配。
示例:
const links = [
{
id: 1,
text: "panel",
path: "/",
icon: <IoBarChartSharp />,
menuItems: ["panel"],
roles: null, // <-- 任何角色/权限
},
{
id: 2,
text: "employee",
// path: "all-jobs",
path: ["add-employee", "all-employee"],
icon: <MdQueryStats />,
menuItems: [
"add new employee",
// "أدوار الموظفين",
"all employees",
// "الموظف المثالي",
],
roles: ["addEmployee"], // <-- 仅适用于addEmployee角色/权限
},
{
id: 3,
text: "customer",
// path: "add-job",
path: ["add-customer", "emp-customers", "all-customers"],
icon: <FaWpforms />,
menuItems: [
"add new customer",
// "ارسال عميل",
// "الحسابات المنتظرة",
"my customers",
"all customers",
],
roles: ["addCustomer", "showAllCustomers"], // <-- addCustomer或showAllCustomers角色/权限
},
{
id: 4,
text: "التقارير",
// path: 'profile',
path: ["profile", "aw", "all-jobs", "add-job"],
icon: <ImProfile />,
menuItems: [
"add customer",
"customer Roles",
"all customers",
"الموظف المثالي",
],
roles: ["showAllCustomers"], // <-- 等等...
},
];
然后在映射之前对links
数组进行筛选。
{links
.filter(link => link.roles?.length
// 如果有要检查的链接角色,请将它们与用户权限进行检查
? link.roles.some(role => user.permissions[role])
// 否则返回true以包括菜单链接项
: true
)
.map((link) => {
...
})
}
英文:
Add a role/permission, or array of roles/permissions, field to the links
array objects. These values should match a user.permissions
object key.
Example:
const links = [
{
id: 1,
text: "panel",
path: "/",
icon: <IoBarChartSharp />,
menuItems: ["panel"],
roles: null, // <-- any role/permission
},
{
id: 2,
text: "employee",
// path: "all-jobs",
path: ["add-employee", "all-employee"],
icon: <MdQueryStats />,
menuItems: [
"add new employee",
// "أدوار الموظفين",
"all employees",
// "الموظف المثالي",
],
roles: ["addEmployee"], // <-- only addEmployee role/permission
},
{
id: 3,
text: "customer",
// path: "add-job",
path: ["add-customer", "emp-customers", "all-customers"],
icon: <FaWpforms />,
menuItems: [
"add new customer",
// "ارسال عميل",
// "الحسابات المنتظرة",
"my customers",
"all customers",
],
roles: ["addCustomer", "showAllCustomers"], // <-- addCustomer or showAllCustomers role/permission
},
{
id: 4,
text: "التقارير",
// path: 'profile',
path: ["profile", "aw", "all-jobs", "add-job"],
icon: <ImProfile />,
menuItems: [
"add customer",
"customer Roles",
"all customers",
"الموظف المثالي",
],
roles: ["showAllCustomers"], // <-- etc...
},
];
Then filter the links
array prior to mapping them.
{links
.filter(link => link.roles?.length
// if there are link roles to check, check them against the user permissions
? link.roles.some(role => user.permissions[role])
// otherwise return true to include menu link item
: true
)
.map((link) => {
...
})
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论