Sam
Sam

Reputation: 6552

Sailsjs: How do I transform a POST request's body/fields for the REST API

It is awesome how sails will automatically generate a REST API for me. But, how can I add extra processing to a REST route? For example, I might have a POST /users route to create new users and it accepts a password as one of the attributes for the users model. But, I wouldn't want to store passwords as-is; rather I would want to hash passwords and salt them for better security. Is there a way to write code before the REST API handles the request so that way I can transform the input or do some kind of processing in general if need be?

Upvotes: 2

Views: 240

Answers (1)

jaumard
jaumard

Reputation: 8292

You can implement beforeValidate or beforeCreate method under your user model Check out the doc here http://www.sailsjs.org/#!/documentation/concepts/ORM/Lifecyclecallbacks.html

I use this for hash password :

/**
 * User.js
 *
 * @description :: TODO: You might write a short summary of how this model works and what it represents here.
 * @docs        :: http://sailsjs.org/#!documentation/models
 */
module.exports = {
  attributes   : {
    name     : 'string',
    password : {
      type      : 'string',
      required  : true,
      minLength : 6
    },
    email    : {
      type     : 'email',
      unique   : true,
      required : true
    },
    toJSON   : function ()
    {
      var obj = this.toObject();
      delete obj.password;
      return obj;
    }
  },
  beforeCreate : function (attrs, next)
  {
    var bcrypt = require('bcrypt');

    bcrypt.genSalt(10, function (err, salt)
    {
      if (err)
      {
        return next(err);
      }

      bcrypt.hash(attrs.password, salt, function (err, hash)
      {
        if (err)
        {
          return next(err);
        }

        attrs.password = hash;
        next();
      });

    });
  }
};

Upvotes: 4

Related Questions