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; }
Preview:
downloadDownload PNG
downloadDownload JPEG
downloadDownload SVG
Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!
Click to optimize width for Twitter