Skip to content

Instantly share code, notes, and snippets.

@kshirish
Created February 21, 2018 16:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kshirish/6e001e2a803c2ab9326af75337257395 to your computer and use it in GitHub Desktop.
Save kshirish/6e001e2a803c2ab9326af75337257395 to your computer and use it in GitHub Desktop.
Access Control
// users
const users = [
{
id: 0,
name: "Rocky"
},
{
id: 1,
name: "John"
},
{
id: 2,
name: "Dick"
},
{
id: 3,
name: "Tom"
},
{
id: 4,
name: "Harry"
}
];
// groups
const groups = [
{
id: 0,
name: "admin",
users: [1, 4]
},
{
id: 1,
name: "cleaner",
users: [0]
}
];
// operations
const create = () => console.log("I can create.");
const edit = () => console.log("I can edit.");
const remove = () => console.log("I can remove.");
const get = () => console.log("I can get.");
// retrieve userId and groupIds of which the user is part of
const getInfo = user => {
const userId = user.id;
const groupIds = groups
.filter(group => group.users.indexOf(userId) !== -1)
.map(group => group.id);
return {
userId,
groupIds
};
};
// logic for who can access what
const rules = {
create: [
{
type: "group",
id: 0
},
{
type: "user",
id: 0
},
{
type: "user",
id: 2
}
],
edit: [
{
type: "group",
id: 0
},
{
type: "user",
id: 2
},
{
type: "user",
id: 3
}
],
remove: [
{
type: "group",
id: 0
},
{
type: "user",
id: 2
},
{
type: "user",
id: 3
}
],
get: [
{
type: "group",
id: 0
},
{
type: "user",
id: 0
}
]
};
// checkpoint/middleware
const isAllowed = (user, operationFun) => {
const { userId, groupIds } = getInfo(user);
const operation = operationFun.name;
if (rules[operation]) {
let isAllowed = rules[operation]
.filter(entity => entity.type === "user")
.some(user => user.id === userId);
if (isAllowed) {
// check if the user can perform the operation
operationFun();
} else {
// if not, check the group can perform the operation
const allowedGroupIds = rules[operation]
.filter(entity => entity.type === "group")
.map(group => group.id);
isAllowed = !!allowedGroupIds.filter(gId => groupIds.indexOf(gId) !== -1)
.length;
if (isAllowed) operationFun();
else console.log("You are not allowed to perform this operation!");
}
} else {
console.log("Operation doesn't exist!");
}
};
// Rules:
// 1. admin group can do anything
// 3. Tom can edit & remove
// 4. Dick can edit & create & remove
// 5. Rocky can create & get
isAllowed(users[0], create);
isAllowed(users[3], edit);
isAllowed(users[4], create);
isAllowed(users[1], edit);
isAllowed(users[3], create);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment