koa2-rbac
TypeScript icon, indicating that this package has built-in type declarations

1.0.1 • Public • Published

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)

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

Readme

Keywords

Package Sidebar

Install

npm i koa2-rbac

Weekly Downloads

0

Version

1.0.1

License

MIT

Unpacked Size

17.4 kB

Total Files

11

Last publish

Collaborators

  • talgat.s