Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Restrict users from updating certain fields but allow backend to edit them

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).

like image 821
Rob Zombie Avatar asked Mar 13 '15 14:03

Rob Zombie


1 Answers

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();
});
like image 127
Rob Zombie Avatar answered Nov 15 '22 05:11

Rob Zombie