Saturday, April 05, 2014

How to Convert REST Call to SharePoint JSOM Object (ECMAScript)

This simple article tries to explain how we use REST Call and convert to SharePoint JSOM Object that retrieves the permissions associated with a Role, this can be also be used for management of permissions of items.

For this example i created a REST Call that retrieves the Permissions associated with a SharePoint RoleDefinition.
To get the SharePoint RoleDefinition associated using REST can be use the following url: "https://[site]/sites/Dev/_api/Web/RoleDefinitions"


For this example, i use the SharePoint RoleDefinition associated to "Full Control" and get the Permissions associated.

Method to call REST Call with Json (SP.BasePermissions

This example code uses SharePoint REST Calls to get the properties of RoleDefinition “Full Control” that includes a Object (SP.BasePermissions) in Json data.

$.ajax({
    url: "https://[site]/sites/Dev/_api/Web/RoleDefinitions(1073741829)",
    method: "GET",
    headers: { "Accept""application/json; odata=verbose" },
    success: function (data) {
        GetRights(data.d.BasePermissions);
    },
    error: function (xhr) {
        SP.UI.Notify.addNotification(xhr.status + ': ' + xhr.statusText, false);
    }
});

This REST call and returning JSON data can be visible using Fiddler tool as shown in the image below.




Method to convert REST json data to SharePoint JSOM (SP.BasePermissions)

The Method "GetRights(data)" uses the Json data to include in SP.BasePermissions() Object using Method "fromJson()".
After the Object is create it's listed the Permissions "SP.PermissionKind" and validate if the permissions are associated with Role "Full Control" using the Method "has".

Code Example:

function GetRights(rights) {
    var ValidateRights = new SP.BasePermissions();
    var permissionsid = '';
    var permissionsnames = '';
    ValidateRights.fromJson(rights);
    for (var prop in SP.PermissionKind.prototype) {
        permissionsid += prop + "\n";
        if (ValidateRights.has(parseInt(SP.PermissionKind.prototype[prop]))) {
            permissionsnames += prop + "\n";
        }
    }
    alert(permissionsid);
    alert(permissionsnames);

}

All the permissions are collected in a String and display in the alert message.



The List of Permissions can be Listed using the SP.PermissionKind Object.


PS: fullMask permision doesn't get all the permissions but only permissions lower then "Low=65535" in 32 Binary and High="32767" in 64 Binary from the SP.PermissionKind.prototype array list
Low(32):
65: 0000065535: 0000000000000001111111111111111: FullMask
High(64):
65: 0000032767: 0000000000000000111111111111111: FullMask

But the explanation of this values and how get the Realfullmask permission value will be explained in another article with the help of my colleague “Selim Gezgin”.

Hope you like this article, 
Kind regards, 
André Lage

No comments: