accesscontrol-decorator-extensions
Control access to whole instances or individual properties on those instances with ease, powered by accesscontrol.
Note: I am developing this for a side-project of mine, and will add features/fix issues as I encounter them. If you have a use-case that is not yet covered, please open an issue (or better yet, a pull request).
Get Started
yarn add accesscontrol-decorator-extensions
or
npm install --save accesscontrol-decorator-extensions
You will need to decorate the class you would like to control access to with the @ProtectedResource
decorator. You can further control access to individual properties with the @ProtectedProperty
decorator. For example:
import {
Action,
ProtectedProperty,
ProtectedResource,
Scope,
} from 'accesscontrol-decorator-extensions';
@ProtectedResource({
ownershipDeterminer: (viewer: User, instance: User) => viewer.id === userResult.id,
roleDeterminer: (viewer: User) => viewer.role,
})
class User {
public id: number;
@ProtectedProperty({
permissions: {
admin: {
[Action.CREATE]: Scope.ANY,
[Action.READ]: Scope.ANY,
[Action.UPDATE]: Scope.ANY,
[Action.DELETE]: Scope.ANY,
},
user: {
[Action.CREATE]: Scope.OWN,
[Action.READ]: Scope.ANY,
[Action.UPDATE]: Scope.OWN,
[Action.DELETE]: Scope.OWN,
},
},
})
public username: string;
@ProtectedProperty({
permissions: {
admin: {
[Action.CREATE]: Scope.ANY,
[Action.READ]: Scope.ANY,
[Action.UPDATE]: Scope.ANY,
[Action.DELETE]: Scope.ANY,
},
user: {
[Action.CREATE]: '',
[Action.READ]: Scope.OWN,
[Action.UPDATE]: '',
[Action.DELETE]: '',
},
},
})
public role: string;
}
Then for actually filtering the action, you would do something like this (imagine in an Express-like context):
import { Action, filterAccess } from 'accesscontrol-decorator-extensions';
export const editUser = async (req, res) => {
const { body, params, user } = req;
const userToUpdate = await db.user.findOne(params.userId);
userToUpdate.username = body.username;
const filteredUserUpdates: Partial<User> = filterAccess(user, Action.UPDATE, userToUpdate);
const savedUser = await db.user.save(filteredUserUpdates);
res.json({
success: true,
user: savedUser,
});
};
To check if a role has access to any fields in the root-level resource for a given action, you could do something like the following:
import { Action, canAccess } from 'accesscontrol-decorator-extensions';
export const deletePost = async (req, res) => {
const { params, user } = req;
if (!canAccess(user, Action.DELETE, new Post())) {
throw new Error('unauthorized!');
}
await db.post.deleteOne(params.id);
res.json({ success: true });
};
TypeScript Configuration
{
"target": "es2015",
"experimentalDecorators": true
}
Contribution
Feel free to contribute by forking this repository, making, testing, and building your changes, then opening a pull request. Please try to maintain a uniform code style.
License
MIT.
Extension of the accesscontrol library (also MIT).