• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

koajs/koa-roles: koa version of Connect-Roles

原作者: [db:作者] 来自: 网络 收藏 邀请

开源软件名称:

koajs/koa-roles

开源软件地址:

https://github.com/koajs/koa-roles

开源编程语言:

JavaScript 100.0%

开源软件介绍:

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 Router = require('koa-router');

const app = new Koa();
const router = new Router();
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());
app.use(router.routes())
  .use(router.allowedMethods());
  
// 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;
  }
});

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

app.listen(3000);

License

MIT




鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap