koa-roles
koa version of Connect-Roles
Last updated 9 years ago by fengmk2 .
MIT · Repository · Bugs · Original npm · Tarball · package.json
$ npm install koa-roles 
SYNC missed versions from official npm registry.

koa-roles

NPM version build status Test coverage Gittip David deps npm download

koa version of connect-roles

Install

$ npm install koa-roles

Usage

const Roles = require('koa-roles');
const koa = require('koa');
const app = new koa();

const user = new Roles({
  async failureHandler(ctx, action) {
    // optional function to customise code that runs when
    // user fails authorisation
    ctx.status = 403;
    var t = ctx.accepts('json', 'html');
    if (t === 'json') {
      ctx.body = {
        message: 'Access Denied - You don\'t have permission to: ' + action
      };
    } else if (t === 'html') {
      ctx.render('access-denied', {action: action});
    } else {
      ctx.body = 'Access Denied - You don\'t have permission to: ' + action;
    }
  }
});

app.use(user.middleware());

// anonymous users can only access the home page
// returning false stops any more rules from being
// considered
user.use(async (ctx, action) => {
  return ctx.user || action === 'access home page';
});

// moderator users can access private page, but
// they might not be the only ones so we don't return
// false if the user isn't a moderator
user.use('access private page', ctx => {
  if (ctx.user.role === 'moderator') {
    return true;
  }
})

//admin users can access all pages
user.use((ctx, action) => {
  if (ctx.user.role === 'admin') {
    return true;
  }
});

app.get('/', user.can('access home page'), async ctx => {
  await ctx.render('private');
});
app.get('/private', user.can('access private page'), async ctx => {
  await ctx.render('private');
});
app.get('/admin', user.can('access admin page'), async ctx => {
  await ctx.render('admin');
});

app.listen(3000);

License

MIT

Current Tags

  • 2.0.0                                ...           latest (7 years ago)

8 Versions

  • 2.0.0                                ...           7 years ago
  • 1.0.3                                ...           8 years ago
  • 1.0.2                                ...           9 years ago
  • 1.0.1                                ...           9 years ago
  • 1.0.0                                ...           10 years ago
  • 0.1.0                                ...           10 years ago
  • 0.0.1                                ...           11 years ago
  • 0.0.0                                ...           11 years ago
Maintainers (1)
Downloads
Total 0
Today 0
This Week 0
This Month 0
Last Day 0
Last Week 0
Last Month 0
Dependencies (1)
Dependents (1)

© 2010 - cnpmjs.org x YWFE | Home | YWFE