title: Node.js API - Allow users to only update and delete their own object
body: <p>I am trying to build a RESTful API using Node.js w/ Express. I am fairly new to the MEAN stack, and want to use best practices. The concept I'm having trouble grasping and implementing is the following:</p>
  
  <p><strong>Restricting routes like PUT and DELETE on a user object, to only allow requests from users who 'own' this object.</strong></p>
  
  <p>One possibility I've thought of:</p>
  
  <h3>Creating secret token for users that matches token in DB</h3>
  
  <p>So when creating a user I assign them a token, store this in the DB and attach it to their session data.</p>
  
  <p>Then my middleware would look something like:</p>
  
  <pre><code>router.put('/api/users/:user_id', function(req, res, next) {
    // already unclear how this token should be transfered 
    var token = req.headers['x-access-token'] || req.session.token;
  
    // update user (PUT /api/users/:user_id)
    User.findById(req.params.user_id, function(err, user) {
      if (err) {
        res.send(err);
      } else if (user.token != token) {
        res.json({ sucess: false, message: 'User not same as authenticated user.' });
      } else {
  
        // set new information only if present in request
        if (req.body.name) user.name         = req.body.name;
        if (req.body.username) user.username = req.body.username;
        ...
  
        // save user
        user.save(function(err) {
          if (err) res.send(err);
  
          // return message
          res.json({ message: 'User updated.' });
        });
      }
  });
  </code></pre>
  
  <h3>Questions I have regarding best practice</h3>
  
  <ul>
  <li>Is the scenario I thought of at all plausible?</li>
  <li>What data should I use to create a unique token for a user? </li>
  <li>Is storing the token in the session the best solution?</li>
  </ul>
  
  <h3>Sidenote</h3>
  
  <p>This is a learning project for me, and I am aware of libraries like Passport.js. I want to learn the fundamentals first.</p>
  
  <p>I have a repo for this project if you need to see some of the surrounding code I'm using: <a href="https://github.com/messerli90/node-api-ownership" rel="nofollow">https://github.com/messerli90/node-api-ownership</a></p>
  
  <p><strong>Edit</strong></p>
  
  <p>I would accept a good RESTful API book recommendation, where these points are covered, as an answer. </p>
  
  <p><strong>Edit 2</strong></p>
  
  <p>I actually found a lot of the answers I was looking for in this tutorial: <a href="http://scottksmith.com/blog/2014/05/29/beer-locker-building-a-restful-api-with-node-passport/" rel="nofollow">http://scottksmith.com/blog/2014/05/29/beer-locker-building-a-restful-api-with-node-passport/</a></p>
  
  <p>I was trying to do this without the use of passport.js but a lot of the concepts covered in the article made some of the mechanics of an authorized API clear to me.</p>