djvirgen / virgen-acl

A simple ACL for node.js
MIT License
74 stars 19 forks source link

Use as middleware? #6

Closed facultymatt closed 7 years ago

facultymatt commented 11 years ago

Hello, Nice work on this ACL module. I appreciate that you can create custom access checks :+1:

Is it possible to use virgin-acl as middleware? Another module, https://github.com/OptimalBits/node_acl, supports this. However I leaning towards using virgen-acl because of the simplicity and control offered, as well as the custom access checks.

Thanks!

djvirgen commented 11 years ago

Hi,

virgen-acl can be used to check access to urls, but you'll need to create your own middleware wrapper. Something like this might work for you:

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

acl.allow(null, 'page', null, function(err, role, resource, path, result, next) {
  // Can't validate permission without a User instance
  if (!role instanceof User) return next();

  // allow admins to access every page
  if (role.isAdmin()) return result(true);

  // Allow everyone to see homepage
  if ('/' === path) return result(true);

  // Allow members to see certain pages
  if (role.isMember() && path.match(/^/members-access\//)) return result(true);

  // All other cases, no permission
  return result(false);
});

// Middleware wrapper
app.use(function(req, res, next) {
  var user = res.locals.currentUser; // get access to user object
  acl.query(user, 'page', req.path, function(err, allowed) {
    if (allowed) return next(); // user is allowed access to this page, pass through
    res.redirect('/'); // not allowed, redirect to home
  });
});

If you like this approach I can add native support to virgen-acl to help make it a little cleaner.

ali-bugdayci commented 10 years ago

This might be a nice start