简体   繁体   English

如果用户在 Reactjs 中拥有多个角色,如何实现角色?

[英]How to implement roles if user have more than one roles in Reactjs?

Previously I've created with Custom Hook and it works but only for 1 role .以前我用自定义钩子创建它,但它只适用于 1 个角色。

How do I make it work for users who have more than 1 role?如何使其适用于拥有 1 个以上角色的用户?

example of user roles :用户角色示例

  • User 1 = ["Super Admin", "Marketing"]用户 1 = [“超级管理员”,“营销”]
  • User 2 = ["Marketing", "Customer Service"]用户 2 = [“营销”、“客户服务”]

This code for Role Map:角色映射的代码:

enum ROLES {
  SUPER = "Super Admin",
  MARKETING = "Marketing",
  CUSTOMER_SERVICE = "Customer Service"
};

export const rolesMaps = (role) => {
  switch (role) {
    case ROLES.SUPER_ADMIN: {
      return {
        adminUserFeature: "READ WRITE DELETE",
        homePageFeature: "READ WRITE DELETE",
      };
    }
    case ROLES.MARKETING : {
      return {
        adminUserFeature: "READ WRITE DELETE",
        homePageFeature: "READ WRITE ",
      };
    }
    case ROLES.CUSTOMER_SERVICE : {
      return {
        adminUserFeature: "READ",
        homePageFeature: "READ",
      };
    }
    default:
      return {};
  }
}

This code for Custom Hook自定义挂钩的此代码

import { useMemo } from "react";
import { rolesMaps } from "./rolesMaps"; //Role Map

export const usePermissions = (role, feature) => {
  return useMemo(() => {
    const permissions = rolesMaps(role && role[0])[feature];
    console.log("permisi", permissions);
    
    return {
      canRead: !!permissions?.includes("READ"),
      canWrite: !!permissions?.includes("WRITE"),
      canDelete: !!permissions?.includes("DELETE"),
    };
  }, [role, feature]);
}

This code for implement on component此代码用于在组件上实现

  const role = useGetRole()
  const { canWrite } = usePermissions(role, "homePageFeature");

  {canWrite && <Button variant="primary" onClick={handleAddNew}>Add New</Button>}

For your role map, you could switch to using a key value pair where the value is an array of strings.对于您的角色映射,您可以切换到使用键值对,其中值是字符串数组。 This way you can check for duplicates easier, Here is my implementation.这样您可以更轻松地检查重复项,这是我的实现。

enum ROLES {
    SUPER_ADMIN = "Super Admin",
    MARKETING = "Marketing",
    CUSTOMER_SERVICE = "Customer Service"
};

// you can now pass in multiple roles into ROLES
export const rolesMaps = (roles: ROLES[]) => {
    const permissions: {[key: string]: string[]} = {};

    const addPermission = (featureName: string, permissionsToAdd: string[]) => {
        if (permissions[featureName] === undefined) {
            permissions[featureName] = [];
        }

        for (const perm of permissionsToAdd) {
            if (permissions[featureName].indexOf(perm) === -1) {
                permissions[featureName].push(perm);
            }
        }
    }

    for (const role of roles) {
        switch (role) {
            case ROLES.MARKETING:
            case ROLES.SUPER_ADMIN: {
                // add permissions that both marketing and super_admin share
                addPermission("adminUserFeature", ["READ", "WRITE", "DELETE"]);
                addPermission("homePageFeature", ["READ", "WRITE"]);
                
                if (role === ROLES.SUPER_ADMIN) {
                    // only admin role can delete in the homePageFeature
                    addPermission("homePageFeature", ["DELETE"]);
                }
            }
            case ROLES.CUSTOMER_SERVICE : {
                addPermission("adminUserFeature", ["READ"]);
                addPermission("homePageFeature", ["READ"]);
            }
        }
    }

    // the return value is now a {[key: string]: string[]}, the value is an array of strings
    // If you want the value to still be the same syntax as in your question
    // You can use permissions[featureName].join(" ") to get a string of roles seperated by a space
    // But the current usage of the return value should still work as arrays also have the .include() method
    return permissions;
}

I have used liked this我用过喜欢这个

export const useRole = ([allowedRoles]) => {
    const { user } = useAuth()
    const history = useHistory()
    useEffect(() => {
        return () => {
            if (!allowedRoles.includes(user?.role)) {
                history.push('/error')
            }
        }
    }, [])

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM