Implement Access Control in Node.js – node acl

Here we are discussing how to implement simple nodejs access control lists, when we develop an application it have more than one user roles and user roles and also have different permissions

Example : Guest, User, Admin etc. in this post we are implementing nodejs access control lists using node acl, node acl is popular and more than 5000 + weekly downloads when we compare to other acl packages

we can use three type of back-end for node acl

  • Redis
  • Mongodb
  • Memory
// Using redis backend
 acl = new acl(new acl.redisBackend(redisClient, prefix));

 // Or Using the memory backend
 acl = new acl(new acl.memoryBackend());

 // Or Using the mongodb backend
 acl = new acl(new acl.mongodbBackend(dbInstance, prefix));

here we are implementing using memory back-end

1# Install node acl

add acl package to your project npm i acl

2# creating permissions file

here we are creating permissions file, here assign acl and set roles for admin, // admin is allowed to view admin page

admin – role, /admin is page and get is request

//permissions.js

var Acl = require('acl'),acl;
acl = new Acl(new Acl.memoryBackend());

set_roles();

function set_roles () 
{
    acl.allow('admin', '/admin', ['get']);
}

module.exports = acl;

so we are created user roles for the user, now we want to assign the addUserRoles, place addUserRoles on login script page


// login.js
acl.addUserRoles(admin._id.toString(), admin.role) 
//acl.addUserRoles('5cda520b88f430366b508579', 'admin')

above part will shows that user id and user role set in the login part, then we move to another part includes middleware on the resource and protect our project in admin.js


// admin.js
router.get('/', [acl.middleware(1, '5cda520b88f430366b508579')],(req, res, next) =>{

the above part 1 represent ACL middleware will only take ‘/admin’ as the URL and protect the particular url, if you want second parameter to protect example, /admin/feedback , you can add 2 in the place of 1

Back to Top