I store some fields on User model that should never be edited by users themselves, but instead should be updated by backend only. So I do validation on beforeSave:
// import all models
var Models = require('cloud/models/index');
// Models.User is a subclass of Parse.User
Parse.Cloud.beforeSave(Models.User, function (request, response) {
var user = request.object;
// prevent numberOfApples from being modified on clients
if(user.existed()) {
if(user.dirty('numberOfApples')) {
response.error('User is not allowed to modify numberOfApples.');
return;
}
}
response.success();
});
So I check if model existed before, this is important so this stuff does not trigger on sign up. But then I tried to update that field manually from Parse dashboard and it throws error. How can I make sure that only user is disallowed to edit this field, while dashboard or backend can do that (apparently when master key is used).
Turns out Request.master
is the way to go here. I allow locked fields to be changed when using master key.
Example:
Parse.Cloud.beforeSave(Models.User, function (request, response) {
var user = request.object;
// prevent system managed fields from being modified on clients
if(user.existed()) {
// we can change those fields when using master key.
if(!request.master) {
var privateFields = [ 'gold', 'skillLevel', 'weaponCount' ];
for(var i = 0, c = privateFields.length; i < c; i++) {
var field = privateFields[i];
if(user.dirty(field)) {
response.error('User is not allowed to modify ' + field + '.');
return;
}
}
}
}
response.success();
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With