1.0.1 • Published 5 years ago

koa2-rbac v1.0.1

Weekly downloads
-
License
MIT
Repository
gitlab
Last release
5 years ago

koa2-rbac

NPM version Node.js Version pipeline status

Simple rbac for koa better use with koa-router

Installation

$ npm install koa2-rbac

API

new Role(options)

ParamTypeDescription
optionsObjectOptions
options.getRole(ctx, next) => stringreturn current role
options.denyHandler(ctx, next) => voiddefault 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

ParamTypeDescription
rolestring | string[] Allowed roles
denyHandler(ctx, next) => stringdeny 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

1.0.1

5 years ago

1.0.0

5 years ago

0.1.0

5 years ago