Create User Tokens

We need to create a secret token that will allow us to verify that a user does indeed have permission to modify a resource.

  1. Create a test:

    test/users/models.js

     //...
    
     var UserToken = require('../../users/models').UserToken;
    
     //...
    
     describe('Users: models', function () {
    
       //...
    
       describe('UserToken', function () {
    
         describe('#new', function () {
           var userId = '000000000000000000000001';
           UserToken.new(userId, function (err, userToken) {
             // Confirm that that an error does not exist
             should.not.exist(err);
             should.exist(userToken.token);
             // the userId is a Schema.ObjectId so to test against our string
             // we need to convert it to a string
             userToken.userId.toString().should.equal(userId);
           });
         });
    
       });
     });
    
    
  2. Create the UserToken and the new method:

    users/models.js

     //... imports
     var crypto = require('crypto');
    
     var UserToken;
    
     //... code
    
     // define the userTokenSchema
     var userTokenSchema = new Schema({
       // We will be looking up the UserToken by userId and token so we need
       // to add and index to these properties to speed up queries.
       userId: {type: Schema.ObjectId, index: true},
       token: {type: String, index: true}
     });
    
     userTokenSchema.statics.new = function (userId, fn) {
       var user = new UserToken();
       // create a random string
       crypto.randomBytes(48, function (ex, buf) {
         // make the string url safe
         var token = buf.toString('base64').replace(/\//g, '_').replace(/\+/g, '-');
         // embed the userId in the token, and shorten it
         user.token = userId + '|' + token.toString().slice(1, 24);
         user.userId = userId;
         user.save(fn);
       });
     };
    
     // Export the UserToken model
     exports.UserToken = UserToken = mongoose.model('UserToken', userTokenSchema);
    

Resources:

Comments