schmidlop
schmidlop

Reputation: 1406

SailsJS: set the status code on an error coming from lifecycle callbacks

I am using the lifecycle callbacks to validate user authorization to change specific attributes.

beforeUpdate: function (valuesToUpdate, cb) {

   //details of how authorized is getting set have been omitted
   if(!authorized) return cb("Unauthorized!");
   cb();
}

When the user is not authorized I receive a 400 Bad Request error

{
    msg: "Unauthorized!"
}

I'd like to return a 403 Forbidden. Is there anyway in SailsJS to control the error returned more precisely?

Update: I am using sails v0.10.5

Upvotes: 3

Views: 755

Answers (1)

Gadelkareem
Gadelkareem

Reputation: 1087

You need to send an instance of WLValidationError to be sent as validation error

//in api/models/User.js
function validationError(invalidAttributes, status, message) {
  var WLValidationError = require('../../node_modules/sails/node_modules/waterline/lib/waterline/error/WLValidationError.js');
  return new WLValidationError({
      invalidAttributes: invalidAttributes,
      status: status,
      message: message
    }
  );
}
var User = {
  attributes: {
    //...
  },
  ownValidate:: function (values, update, cb) {
    //example of not allowed param on update
    //if it is an update then do not allow email param
    if (update && values.email) {
      return cb(validationError({
        email: [
          {
            message: 'Email is not allowed for updates.'
          }
        ]
      }, 403 /*status*/));
    }
    sails.models['user'].findOne(values.email).exec(function (err, user) {
      if (err) return cb(err);
      if (user) {
        return cb(validationError({
          email: [
            {
              value: values.email,
              rule: 'E_UNIQUE'
              /* unique validation message is left for the default one here */
            }
          ]
        }, 409));
      }
    });
  },
  beforeCreate: function (values, cb) {
    return sails.models['user'].ownValidate(values, false, cb);
  },
  beforeUpdate: function (values, cb) {
    return sails.models['user'].ownValidate(values, true, cb);
  }
}

For more info check this

Upvotes: 2

Related Questions