@@ -51,6 +51,10 @@ public static Result AddUserToGroups([PropertyTab] Input input, [PropertyTab] Co
5151 }
5252 catch ( LdapException ex )
5353 {
54+ if ( ex . ResultCode == LdapException . AttributeOrValueExists && input . UserExistsAction == UserExistsAction . Skip )
55+ {
56+ return new Result ( false , "User already exists in the group, skipped as requested." , input . UserDistinguishedName , input . GroupDistinguishedName ) ;
57+ }
5458 throw new Exception ( $ "AddUserToGroups LDAP error: { ex . Message } ") ;
5559 }
5660 catch ( Exception ex )
@@ -66,44 +70,26 @@ public static Result AddUserToGroups([PropertyTab] Input input, [PropertyTab] Co
6670
6771 private static bool UserExistsInGroup ( LdapConnection connection , string userDn , string groupDn , CancellationToken cancellationToken )
6872 {
69- // Search for the user's groups
73+ cancellationToken . ThrowIfCancellationRequested ( ) ;
74+
7075 ILdapSearchResults searchResults = connection . Search (
7176 groupDn ,
7277 LdapConnection . ScopeSub ,
7378 "(objectClass=*)" ,
7479 null ,
7580 false ) ;
7681
77- // Check if the user is a member of the specified group
78- while ( searchResults . HasMore ( ) )
82+ if ( searchResults . HasMore ( ) )
7983 {
80- cancellationToken . ThrowIfCancellationRequested ( ) ;
81- LdapEntry entry ;
8284 try
8385 {
84- entry = searchResults . Next ( ) ;
85- }
86- catch ( LdapException )
87- {
88- continue ;
86+ var entry = searchResults . Next ( ) ;
87+ var memberAttr = entry . GetAttribute ( "member" ) ;
88+ return memberAttr . StringValueArray . Contains ( userDn , StringComparer . OrdinalIgnoreCase ) ;
8989 }
90-
91- if ( entry != null )
90+ catch ( KeyNotFoundException )
9291 {
93- LdapAttribute memberAttr ;
94-
95- try
96- {
97- memberAttr = entry . GetAttribute ( "member" ) ;
98- }
99- catch ( KeyNotFoundException )
100- {
101- continue ;
102- }
103-
104- var currentMembers = memberAttr . StringValueArray ;
105- if ( currentMembers . Where ( e => e == userDn ) . Any ( ) )
106- return true ;
92+ return false ;
10793 }
10894 }
10995
0 commit comments