1

我正在开发一个基于角色的应用程序。我们有 4 种不同的服务,我们必须根据角色显示操作按钮。例如,管理员可以看到所有操作按钮,但财务团队的人员只能看到财务操作按钮。

我正在使用 CASL js 库,但很难理解它是如何工作的。现在我的所有操作按钮都显示出来了。

能力.js

import { AbilityBuilder } from "@casl/ability";

const user = { name: "Admin", role: "finance" };
// const user = { name: "Finance", role: "finance" };
// const user = { name: "Subscriber", role: "sale" };
// const user = { name: "Subscriber", role: "employee" };

function subjectName(item) {
  if (user.role === "admin") {
    return "Admin";
  }
  return item;
}

export default AbilityBuilder.define({ subjectName }, can => {
  can(["read"], "Admin");
  can(["read"], "Finance");
  can(["read"], "Sale");
  can(["read"], "Employee");
  can(["read"], "Stock");
});

反应 app.js

import React from "react";
import { Can } from "@casl/react";
import ability from "./ability";

import "./App.css";

export default () => {
  return (
    <div>
      <h1>User</h1>
      <Can I="read" a="Finance" ability={ability}>
        <button>Finance</button>
      </Can>
      <Can I="read" a="Sale" ability={ability}>
        <button>Sale</button>
      </Can>
      <Can I="read" a="Employee" ability={ability}>
        <button>employee</button>
      </Can>
      <Can I="read" a="Stock" ability={ability}>
        <button>stock</button>
      </Can>
    </div>
  );
};
4

2 回答 2

0

像这样做@Dinesh Kumar的测试报价会更好吗

["employee", "admin"].includes(role), instead of role === "employee" || role === "admin"

结束了

["employee", "admin"].includes(role) && <AdminButton />
于 2021-04-07T14:59:57.567 回答
0

我不确定 CASL,但你可以这样做。您也可以添加任何基于角色的条件。

import React, { Component } from "react";

class App extends Component {
  state = {};
  clickManager = par => {
    console.log("Clicked by: ", par);
  };
  render() {
    let role = "admin";
    return (
      <div>
        {role === "admin" ? (
          <button
            onClick={() => {
              this.clickManager(role);
            }}
          >
            Admin
          </button>
        ) : (
          <div />
        )}
        {role === "finance" || role === "admin" ? (
          <button
            onClick={() => {
              this.clickManager(role);
            }}
          >
            Finance
          </button>
        ) : (
          <div />
        )}
        {role === "sales" || role === "admin" ? (
          <button
            onClick={() => {
              this.clickManager(role);
            }}
          >
            Sales
          </button>
        ) : (
          <div />
        )}
        {role === "employee" || role === "admin" ? (
          <button
            onClick={() => {
              this.clickManager(role);
            }}
          >
            employee
          </button>
        ) : (
          <div />
        )}
      </div>
    );
  }
}

export default App;
于 2019-08-01T05:33:31.113 回答