CASL Ability subject helper 有条件
CASL Ability subject helper with conditions
我正在测试在 express 中对 RBAC 使用“@casl/ability”。
根据 CASL 文档,我应该能够定义针对对象操作的属性的条件限制,并且在不使用 类 的情况下,可以使用对象辅助函数来包装 DTO。
参考:https://casl.js.org/v4/en/guide/subject-type-detection
我尝试了下面这个非常简单的例子,它应该有效。但事实并非如此。我在某些方面理解不正确吗?
import { Ability, subject } from "@casl/ability";
const ability = new Ability([
{
action: "write",
subject: "docs",
conditions: {
publisherId: 53
}
}
]);
const docs = {};
// Also, if the third argument is skipped for 'fields', it throws an error
console.log(
ability.can("write", subject("docs", docs), "", { publisherId: 53 })
);
我这里有一个沙盒https://codesandbox.io/s/casl-test-conditions-uzc8v?file=/src/index.js:0-286
您错误地使用了ability.can
检查Api docs。这就是为什么它会抛出错误消息,指出您错误地使用 can
.
修正你的例子:
import { Ability, subject } from "@casl/ability";
const ability = new Ability([
{
action: "write",
subject: "docs",
conditions: {
publisherId: 53
}
}
]);
const docs = subject('docs', {
publisherId: 53
}); // “docs” type instance
console.log(
ability.can("write", docs)
);
我正在测试在 express 中对 RBAC 使用“@casl/ability”。 根据 CASL 文档,我应该能够定义针对对象操作的属性的条件限制,并且在不使用 类 的情况下,可以使用对象辅助函数来包装 DTO。
参考:https://casl.js.org/v4/en/guide/subject-type-detection
我尝试了下面这个非常简单的例子,它应该有效。但事实并非如此。我在某些方面理解不正确吗?
import { Ability, subject } from "@casl/ability";
const ability = new Ability([
{
action: "write",
subject: "docs",
conditions: {
publisherId: 53
}
}
]);
const docs = {};
// Also, if the third argument is skipped for 'fields', it throws an error
console.log(
ability.can("write", subject("docs", docs), "", { publisherId: 53 })
);
我这里有一个沙盒https://codesandbox.io/s/casl-test-conditions-uzc8v?file=/src/index.js:0-286
您错误地使用了ability.can
检查Api docs。这就是为什么它会抛出错误消息,指出您错误地使用 can
.
修正你的例子:
import { Ability, subject } from "@casl/ability";
const ability = new Ability([
{
action: "write",
subject: "docs",
conditions: {
publisherId: 53
}
}
]);
const docs = subject('docs', {
publisherId: 53
}); // “docs” type instance
console.log(
ability.can("write", docs)
);