node.js - nodejs passport - use same routes in api but return different sets of data based on permissions -




not sure of clean way go his. let's have endpoint:

get /api/books/ 

for user on webservice, return only user's resources. might little this:

exports.getbooks = function(req, res) {   // find books user   bookmodel.find({ userid: req.user._id }, function(err, books) {     if (err)       res.send(err);      res.json(books);   }); }; 

the web service using api needs user logged in first. can achieve using basic passport strategy ensure authentication. let's have admin account needs see books ever recorded. what's more admin account , user accounts have different properties assigning boolean permissions not enough. using same endpoint:

get /api/books 

i see no reason write endpoint achieve this. difference this:

exports.getbooks = function(req, res) {    // find books in database    bookmodel.find({}, function(err, books) {      if (err)        res.send(err);       res.json(books);    });  }; 

however cannot come clean way achieve while using passport middlewear intended so:

router.route('/books')   .post(authcontroller.isauthenticated, bookcontroller.postbooks)   .get(authcontroller.isauthenticated, bookcontroller.getbooks); 

the function isauthenticated will verify whether or not user requesting resources has permission , not change way controller behaves. i'm open ideas.

answer

the user @zerocho suggested check user properties in req.user object determine should sent back. more simple expected. in implementation passport.basicauth strategy, check table has matching doc. once user found in common user or admin user table add property in ismatch return object.

   // basic strategy users    passport.use('basic', new basicstrategy(       function(email, password, done) {        verifyuserpassword(email, password,     function(err, ismatch) {       if(err) { return done(err); }        // password did not match       if(!ismatch) { return done(null, false); }        // success       var userinfo = {         email: email,         isadmin: ismatch.isadmin || false,         businessid: ismatch.businessid || false       };        return done(null, userinfo);     });   })     ); 

then can check if .isadmin or .businessid valid in requests.

just separate controller if statement

exports.getbooks = function(req, res) {   if (req.user.isadmin) { // or other code check user admin     // find books in database     bookmodel.find({}, function(err, books) {       if (err)         res.send(err);       res.json(books);     });   } else {     bookmodel.find({ userid: req.user._id }, function(err, books) {       if (err)         res.send(err);       res.json(books);     });   } }; 




wiki

Comments

Popular posts from this blog

Asterisk AGI Python Script to Dialplan does not work -

python - Read npy file directly from S3 StreamingBody -

kotlin - Out-projected type in generic interface prohibits the use of metod with generic parameter -