我在使用Node ACL分配用户角色和权限时遇到麻烦。我是MEAN Stack的新手,所以我真的对节点或javascript框架的工作原理没有很好的了解。
我正在尝试创建一个注册系统,当用户注册后,他将与user
一起被分配user permissions
角色。
到目前为止,这是我的代码
* server.js *
这是我的节点应用程序入口点
var acl;
var app = express();
//Importing other required files
var databaseConfig = require('./config/database');
var routes = require('./routes/index');
//Connect to the database
//Set up default mongoose connection
mongoose.connect(databaseConfig.url,{ useNewUrlParser: true },_mongo_connected);
function _mongo_connected( error, db ) {
if (error){
console.log(chalk.red('Could not connect to database. Error '+error));
} else{
console.log(chalk.green('Connected to database '+ config.db.uri));
var mongoBackend = new node_acl.mongodbBackend(db);
acl = new node_acl( mongoBackend);
global.ACL = acl; // I set it global so i can use it else where
set_roles();
}
}
function set_roles() {
acl.allow([
{
roles: 'admin',
allows: [
{ resources: '*', permissions: '*' }
]
}, {
roles: 'user',
allows: [
{ resources: '/api/user',permissions:['get', 'put', 'delete'] }
]
}, {
roles: 'guest',
allows: []
}
]);
acl.addRoleParents( 'user', 'guest' );
acl.addRoleParents( 'admin', 'user' );
}
我的路线文件 * route / index.js *
var express = require('express');
var router = express.Router();
var authController = require('../app/Controllers/AuthController');
router.post('/registration',authController.registration);
现在 * AuthController.js *
const User = require('../Models/User');
exports.registration = function (req, res) {
let errors = [];
if (!req.body.email ){
errors.push('Please enter your email');
}
if (errors.length){
//There are errors
res.json({
code:420,
success:false,
msg:'One or more filed are missing',
errors:errors
});
} else{
let newUser = new User({
name:req.body.name,
email:req.body.email,
password:req.body.password,
firstName:req.body.firstName,
lastName:req.body.lastName,
role:'user'
});
User.addUser(newUser,(error,user)=>{
if (error){
res.json({
code:420,
success:false,
msg:'Failed to register user.Probably this email/username is already taken.',
errors:error.errors
});
}else{
console.log('Hello');
console.log('User id',user._id.toString());
ACL.addUserRoles(user._id.toString(), user.role, err => {
if (err) {
console.log(err);
}
console.log('Added', user.role, 'role to user', user.firstName, 'with id', user._id);
});
res.json({
code:200,
success:true,
msg:'User registered successfully'
});
}
})
}
};
当我点击API时,用户什么都没有注册到数据库中,而我期望它为用户分配user
权限。
谁能帮我。
正如您所看到的,我将ACL
设置为全局变量,但我认为这不是我应该做的。
我从这里开始关注教程:https://blog.codecentric.de/en/2018/07/protecting-resources-with-node_acl-module-in-nodejs/
答案 0 :(得分:0)
在我的节点应用程序的server.js中,acl是通过使用accessControl()实现的。
const isAuthenticated = (req, res, next) => {
if (req.isAuthenticated()) {
next()
}
res.redirect('login')
}
function accessControl() {
const nodeAcl = new ACL(new ACL.memoryBackend())
nodeAcl.allow([{
roles: 'admin',
allows: [{
resources: ['/home','/api/users', '/api/posts'],
permissions: '*',
}],
}, {
roles: 'user',
allows: [{
resources: ['/api/users', '/api/posts'],
permissions: 'get',
}],
}, {
roles: 'guest',
allows: [],
}])
// Inherit roles
// Every user is allowed to do what guests do
// Every admin is allowed to do what users do
nodeAcl.addRoleParents('user', 'guest')
nodeAcl.addRoleParents('admin', 'user')
nodeAcl.addUserRoles('joe', 'admin')
nodeAcl.addUserRoles('john', 'user')
nodeAcl.addUserRoles(0, 'guest')
return nodeAcl
}
const access = accessControl()
为角色分配权限后,我在获取主目录URL时使用了ACL中间件。
app.get('/home', [isAuthenticated, access.middleware()], (req, res) => {
res.render(__dirname + '/views/home.ejs');
});
这对我有用。我也希望对您有用。