jspears / mers

Mongoose Express Rest Service
MIT License
342 stars 42 forks source link

How can I protect UPDATE, DELETE, INSERT endpoints with authentication? #25

Closed dht closed 10 years ago

jspears commented 10 years ago

mers doesn't handle that bit, however it works fine with http://passportjs.org/. Just need to make sure that the auth is defined before mers. You can use filters if you want to do application logic filtering in there. I should do an example of that

app.post('/rest/*',
  passport.authenticate('local'),
  function(req, res) {
    // If this function gets called, authentication was successful.
    // `req.user` contains the authenticated user.
    res.redirect('/users/' + req.user.username);
  });

app.use('/rest', mers.rest(...))
pehaada commented 10 years ago

I did the following using passport to secure the app. As the app grows I can make this more modular if needed. Basically ever request coming in is checked against the "Authenicated" user.

//Secure Express Back End by calling SPAuth on all requests
    app.all('/*',auth.SPAuth);
    app.use('/rest', mers({uri: config.db}).rest());

//Check to see if the user is logged in before allowing the API to return a result.
exports.SPAuth = function (req, res, next) {
           // Control Security on Routes
            if (!req.isAuthenticated()) {
                console.log("No API access user is not Authenicated");
                res.status(404).send("I'm Sorry you need to be logged in.");

            }
            else {
                // TODO: Inject a function to handle is the User has the proper role to be accessing the API

                // TODO: Does the user have access to the data how do we handle if the user can access a given "Counties" data. This is an issue if we will share a single database.

                //USER is Authenticated call the NEXT () function to allow the user to continue
                console.log("UserID: " + req.user._id + " Authenticated");
                next();
            }

};
jspears commented 10 years ago

Thanks, for writing it up. Will add to the help somewhere.