Monday 24 June 2013

CRM 2011: Using FetchXML with JavaScript to check for a user privilege client side

I recently had the need to perform a client side check if a user had Create privilege on the Account entity.  I knew it should be simple to create a FetchXML query to find this information, so all I needed was to execute this FetchXML query from the form.   There are a number of handy JavaScript libraries to to execute FetchXML and I decided to go with the XrmSvcToolkit.

So here is my new FetchXML privilege check function using the XrmSvcToolkit.

function HasUserPrivilage(UserId, PrivilageName) {
    var hasPrivilege = false;
    var fetchXml = "<fetch mapping='logical' version='1.0'>"
            + "<entity name='privilege'>"
            + "<attribute name='accessright' />"
            + "<attribute name='name' />"
            + "<filter>"
            + "<condition attribute='name' operator='eq' value='" + PrivilageName + "' />"
            + "</filter>"
            + "<link-entity name='roleprivileges' from='privilegeid' to='privilegeid'>"
            + "<link-entity name='role' from='parentrootroleid' to='roleid'>"
            + "<link-entity name='systemuserroles' from='roleid' to='roleid'>"
            + "<filter>"
            + "<condition attribute='systemuserid' operator='eq' value='" + UserId + "' />"
            + "</filter>"
            + "</link-entity>"
            + "</link-entity>"
            + "</link-entity>"
            + "</entity>"
            + "</fetch>";

    XrmSvcToolkit.fetch({
        fetchXml: fetchXml,
        async: false,
        successCallback: function (result) {
            if (result.entities.length > 0) {
                hasPrivilege = true;
            } else {
                hasPrivilege = false;
            }
        },
        errorCallback: function (error) {
            throw error;
        }
    });
    return hasPrivilege;
}

And usage

HasUserPrivilage(Xrm.Page.context.getUserId(), "prvCreateAccount");

2 comments:

  1. Thanks you so much, I could not figure out why i wasn't getting privileges back for user with roles not in the root business unit.

    ReplyDelete