koa2-rbac
v1.0.1
Published
Simple rbac for koa2
Downloads
1
Readme
koa2-rbac
Simple rbac for koa better use with koa-router
Installation
$ npm install koa2-rbac
API
new Role(options)
| Param | Type | Description | | --------------------- | ---------------------------------- | -------------------- | | [options] | Object | Options | | [options.getRole] | (ctx, next) => string | return current role | | [options.denyHandler] | (ctx, next) => void | default deny handler |
Example
Basic usage with koa-router
, use named routes(not required) to enable easy error message:
const Koa = require("koa");
const Router = require("koa-router");
const Role = require("koa2-rbac");
const app = new Koa();
const router = new Router();
const role = new Role({
getRole(ctx, next) {
return ctx._user.role;
},
denyHandler(ctx, next) {
const { _matchedRouteName: matchedRouteName } = ctx;
ctx.status = 403;
ctx.body = {
error: matchedRouteName
? `Access Denied - You don't have permission to :: ${matchedRouteName}`
: "Access Denied - You don't have permission"
};
}
});
roles.is(roles, denyHanlder) => Koa.Middleware | void
| Param | Type | Description | | ------------- | ------------------------------------ | ------------------------------ | | [role] | string | string[] | Allowed roles | | [denyHandler] | (ctx, next) => string | deny handler for current route |
Example
Basic usage with koa-router
router.patch("Update user", "/users/:id", role.is("ADMIN"), (ctx, next) => {
// Only ADMIN allowed
});
router.post(
"Send comment",
"/comments",
role.is(["ADMIN", "USER"]),
(ctx, next) => {
// Only ADMIN and USER allowed
}
);
router.get("Get post", "/posts/:id", (ctx, next) => {
// Everyone allowed, better to leave without role.is
});
router.delete(
"Delete post",
"/posts/:id",
role.is(["ADMIN", "USER"], (ctx, next) => {
ctx.status = 403;
ctx.body = {
error: "You cannot delete post"
};
}),
(ctx, next) => {
// Only ADMIN and USER allowed, for others returns "You cannot delete post"
}
);
License
MIT