Skip to content

Instantly share code, notes, and snippets.

@alexandrebodin
Last active December 24, 2021 15:17
Show Gist options
  • Save alexandrebodin/d16e64fade47721177ded88f0fd10cea to your computer and use it in GitHub Desktop.
Save alexandrebodin/d16e64fade47721177ded88f0fd10cea to your computer and use it in GitHub Desktop.
const _ = require("lodash");
const { defineAbility, an } = require("@casl/ability");
const { permittedFieldsOf } = require("@casl/ability/extra");
function Article(attrs) {
Object.assign(this, attrs);
}
const user = {
id: 1,
age: 2,
roles: [
{
id: 1,
name: "admin",
permissions: [
{
action: "read",
subject: "Article",
fields: ["author.name", "author.compo", "author.compo.compo.field"],
conditions: ["isOwner", "userIs21"],
},
],
},
],
};
const conditionGenerators = {
userIs21: (user) => {
if (user.age === 21) {
return true;
}
return false;
},
isOwner: (user) => ({ "created_by.id": user.id }),
};
const ability = defineAbility((allow) => {
user.roles.forEach((role) => {
role.permissions.forEach((perm) => {
if (perm.conditions && perm.conditions.length > 0) {
perm.conditions.forEach((cond) => {
const condition = conditionGenerators[cond](user);
if (condition === false) return; // if the generators returns false it means the permission should not be given.
if (condition === true) {
return allow(perm.action, perm.subject, perm.fields);
}
return allow(perm.action, perm.subject, perm.fields, condition);
});
} else {
return allow(perm.action, perm.subject, perm.fields);
}
});
});
});
const article = new Article({
author: {
name: "Georges",
},
created_by: {
id: 1,
},
});
console.log(ability.can("read", article, "author.name"));
// const data = ability.rulesFor("read", article).filter(article);
const allowedFields = permittedFieldsOf(ability, "read", article);
console.log(allowedFields);
console.log(_.pick(article, allowedFields));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment