Sync User's permission sets

PHOTO EMBED

Tue Nov 08 2022 11:30:02 GMT+0000 (Coordinated Universal Time)

Saved by @Justus #apex

syncUserPermissions('0058d0000020p2jAAA','0058d000005QinC');


/**
 * Method to sync permission sets between users
 */
void syncUserPermissions(Id sourceUserId, Id targetUserId){
	
	// Get the users details
	User sourceUser = [SELECT Id, Profile.UserLicense.Name FROM User WHERE Id =:sourceUserId];
	User targetUser = [SELECT Id, Profile.UserLicense.Name FROM User WHERE Id =:targetUserId];
	
	// This solves a lot of headaches
	if(sourceUser.Profile.UserLicense.Name != targetUser.Profile.UserLicense.Name ){
		throw new StringException('You can only sync users are of the same licence type.');
	}

	// Query PSAs for source user
	PermissionSetAssignment[] sourceUserAssignments = [SELECT PermissionSetId, IsActive FROM PermissionSetAssignment WHERE  
													  	AssigneeId = :sourceUser.Id AND 
													  	PermissionSet.IsOwnedByProfile = false AND 
													  	PermissionSet.License.Name IN(null, :sourceUser.Profile.UserLicense.Name)
													  ];
	// Query PSA's for the target user
	PermissionSetAssignment[] targetUserAssignments = [SELECT PermissionSetId FROM PermissionSetAssignment WHERE AssigneeId = :targetUser.Id AND PermissionSet.IsOwnedByProfile = false ];


	// Clean target user
	delete targetUserAssignments;

	/**
	 * Create the new assignments
	 */
	targetUserAssignments = new PermissionSetAssignment[]{};
	for(PermissionSetAssignment psa : sourceUserAssignments){
		targetUserAssignments.add(
			new PermissionSetAssignment(
				AssigneeId = targetUser.Id,
				PermissionSetId = psa.PermissionSetId
			)
		);
	}
	insert targetUserAssignments;
}
content_copyCOPY