Sails.js Custom Model Does Not Delete Password

I am trying to remove the password from the serial model of the JSON user.

For some reason, my controller is returning res.json({user: myUser}); , returns the full user, including password. Below is my user model. Thoughts?

 # models/User.js var User = { attributes: { username: 'string', password: 'string' }, // Override toJSON method to remove password from API toJSON: function() { var obj = this.toObject(); // BELOW NOT WORKING delete obj.password; return obj; } }; module.exports = User; 
+5
source share
2 answers

You add toJSON as a class method (outside the attributes object); this should be an instance method:

 # models/User.js var User = { attributes: { username: 'string', password: 'string', // Override toJSON method to remove password from API toJSON: function() { var obj = this.toObject(); delete obj.password; return obj; } } }; module.exports = User; 

This will add the toJSON method to each instance of User and will work as you would expect when doing things like res.json() .

+18
source

If one of you spent the last 2 hours hunting for it ... if you use passports, do not forget to remove passwords and accessTokens (unless you need them in your application ...) I just hope this helps someone then save time.

 var User = { attributes: { ... toJSON: function () { var obj = this.toObject(); delete obj.password; delete obj.accessToken; if (obj.passports) { for (var i = 0; i< obj.passports.length; i++) { delete obj.passports[i].password; delete obj.passports[i].accessToken; } } return obj; } } 
0
source

Source: https://habr.com/ru/post/1201618/


All Articles