Show TOC

Assigning Users to RolesLocate this document in the navigation structure

Prerequisites

You have imported the required interfaces and gotten the required factories.

More information: User Management Functions for Roles .

Context

This procedure describes how to assign a user to a role programmatically. Use this procedure if you cannot use the existing user administration tools to perform role assignment and need to customize your tools to assign roles programmatically. You can adapt this procedure to assign groups to roles.

Procedure

  1. Use the IUser and IRole interfaces to get the user and role objects.
  2. Check if the user is already directly assigned a member of the role or not.

    This is to avoid AttributeValueAlreadyExistsException . You cannot avoid this risk completely. There is the remote possibility that another application makes the same role assignment in the time between this check and the actual role assignment.

  3. Use the getMutableRole() method to get a modifiable version of the role object.
  4. Use the addMember() method to assign the user to the role.
  5. Commit your changes.

Example

This example gets the user “demo_user” and the role “demo_role” . It then checks if “demo_user” is already directly assigned to “demo_role” . If not the method assigns the user to the role.

public static void modifyRole_setAssignment(String roleUniqueName, String logonID){
	try {

	// Get the user "demo_user" and the role "demo_role".
					
	IUser user = userFactory.getUserByLogonID(logonID);
	IRole role = roleFactory.getRoleByUniqueName(roleUniqueName);

	// Check if the user is already assigned directly to the role. 
				
	if (!role.isMember(user.getUniqueID(), false)) {
					
		//Get a modifiable role object from the UME. 
					
		role = roleFactory.getMutableRole(role.getUniqueID());
					
		// Make the user as direct member of the role.
					
		role.addMember(user.getUniqueID());

		/*
		 * Write the changes to the database.  
		 * Note: If the user was already added to this role on another cluster node
		 * while between the check in the 'if' statement and now,  an
		 * AttributeValueAlreadyExistsException occurs.
		 */
					
		role.save();
		role.commit();
	}
	} catch (NoSuchUserException nsuex) {
		// TODO: Handle NoSuchUserException.
	} catch (NoSuchUserAccountException nsuaex) {
		// TODO: Handle NoSuchUserAccountException.
	} catch (NoSuchRoleException nsrex) {
		// TODO: Handle NoSuchRoleException.
	} catch (AttributeValueAlreadyExistsException avaeex) {
		// TODO: Handle AttributeValueAlreadyExistsException.
	} catch (UMException umex) {
	// TODO: Handle UMException.
	} catch (UMRuntimeException umrex) {
		// TODO: Handle UMRuntimeException.
	}

}