Friday, 28 April 2017

acl.middleware() function leading to below error-" Error checking permissions to access resource"

I have all the authentication functionality in server.js file //server.js

//Mongoose
var db = 'mongodb://localhost/moviedb';
mongoose.connect(db);

//Authentication
app.use(passport.initialize());
app.use(passport.session());
passport.use(new LocalStrategy(
  function(username, password, done) {
    User.findOne({ username: username }, function(err, user) {
      if (err) { return done(err); }
      if (!user) {
        return done(null, false, { message: 'Incorrect username.' });
      }
      if (!user.validPassword(password)) {
        return done(null, false, { message: 'Incorrect password.' });
      }
      return done(null, user);
    });
  }
));
passport.serializeUser(function(user, done) {
  done(null, user._id);
});

passport.deserializeUser(function(id, done) {
  User.findById(id, function(err, user) {
    done(err, user);
  });
});


app.post('/login', function(req, res, next) {
passport.authenticate('local', function(err, user, info) { 
  if (err) { return next(err); }
  if (!user) {
    console.log(info);
    return res.send(info);
      }
  req.logIn(user, function(err) {
    if (err) { return next(err); }
  else{

  var acl_js=require('./acl');
return res.send(user);
}
  });
})(req, res, next)
});

//acl.js contains acl authorization functionality. The routes used in resources are express routes.

var node_acl = require('acl'),
 mongodb = require('mongodb'),
 acl;


(function(err,db){
  //var mongoBackend = new node_acl.mongodbBackend(mongodb.connect('mongodb://127.0.0.1:27017/acl'));
  acl = new node_acl(new node_acl.mongodbBackend(mongodb.connect('mongodb://127.0.0.1:27017/acl')), logger());
  set_roles();
})();
  function logger() {
      return {
          debug: function(msg) {
              console.log('-DEBUG-', msg);
          }
      };
  }
   function set_roles() {
      // Define roles, resources and permissions
      acl.allow([{
          roles: 'admin',
          allows: [{
                  resources: '/stream/delete',
                  permissions: '*'
              }, {
                  resources: '/stream/update',
                  permissions: '*'
              }
          ]
      }, {
          roles: 'user',
          allows: [{
                  resources:'/stream/add',
                  permissions:'*'
                  }]
      }
      ]);

      acl.isAllowed('58fe0f08b0c2b6144392c70f', 'delete', 'view', function(err, res){
    if(res){
        console.log("User joed is allowed to view blogs")
       }
     })

      acl.removeAllow('user', '/stream/display', 'get', function(err, res) {
        if(err){console.log("err in remove"+err);}
          if (res) {
              console.log("User joe is no longer allowed to get access delete")
          }
      })
      // Inherit roles
      //  Every user is allowed to do what guests do
      //  Every admin is allowed to do what users do
        acl.addRoleParents('user', 'admin');
          acl.addUserRoles('58fe0f08b0c2b6144392c710', 'user');//we have hardcoded user id
        acl.addUserRoles('58fe0f08b0c2b6144392c70f','admin');

  }
  module.exports = acl;

//user.js contains routes which I am trying to protect using middleware()

router.post('/add',acl.middleware(2,get_user_id),function(req, res, next)  
{  
  console.log("inside add route");
  ){
    if(res){
      console.log("inside add if");
     var movie=new Movie(req.body);
    movie.save(function(err,data){
    if(err)
      res.send({'success':'Not Saved'});
    else
    res.send({'success':'SAVED'});
    });

    }
    else
    {
      console.log("err in add router"+err);
    }

  });

However my code is resulting in below error=>

-DEBUG- Requesting * on /stream/add by user 58fe0f08b0c2b6144392c710 Error: Error checking permissions to access resource at /vagrant/omdb/node_modules/acl/lib/acl.js:697:14 at tryCatcher (/vagrant/omdb/node_modules/acl/node_modules/bluebird/js/release/util.js:16:23) at Promise.errorAdapter [as _rejectionHandler0] (/vagrant/omdb/node_modules/acl/node_modules/bluebird/js/release/nodeify.js:35:34) at Promise._settlePromise (/vagrant/omdb/node_modules/acl/node_modules/bluebird/js/release/promise.js:566:21) at Promise._settlePromise0 (/vagrant/omdb/node_modules/acl/node_modules/bluebird/js/release/promise.js:614:10) at Promise._settlePromises (/vagrant/omdb/node_modules/acl/node_modules/bluebird/js/release/promise.js:689:18) at Async._drainQueue (/vagrant/omdb/node_modules/acl/node_modules/bluebird/js/release/async.js:133:16) at Async._drainQueues (/vagrant/omdb/node_modules/acl/node_modules/bluebird/js/release/async.js:143:10) at Immediate.Async.drainQueues (/vagrant/omdb/node_modules/acl/node_modules/bluebird/js/release/async.js:17:14) at runCallback (timers.js:651:20) at tryOnImmediate (timers.js:624:5) at processImmediate [as _immediateCallback] (timers.js:596:5)

and it is displaying the below exceptions-

err in removeTypeError: self.db.collection is not a function Unhandled rejection TypeError: self.db.collection is not a function

I feel after reading blogs that my acl db is not connected before accessing the routes but I am unable to fix it.Please help me deal with the above issue.



via Anjali Upreti

No comments:

Post a Comment