Tuesday, August 16, 2016

Add/Remove Role to User through X++ code AX2012

Hi guys. We had a requirement where I had to provide SysAdmin role to the current user for the task which he is performing and once it is done then the role had to be removed. As ever google came to help big time and finally my code is ready:

Method to add role:

private void grantAdminRole()
{
    SecurityRole        role;
    SecurityUserRole    userRole;
    boolean             added;
    UserInfo            userInfo;

    select role where role.Name == 'System Administrator';

    select * from userRole
        where userRole.SecurityRole == role.RecId &&
            userRole.User == curUserId();

    if (!userRole || (userRole.AssignmentStatus != RoleAssignmentStatus::Enabled))
    {
        userRole.User = curUserId();
        userRole.SecurityRole = role.RecId;
        userRole.AssignmentMode = RoleAssignmentMode::Manual;
        userRole.AssignmentStatus = RoleAssignmentStatus::Enabled;
        SecuritySegregationOfDuties::assignUserToRole(userRole, null);
    }
}


Method to remove the role from user:

private void revokeAdminRole()
{
    fieldName                           userId;
    SysSecTreeRoles                     roleTree;
    SecurityUserRole                    securityUserRole;
    OMUserRoleOrganization              org;
    SecurityUserRoleCondition           condition;
    SecuritySegregationOfDutiesConflict conflict;
    SecurityRole                        role;

    ttsbegin;

    select role where role.Name == 'System Administrator';

    delete_from condition
        exists join securityUserRole
        where condition.SecurityUserRole == securityUserRole.RecId && securityUserRole.User == curUserId() && securityUserRole.SecurityRole == role.RecId;

    select OMInternalOrganization, SecurityRole from org where org.User == curUserId() && org.SecurityRole == role.RecId;

    if (org.SecurityRole)
    {
        EePersonalDataAccessLogging::logUserRoleChange(org.SecurityRole, org.omInternalOrganization, curUserId(), AddRemove::Remove);
    }

    delete_from org where org.User == curUserId() && org.SecurityRole == role.RecId;

    delete_from conflict where conflict.User == curUserId() && ((conflict.ExistingRole == role.RecId) || (conflict.NewRole == role.RecId));

    //<GEEEE>
    EePersonalDataAccessLogging::logUserRoleChange(role.RecId, 0, curUserId(), AddRemove::Remove);
    //</GEEEE>

    delete_from securityUserRole where securityUserRole.User == curUserId() && securityUserRole.SecurityRole == role.RecId;

    ttscommit;

}

No comments:

Post a Comment