How to Change User Role Programatically

Environment

Service Business Logic, Users
Feature Cloud Functions, Cloud Code for Data

Description

Frequently you need to set programmatically the role of a user account based on certain logic. For example, when the user achieves certain rank or performs an in-app purchase. This requires administrative privileges for the app and can be achieved with server-side logic.

Solution

You can add such logic to the business logic layer - for example you may expose a Cloud Function available to administrattors only or after a user account is created - check for certain conditions and update the role.

Updating a user role requires the use of a Master Key - it is strongly recommended not to include your Master Key inside your app code - therefore a perfect solution is to use Cloud Code as the code stays on Telerik Platform server.

Here is an example using the JavaScript SDK in the Cloud Code to change the user role:

    // Set the new user role (the roleID of your custom role)
    // Get the userId to which the new role will be applied.
    var customRoleId = 'custom-role-id-here';
    var userId = 'user-id-here';

    // Check if the user is eligible for role change (matches a condition you have set) 
    if ('your-condition') {

        // Create an Everlive instance authorized with a Master Key. The Master Key is needed to modify the user role.
        var everliveWithMasterKey = Everlive.Sdk.withMasterKey();

        // Update the user role by setting its roleId.
        everliveWithMasterKey.Users.updateSingle({ 'Id': userId, 'Role': customRoleId },
            function(data) {
                // Exit after the role was modified
                done();
            },
            function(error) {
                console.log(JSON.stringify(error));
                // The role was not modified. Exit the function.
                done();
            });

    } else {
        // The user is not eligible for role change. Exit the function.
        done();
    }

Notes

If you decide to go with a Cloud function, you can set permisions on who can execute Cloud Functions in order to achieve better security. For example, you can allow only users with an "Administrator" role to be able to invoke the Cloud function.

See Also

Start a free trial Request a demo
Contact us: +1-888-365-2779
sales@telerik.com
Copyright © 2016-2017, Progress Software Corporation and/or its subsidiaries or affiliates. All Rights Reserved.