如何优化我的前端权限?

huangapple go评论54阅读模式
英文:

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 }) =&gt; {
const { user } = useAppContext();
const links = [
{
id: 1,
text: &quot;panel&quot;,
path: &quot;/&quot;,
icon: &lt;IoBarChartSharp /&gt;,
menuItems: [&quot;panel&quot;],
},
{
id: 2,
text: &quot;employee&quot;,
// path: &quot;all-jobs&quot;,
path: [&quot;add-employee&quot;, &quot;all-employee&quot;],
icon: &lt;MdQueryStats /&gt;,
menuItems: [
&quot;add new employee&quot;,
// &quot;أدوار الموظفين&quot;,
&quot;all employees&quot;,
// &quot;الموظف المثالي&quot;,
],
},
{
id: 3,
text: &quot;customer&quot;,
// path: &quot;add-job&quot;,
path: [&quot;add-customer&quot;, &quot;emp-customers&quot;, &quot;all-customers&quot;],
icon: &lt;FaWpforms /&gt;,
menuItems: [
&quot;add new customer&quot;,
// &quot;ارسال عميل&quot;,
// &quot;الحسابات المنتظرة&quot;,
&quot;my customers&quot;,
&quot;all customers&quot;,
],
},
{
id: 4,
text: &quot;التقارير&quot;,
// path: &#39;profile&#39;,
path: [&quot;profile&quot;, &quot;aw&quot;, &quot;all-jobs&quot;, &quot;add-job&quot;],
icon: &lt;ImProfile /&gt;,
menuItems: [
&quot;add customer&quot;,
&quot;customer Roles&quot;,
&quot;all customers&quot;,
&quot;الموظف المثالي&quot;,
],
},
];
const [isDropdownOpen2, setIsDropdownOpen2] = useState(false);
const [isDropdownOpen3, setIsDropdownOpen3] = useState(false);
const toggleDropdown2 = () =&gt; {
setIsDropdownOpen2(!isDropdownOpen2);
};
const toggleDropdown3 = () =&gt; {
setIsDropdownOpen3(!isDropdownOpen3);
};
const [activeStatus, setActiveStatus] = useState({
firstnavcontainer: false,
secondnavcontainer: false,
thirdnavcontainer: false,
});
const firstFunction = () =&gt; {
setActiveStatus((prevState) =&gt; ({
firstnavcontainer: true,
secondnavcontainer: false,
thirdnavcontainer: false,
}));
};
const secondFunction = () =&gt; {
setActiveStatus((prevState) =&gt; ({
...prevState,
firstnavcontainer: false,
secondnavcontainer: true,
thirdnavcontainer: false,
}));
console.log(activeStatus);
};
const thirdFunction = () =&gt; {
setActiveStatus((prevState) =&gt; ({
...prevState,
firstnavcontainer: false,
secondnavcontainer: false,
thirdnavcontainer: true,
}));
};
return (
&lt;div className=&quot;nav-links&quot;&gt;
{links.map((link) =&gt; {
const { text, path, id, icon, menuItems } = link;
return (
&lt;&gt;
{/* first item */}
{id === 1 &amp;&amp; (
&lt;div className=&quot;nav-item extra&quot; onClick={firstFunction}&gt;
&lt;ul className=&quot;dropdown-menu&quot;&gt;
{menuItems.map((item, index) =&gt; (
&lt;NavLink
to={path[index]}
// onClick={ToggleSideBar}
className={({ isActive }) =&gt;
isActive
? &quot;dropdownmenu-item red-background&quot;
: &quot;dropdownmenu-item&quot;
}
&gt;
&lt;div className=&quot;dropdown-itemcontainer&quot;&gt;
&lt;span className=&quot;dropdown-itemtext&quot;&gt;{item}&lt;/span&gt;
&lt;/div&gt;
&lt;/NavLink&gt;
))}
&lt;/ul&gt;
&lt;/div&gt;
)}
{/* second section */}
{id === 2 &amp;&amp; (
&lt;div className=&quot;nav-item extra&quot; onClick={secondFunction}&gt;
&lt;button
className={`dropdown-toggle ${
activeStatus.secondnavcontainer ? &quot;red-background&quot; : &quot;&quot;
}`}
&gt;
&lt;div className=&quot;dropdownbtn&quot;&gt;
&lt;span className=&quot;icon&quot;&gt;{icon}&lt;/span&gt;
&lt;span&gt;{text}&lt;/span&gt;
&lt;/div&gt;
&lt;BsChevronDown
className=&quot;dropdown-icon&quot;
onClick={toggleDropdown2}
/&gt;
&lt;/button&gt;
{isDropdownOpen2 &amp;&amp; (
&lt;ul className=&quot;dropdown-menu&quot;&gt;
{menuItems.map((item, index) =&gt; (
&lt;NavLink
to={path[index]}
// onClick={ToggleSideBar}
className={({ isActive }) =&gt;
isActive
? &quot;dropdownmenu-item active&quot;
: &quot;dropdownmenu-item&quot;
}
&gt;
&lt;div className=&quot;dropdown-itemcontainer&quot;&gt;
&lt;span className=&quot;dropdown-itemtext&quot;&gt;{item}&lt;/span&gt;
&lt;/div&gt;
&lt;/NavLink&gt;
))}
&lt;/ul&gt;
)}
&lt;/div&gt;
)}
{/* third section */}
{id === 3 &amp;&amp; (
&lt;div className=&quot;nav-item extra&quot; onClick={thirdFunction}&gt;
&lt;button
className={`dropdown-toggle ${
activeStatus.thirdnavcontainer ? &quot;red-background&quot; : &quot;&quot;
}`}
&gt;
&lt;div className=&quot;dropdownbtn&quot;&gt;
&lt;span className=&quot;icon&quot;&gt;{icon}&lt;/span&gt;
&lt;span&gt;{text}&lt;/span&gt;
&lt;/div&gt;
&lt;BsChevronDown
className=&quot;dropdown-icon&quot;
onClick={toggleDropdown3}
/&gt;
&lt;/button&gt;
{isDropdownOpen3 &amp;&amp; (
&lt;ul className=&quot;dropdown-menu&quot;&gt;
{menuItems.map((item, index) =&gt; (
&lt;NavLink
to={path[index]}
// onClick={ToggleSideBar}
className={({ isActive }) =&gt;
isActive
? &quot;dropdownmenu-item active&quot;
: &quot;dropdownmenu-item&quot;
}
&gt;
&lt;div className=&quot;dropdown-itemcontainer&quot;&gt;
&lt;span className=&quot;dropdown-itemtext&quot;&gt;{item}&lt;/span&gt;
&lt;/div&gt;
&lt;/NavLink&gt;
))}
&lt;/ul&gt;
)}
&lt;/div&gt;
)}
&lt;/&gt;
);
})}
&lt;/div&gt;
);
};
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: &quot;panel&quot;,
    path: &quot;/&quot;,
    icon: &lt;IoBarChartSharp /&gt;,
    menuItems: [&quot;panel&quot;],
    roles: null, // &lt;-- any role/permission
  },
  {
    id: 2,
    text: &quot;employee&quot;,
    // path: &quot;all-jobs&quot;,
    path: [&quot;add-employee&quot;, &quot;all-employee&quot;],
    icon: &lt;MdQueryStats /&gt;,
    menuItems: [
      &quot;add new employee&quot;,
      // &quot;أدوار الموظفين&quot;,
      &quot;all employees&quot;,
      // &quot;الموظف المثالي&quot;,
    ],
    roles: [&quot;addEmployee&quot;], // &lt;-- only addEmployee role/permission
  },
  {
    id: 3,
    text: &quot;customer&quot;,
    // path: &quot;add-job&quot;,
    path: [&quot;add-customer&quot;, &quot;emp-customers&quot;, &quot;all-customers&quot;],
    icon: &lt;FaWpforms /&gt;,
    menuItems: [
      &quot;add new customer&quot;,
      // &quot;ارسال عميل&quot;,
      // &quot;الحسابات المنتظرة&quot;,
      &quot;my customers&quot;,
      &quot;all customers&quot;,
    ],
    roles: [&quot;addCustomer&quot;, &quot;showAllCustomers&quot;], // &lt;-- addCustomer or showAllCustomers role/permission
  },
  {
    id: 4,
    text: &quot;التقارير&quot;,
    // path: &#39;profile&#39;,
    path: [&quot;profile&quot;, &quot;aw&quot;, &quot;all-jobs&quot;, &quot;add-job&quot;],
    icon: &lt;ImProfile /&gt;,
    menuItems: [
      &quot;add customer&quot;,
      &quot;customer Roles&quot;,
      &quot;all customers&quot;,
      &quot;الموظف المثالي&quot;,
    ],
    roles: [&quot;showAllCustomers&quot;], // &lt;-- etc...
  },
];

Then filter the links array prior to mapping them.

{links
  .filter(link =&gt; link.roles?.length
    // if there are link roles to check, check them against the user permissions
    ? link.roles.some(role =&gt; user.permissions[role])
    // otherwise return true to include menu link item
    : true
  )
  .map((link) =&gt; {
    ...
  })
}

huangapple
  • 本文由 发表于 2023年5月28日 06:22:58
  • 转载请务必保留本文链接:https://go.coder-hub.com/76349277.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定