How to Secure Restful Route in Backbone and Express?

How can I secure my express "GET" route in my App so emails and user data can't be exposed to an unauthorized client. I was wondering, should I hash all the fields as I did with password?

My GET "/users" route sends JSON like this..

 {
 "name": "keven",
 "email": "keveng@gmail.com",
 "user": "keven",
 "password": "EEOnGFritH1631671dc8da7431399f824b3925a49e",
 "country": "America",
 "date": "April 20th 2013, 10:34:22 pm",
 "_id": "5173502e5g52676c1b000001"
  }

In my backbone and node/express app I have a url in my backbone collection, like this..

Users = Backbone.Collection.extend({
model: User,
url: '/users',
});

And the express route is like this:

app.get('/users', function(req, res){
User.find({}, function (err, accounts) {
res.send(accounts);
});
});

Thanks.

While this is not ideal, if the user and password are being sent with each request, you simply need some middleware to perform authentication & authorization in your node.js application.

An authentication function:

function authenticate(user, password, fn) {
  // Trivial, but not recommended
  User.findOne({user: user, password: password}, function (err, user) {
    if (err) {
      return fn(err);
    }
    if (!user) {
      return fn(new Error('no such user'));
    }

    return fn(null, user);
  });
}

An authorization middleware function, which relies on authentication:

function authorize(req, res, next) {
  authenticate(req.params.user, req.params.password, function(err, user) {
    if (err) {
      res.redirect('/login');
    }

    // Probably other logic her to determine now *what* they can do

    return next(null, user);
  });
}

Now, since you're using Express, you can make use of the authorization middleware in your route to restrict access:

app.get('/users', authorize, function(req, res){
  // Can only get here if allowed
  User.find({}, function (err, accounts) {
    res.send(accounts);
  });
});

But notice this will be performing a search for the user with each request - one of the reasons I said its not ideal. For proper system security design, you should be looking at using http basic authentication, and session-based cookies or oauth.

Here are some links for you to check out: