简体   繁体   中英

define user role node_acl, mongoose , express

I am trying to use node_acl to manage the authorization in my app. But I have a doubt how to implement the role for every user

app.js

const mongoose = require('mongoose');
const app = express();
const security = require(./security/security_acl);

//----------Database Connection ------------------------------
mongoose.Promise = global.Promise;
mongoose.connect('mongodb://localhost/db_test', { useMongoClient: true })
  .then(() => logger.info('Database connected'))
  .catch(error => logger.error('Database connection error: $(error.message)'))
const db = mongoose.connection;

// all other middleware functions

security_acl.js

'use strict';
const mongoose = require('mongoose');
const node_acl = require('acl');
var acl;
acl = new node_acl(new node_acl.mongodbBackend(mongoose.connection.db, 'acl_'));

set_roles();

function set_roles () {

    acl.allow([{
        roles: 'admin',
        allows: [{
                resources: '/api/config',
                permissions: '*'
            }
        ]
    }, {
        roles: 'user',
        allows: [{
            resources: 'clients',
            permissions: ['view', 'edit', 'delete']
        }]
    }, {
        roles: 'guest',
        allows: []
    }]);

    acl.addUserRoles('5863effc17a181523b12d48e', 'admin').then(function (res){
        console.log('Good');
    }).catch(function (err){
        console.log('Bad');
    });

}

module.exports = acl;

User Model

const userSchema = Schema({
  username: {
    type: String,
    required: [true, 'Username can't be empty'']
  },
  email: {
    type: String,
    required: [true, 'email can't be empty'']
  },
  encrypted_password: {
    type: String,
    required: [true, 'Password can't be empty'']
  },

  role: {
    type: Schema.Types.ObjectId,
    ref: 'roles',
    required: [true, 'Role can't be empty']
  }
}, {
  timestamps: true
});

In my user model I have a reference to the model ROLES.

How can pass the user id and role to the function acl.addUserRoles for all the users(new and previously registered)

Thanks in advance

Try this

userModel.find().populate("roles").exec().then(users => {
    users.forEach(user => 
        acl.addUserRoles(user._id, user.roles.map(role => role.name));
    )
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM