egg-userrole
user role plugin for egg
Last updated 7 years ago by wanghx .
MIT · Repository · Bugs · Original npm · Tarball · package.json
$ cnpm install egg-userrole 
SYNC missed versions from official npm registry.

egg-userrole

NPM version build status Test coverage David deps Known Vulnerabilities npm download

Provide dynamic roles based authorisation. Use koa-roles.

Install

$ npm i egg-userrole --save

Usage

// {app_root}/config/plugin.js
exports.userrole = {
  package: 'egg-userrole',
};

Recommend to use along with custom userservice plugin (which provide ctx.user).

see egg-userservice for more info.

Build-in

Roles build-in failureHandler:

function failureHandler(ctx, action) {
  const message = 'Forbidden, required role: ' + action;
  if (ctx.acceptJSON) {
    ctx.body = {
      message: message,
      stat: 'deny',
    };
  } else {
    ctx.status = 403;
    ctx.body = message;
  }
};

Build-in user role define:

app.role.use('user', ctx => !!ctx.user);

How to custom failureHandler

Define app.role.failureHandler(action) method in config/role.js

  • app/extend/context.js
// {app_root}/config/role.js or {framework_root}/config/role.js
module.exports = app => {
  app.role.failureHandler = function(ctx, action) {
    if (ctx.acceptJSON) {
      ctx.body = { target: loginURL, stat: 'deny' };
    } else {
      ctx.realStatus = 200;
      ctx.redirect(loginURL);
    }
  };
}

How to custom role

// {app_root}/config/role.js or {framework_root}/config/role.js
module.exports = function(app) {
  app.role.use('admin', ctx => {
    return ctx.user && ctx.user.isAdmin;
  });

  app.role.use('can write', async ctx => {
    const post = await ctx.service.post.fetch(ctx.request.body.id);
    return ctx.user.name === post.author;
  });
};

Questions & Suggestions

Please open an issue here.

License

MIT

Current Tags

  • 2.1.0                                ...           latest (7 years ago)

10 Versions

  • 2.1.0                                ...           7 years ago
  • 2.0.0                                ...           8 years ago
  • 1.1.2                                ...           9 years ago
  • 1.1.1                                ...           9 years ago
  • 1.1.0                                ...           9 years ago
  • 1.0.0                                ...           9 years ago
  • 0.1.0                                ...           10 years ago
  • 0.0.3                                ...           10 years ago
  • 0.0.2                                ...           10 years ago
  • 0.0.1                                ...           10 years ago
Downloads
Today 0
This Week 0
This Month 0
Last Day 0
Last Week 0
Last Month 3
Dependencies (1)
Dev Dependencies (7)
Dependents (1)

Copyright 2013 - present © cnpmjs.org | Home |