在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
开源软件名称:koajs/koa-roles开源软件地址:https://github.com/koajs/koa-roles开源编程语言:JavaScript 100.0%开源软件介绍:koa-roleskoa version of connect-roles Install$ npm install koa-roles Usageconst 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 |
2023-10-27
2022-08-15
2022-08-17
2022-09-23
2022-08-13
请发表评论