List of usage examples for javax.naming.directory SearchResult getAttributes
public Attributes getAttributes()
From source file:org.wso2.carbon.identity.agent.onprem.userstore.manager.ldap.LDAPUserStoreManager.java
/** * {@inheritDoc}//from w ww . ja v a 2s . c om */ public String[] doListUsers(String filter, int maxItemLimit) throws UserStoreException { boolean debug = log.isDebugEnabled(); String[] userNames = new String[0]; if (maxItemLimit == 0) { return userNames; } int givenMax; int searchTime; try { givenMax = Integer.parseInt(userStoreProperties.get(CommonConstants.PROPERTY_MAX_USER_LIST)); } catch (Exception e) { givenMax = CommonConstants.MAX_USER_LIST; } try { searchTime = Integer.parseInt(userStoreProperties.get(CommonConstants.PROPERTY_MAX_SEARCH_TIME)); } catch (Exception e) { searchTime = CommonConstants.MAX_SEARCH_TIME; } if (maxItemLimit <= 0 || maxItemLimit > givenMax) { maxItemLimit = givenMax; } SearchControls searchCtls = new SearchControls(); searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE); searchCtls.setCountLimit(maxItemLimit); searchCtls.setTimeLimit(searchTime); if (filter.contains("?") || filter.contains("**")) { throw new UserStoreException( "Invalid character sequence entered for user search. Please enter valid sequence."); } StringBuilder searchFilter = new StringBuilder( userStoreProperties.get(LDAPConstants.USER_NAME_LIST_FILTER)); String searchBases = userStoreProperties.get(LDAPConstants.USER_SEARCH_BASE); String userNameProperty = userStoreProperties.get(LDAPConstants.USER_NAME_ATTRIBUTE); String serviceNameAttribute = "sn"; StringBuilder finalFilter = new StringBuilder(); // read the display name attribute - if provided String displayNameAttribute = userStoreProperties.get(LDAPConstants.DISPLAY_NAME_ATTRIBUTE); String[] returnedAtts; if (StringUtils.isNotEmpty(displayNameAttribute)) { returnedAtts = new String[] { userNameProperty, serviceNameAttribute, displayNameAttribute }; finalFilter.append("(&").append(searchFilter).append("(").append(displayNameAttribute).append("=") .append(escapeSpecialCharactersForFilterWithStarAsRegex(filter)).append("))"); } else { returnedAtts = new String[] { userNameProperty, serviceNameAttribute }; finalFilter.append("(&").append(searchFilter).append("(").append(userNameProperty).append("=") .append(escapeSpecialCharactersForFilterWithStarAsRegex(filter)).append("))"); } if (debug) { log.debug( "Listing users. SearchBase: " + searchBases + " Constructed-Filter: " + finalFilter.toString()); log.debug("Search controls. Max Limit: " + maxItemLimit + " Max Time: " + searchTime); } searchCtls.setReturningAttributes(returnedAtts); DirContext dirContext = null; NamingEnumeration<SearchResult> answer = null; List<String> list = new ArrayList<>(); try { dirContext = connectionSource.getContext(); // handle multiple search bases String[] searchBaseArray = searchBases.split(CommonConstants.XML_PATTERN_SEPERATOR); for (String searchBase : searchBaseArray) { answer = dirContext.search(escapeDNForSearch(searchBase), finalFilter.toString(), searchCtls); while (answer.hasMoreElements()) { SearchResult sr = answer.next(); if (sr.getAttributes() != null) { log.debug("Result found .."); Attribute attr = sr.getAttributes().get(userNameProperty); // If this is a service principle, just ignore and // iterate rest of the array. The entity is a service if // value of surname is Service Attribute attrSurname = sr.getAttributes().get(serviceNameAttribute); if (attrSurname != null) { if (debug) { log.debug(serviceNameAttribute + " : " + attrSurname); } String serviceName = (String) attrSurname.get(); if (serviceName != null && serviceName.equals(LDAPConstants.SERVER_PRINCIPAL_ATTRIBUTE_VALUE)) { continue; } } if (attr != null) { String name = (String) attr.get(); list.add(name); } } } } userNames = list.toArray(new String[list.size()]); Arrays.sort(userNames); if (debug) { for (String username : userNames) { log.debug("result: " + username); } } } catch (PartialResultException e) { // can be due to referrals in AD. so just ignore error String errorMessage = "Error occurred while getting user list for filter : " + filter + "max limit : " + maxItemLimit; if (isIgnorePartialResultException()) { if (log.isDebugEnabled()) { log.debug(errorMessage, e); } } else { throw new UserStoreException(errorMessage, e); } } catch (NamingException e) { String errorMessage = "Error occurred while getting user list for filter : " + filter + "max limit : " + maxItemLimit; if (log.isDebugEnabled()) { log.debug(errorMessage, e); } throw new UserStoreException(errorMessage, e); } finally { JNDIUtil.closeNamingEnumeration(answer); JNDIUtil.closeContext(dirContext); } return userNames; }
From source file:org.wso2.carbon.identity.agent.onprem.userstore.manager.ldap.LDAPUserStoreManager.java
/** * {@inheritDoc}/*from ww w .j av a2s . c om*/ */ public Map<String, String> getUserPropertyValues(String userName, String[] propertyNames) throws UserStoreException { String userAttributeSeparator = ","; String userDN = null; // read list of patterns from user-mgt.xml String patterns = userStoreProperties.get(LDAPConstants.USER_DN_PATTERN); if (patterns != null && !patterns.isEmpty()) { if (log.isDebugEnabled()) { log.debug("Using User DN Patterns " + patterns); } if (patterns.contains(CommonConstants.XML_PATTERN_SEPERATOR)) { userDN = getNameInSpaceForUserName(userName); } else { userDN = MessageFormat.format(patterns, escapeSpecialCharactersForDN(userName)); } } Map<String, String> values = new HashMap<>(); DirContext dirContext = this.connectionSource.getContext(); String userSearchFilter = userStoreProperties.get(LDAPConstants.USER_NAME_SEARCH_FILTER); String searchFilter = userSearchFilter.replace("?", escapeSpecialCharactersForFilter(userName)); NamingEnumeration<?> answer = null; NamingEnumeration<?> attrs = null; NamingEnumeration<?> allAttrs = null; try { if (userDN != null) { SearchControls searchCtls = new SearchControls(); searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE); if (propertyNames[0].equals(CommonConstants.WILD_CARD_FILTER)) { propertyNames = null; } searchCtls.setReturningAttributes(propertyNames); try { answer = dirContext.search(escapeDNForSearch(userDN), searchFilter, searchCtls); } catch (PartialResultException e) { // can be due to referrals in AD. so just ignore error String errorMessage = "Error occurred while searching directory context for user : " + userDN + " searchFilter : " + searchFilter; if (isIgnorePartialResultException()) { if (log.isDebugEnabled()) { log.debug(errorMessage, e); } } else { throw new UserStoreException(errorMessage, e); } } catch (NamingException e) { String errorMessage = "Error occurred while searching directory context for user : " + userDN + " searchFilter : " + searchFilter; if (log.isDebugEnabled()) { log.debug(errorMessage, e); } throw new UserStoreException(errorMessage, e); } } else { answer = this.searchForUser(searchFilter, propertyNames, dirContext); } assert answer != null; while (answer.hasMoreElements()) { SearchResult sr = (SearchResult) answer.next(); Attributes attributes = sr.getAttributes(); if (attributes != null) { for (allAttrs = attributes.getAll(); allAttrs.hasMore();) { Attribute attribute = (Attribute) allAttrs.next(); if (attribute != null) { StringBuilder attrBuffer = new StringBuilder(); for (attrs = attribute.getAll(); attrs.hasMore();) { Object attObject = attrs.next(); String attr = null; if (attObject instanceof String) { attr = (String) attObject; } else if (attObject instanceof byte[]) { //if the attribute type is binary base64 encoded string will be returned attr = new String(Base64.encodeBase64((byte[]) attObject), "UTF-8"); } if (attr != null && attr.trim().length() > 0) { String attrSeparator = userStoreProperties.get(MULTI_ATTRIBUTE_SEPARATOR); if (attrSeparator != null && !attrSeparator.trim().isEmpty()) { userAttributeSeparator = attrSeparator; } attrBuffer.append(attr).append(userAttributeSeparator); } String value = attrBuffer.toString(); /* * Length needs to be more than userAttributeSeparator.length() for a valid * attribute, since we * attach userAttributeSeparator */ if (value.trim().length() > userAttributeSeparator.length()) { value = value.substring(0, value.length() - userAttributeSeparator.length()); values.put(attribute.getID(), value); } } } } } } } catch (NamingException e) { String errorMessage = "Error occurred while getting user property values for user : " + userName; if (log.isDebugEnabled()) { log.debug(errorMessage, e); } throw new UserStoreException(errorMessage, e); } catch (UnsupportedEncodingException e) { String errorMessage = "Error occurred while Base64 encoding property values for user : " + userName; if (log.isDebugEnabled()) { log.debug(errorMessage, e); } throw new UserStoreException(errorMessage, e); } finally { // close the naming enumeration and free up resource JNDIUtil.closeNamingEnumeration(attrs); JNDIUtil.closeNamingEnumeration(answer); // close directory context JNDIUtil.closeContext(dirContext); } return values; }
From source file:de.acosix.alfresco.mtsupport.repo.auth.ldap.EnhancedLDAPUserRegistry.java
/** * * {@inheritDoc}/*from www . j a v a 2 s . c om*/ */ @Override public String resolveDistinguishedName(final String userId, final AuthenticationDiagnostic diagnostic) throws AuthenticationException { LOGGER.debug("resolveDistinguishedName userId: {}", userId); final SearchControls userSearchCtls = new SearchControls(); userSearchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE); // Although we don't actually need any attributes, we ask for the UID for compatibility with Sun Directory Server. See ALF-3868 userSearchCtls.setReturningAttributes(new String[] { this.userIdAttributeName }); final String query = this.userSearchBase + "(&" + this.personQuery + "(" + this.userIdAttributeName + "= userId))"; NamingEnumeration<SearchResult> searchResults = null; SearchResult result = null; InitialDirContext ctx = null; try { ctx = this.ldapInitialContextFactory.getDefaultIntialDirContext(diagnostic); // Execute the user query with an additional condition that ensures only the user with the required ID is // returned. Force RFC 2254 escaping of the user ID in the filter to avoid any manipulation searchResults = ctx.search(this.userSearchBase, "(&" + this.personQuery + "(" + this.userIdAttributeName + "={0}))", new Object[] { userId }, userSearchCtls); if (searchResults.hasMore()) { result = searchResults.next(); final Attributes attributes = result.getAttributes(); final Attribute uidAttribute = attributes.get(this.userIdAttributeName); if (uidAttribute == null) { if (this.errorOnMissingUID) { throw new AlfrescoRuntimeException( "User returned by user search does not have mandatory user id attribute " + attributes); } else { LOGGER.warn("User returned by user search does not have mandatory user id attribute {}", attributes); } } // MNT:2597 We don't trust the LDAP server's treatment of whitespace, accented characters etc. We will // only resolve this user if the user ID matches else if (userId.equalsIgnoreCase((String) uidAttribute.get(0))) { final String name = result.getNameInNamespace(); this.commonCloseSearchResult(result); result = null; return name; } this.commonCloseSearchResult(result); result = null; } final Object[] args = { userId, query }; diagnostic.addStep(AuthenticationDiagnostic.STEP_KEY_LDAP_LOOKUP_USER, false, args); throw new AuthenticationException("authentication.err.connection.ldap.user.notfound", args, diagnostic); } catch (final NamingException e) { // Connection is good here - AuthenticationException would be thrown by ldapInitialContextFactory final Object[] args1 = { userId, query }; diagnostic.addStep(AuthenticationDiagnostic.STEP_KEY_LDAP_SEARCH, false, args1); // failed to search final Object[] args = { e.getLocalizedMessage() }; throw new AuthenticationException("authentication.err.connection.ldap.search", diagnostic, args, e); } finally { this.commonAfterQueryCleanup(searchResults, result, ctx); } }
From source file:org.wso2.carbon.user.core.ldap.ReadWriteLDAPUserStoreManager.java
/** * Check whether user is in the group by searching through its member attributes. * * @param userDN/*from w ww. ja va 2s . c o m*/ * @param groupEntry * @return * @throws UserStoreException */ protected boolean isUserInRole(String userDN, SearchResult groupEntry) throws UserStoreException { boolean isUserInRole = false; try { Attributes groupAttributes = groupEntry.getAttributes(); if (groupAttributes != null) { // get group's returned attributes NamingEnumeration attributes = groupAttributes.getAll(); // loop through attributes while (attributes.hasMoreElements()) { Attribute memberAttribute = (Attribute) attributes.next(); String memberAttributeName = realmConfig .getUserStoreProperty(LDAPConstants.MEMBERSHIP_ATTRIBUTE); if (memberAttributeName.equalsIgnoreCase(memberAttribute.getID())) { // loop through attribute values for (int i = 0; i < memberAttribute.size(); i++) { if (userDN.equalsIgnoreCase((String) memberAttribute.get(i))) { return true; } } } } attributes.close(); } } catch (NamingException e) { String errorMessage = "Error occurred while looping through attributes set of group: " + groupEntry.getNameInNamespace(); if (log.isDebugEnabled()) { log.debug(errorMessage, e); } throw new UserStoreException(errorMessage, e); } return isUserInRole; }
From source file:org.wso2.carbon.user.core.ldap.ReadWriteLDAPUserStoreManager.java
/** * Check whether this is the last/only user in this group. * * @param userDN/* w w w.j a v a 2 s.co m*/ * @param groupEntry * @return groupContext */ @SuppressWarnings("rawtypes") protected boolean isOnlyUserInRole(String userDN, SearchResult groupEntry) throws UserStoreException { boolean isOnlyUserInRole = false; try { Attributes groupAttributes = groupEntry.getAttributes(); if (groupAttributes != null) { NamingEnumeration attributes = groupAttributes.getAll(); while (attributes.hasMoreElements()) { Attribute memberAttribute = (Attribute) attributes.next(); String memberAttributeName = realmConfig .getUserStoreProperty(LDAPConstants.MEMBERSHIP_ATTRIBUTE); String attributeID = memberAttribute.getID(); if (memberAttributeName.equals(attributeID)) { if (memberAttribute.size() == 1 && userDN.equals(memberAttribute.get())) { return true; } } } attributes.close(); } } catch (NamingException e) { String errorMessage = "Error occurred while looping through attributes set of group: " + groupEntry.getNameInNamespace(); if (log.isDebugEnabled()) { log.debug(errorMessage, e); } throw new UserStoreException(errorMessage, e); } return isOnlyUserInRole; }
From source file:dk.magenta.ldap.LDAPMultiBaseUserRegistry.java
public String resolveDistinguishedName(String userId, AuthenticationDiagnostic diagnostic) throws AuthenticationException { if (logger.isDebugEnabled()) { logger.debug("resolveDistinguishedName userId:" + userId); }/* w ww . j av a 2 s .c o m*/ SearchControls userSearchCtls = new SearchControls(); userSearchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE); // Although we don't actually need any attributes, we ask for the UID for compatibility with Sun Directory Server. See ALF-3868 userSearchCtls.setReturningAttributes(new String[] { this.userIdAttributeName }); InitialDirContext ctx = null; for (String userSearchBase : this.userSearchBases) { String query = userSearchBase + "(&" + this.personQuery + "(" + this.userIdAttributeName + "= userId))"; NamingEnumeration<SearchResult> searchResults = null; SearchResult result = null; try { ctx = this.ldapInitialContextFactory.getDefaultIntialDirContext(diagnostic); // Execute the user query with an additional condition that ensures only the user with the required ID is // returned. Force RFC 2254 escaping of the user ID in the filter to avoid any manipulation searchResults = ctx.search(userSearchBase, "(&" + this.personQuery + "(" + this.userIdAttributeName + "={0}))", new Object[] { userId }, userSearchCtls); if (searchResults.hasMore()) { result = searchResults.next(); Attributes attributes = result.getAttributes(); Attribute uidAttribute = attributes.get(this.userIdAttributeName); if (uidAttribute == null) { if (this.errorOnMissingUID) { throw new AlfrescoRuntimeException( "User returned by user search does not have mandatory user id attribute " + attributes); } else { LDAPMultiBaseUserRegistry.logger .warn("User returned by user search does not have mandatory user id attribute " + attributes); } } // MNT:2597 We don't trust the LDAP server's treatment of whitespace, accented characters etc. We will // only resolve this user if the user ID matches else if (userId.equalsIgnoreCase((String) uidAttribute.get(0))) { String name = result.getNameInNamespace(); // Close the contexts, see ALF-20682 Context context = (Context) result.getObject(); if (context != null) { context.close(); } result = null; return name; } // Close the contexts, see ALF-20682 Context context = (Context) result.getObject(); if (context != null) { context.close(); } result = null; } } catch (NamingException e) { // Connection is good here - AuthenticationException would be thrown by ldapInitialContextFactory Object[] args1 = { userId, query }; diagnostic.addStep(AuthenticationDiagnostic.STEP_KEY_LDAP_SEARCH, false, args1); } if (result != null) { try { Context context = (Context) result.getObject(); if (context != null) { context.close(); } } catch (Exception e) { logger.debug("error when closing result block context", e); } } if (searchResults != null) { try { searchResults.close(); } catch (Exception e) { logger.debug("error when closing searchResults context", e); } } } if (ctx != null) { try { ctx.close(); } catch (NamingException e) { logger.debug("error when closing ldap context", e); } } // failed to search // Object[] args = {e.getLocalizedMessage()}; throw new AuthenticationException("authentication.err.connection.ldap.search", diagnostic); }
From source file:org.alfresco.repo.security.sync.ldap.LDAPUserRegistry.java
public String resolveDistinguishedName(String userId, AuthenticationDiagnostic diagnostic) throws AuthenticationException { if (logger.isDebugEnabled()) { logger.debug("resolveDistinguishedName userId:" + userId); }/* w w w . ja va 2s. c o m*/ SearchControls userSearchCtls = new SearchControls(); userSearchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE); // Although we don't actually need any attributes, we ask for the UID for compatibility with Sun Directory Server. See ALF-3868 userSearchCtls.setReturningAttributes(new String[] { this.userIdAttributeName }); String query = this.userSearchBase + "(&" + this.personQuery + "(" + this.userIdAttributeName + "= userId))"; NamingEnumeration<SearchResult> searchResults = null; SearchResult result = null; InitialDirContext ctx = null; try { ctx = this.ldapInitialContextFactory.getDefaultIntialDirContext(diagnostic); // Execute the user query with an additional condition that ensures only the user with the required ID is // returned. Force RFC 2254 escaping of the user ID in the filter to avoid any manipulation searchResults = ctx.search(this.userSearchBase, "(&" + this.personQuery + "(" + this.userIdAttributeName + "={0}))", new Object[] { userId }, userSearchCtls); if (searchResults.hasMore()) { result = searchResults.next(); Attributes attributes = result.getAttributes(); Attribute uidAttribute = attributes.get(this.userIdAttributeName); if (uidAttribute == null) { if (this.errorOnMissingUID) { throw new AlfrescoRuntimeException( "User returned by user search does not have mandatory user id attribute " + attributes); } else { LDAPUserRegistry.logger .warn("User returned by user search does not have mandatory user id attribute " + attributes); } } // MNT:2597 We don't trust the LDAP server's treatment of whitespace, accented characters etc. We will // only resolve this user if the user ID matches else if (userId.equalsIgnoreCase((String) uidAttribute.get(0))) { String name = result.getNameInNamespace(); // Close the contexts, see ALF-20682 Context context = (Context) result.getObject(); if (context != null) { context.close(); } result = null; return name; } // Close the contexts, see ALF-20682 Context context = (Context) result.getObject(); if (context != null) { context.close(); } result = null; } Object[] args = { userId, query }; diagnostic.addStep(AuthenticationDiagnostic.STEP_KEY_LDAP_LOOKUP_USER, false, args); throw new AuthenticationException("authentication.err.connection.ldap.user.notfound", args, diagnostic); } catch (NamingException e) { // Connection is good here - AuthenticationException would be thrown by ldapInitialContextFactory Object[] args1 = { userId, query }; diagnostic.addStep(AuthenticationDiagnostic.STEP_KEY_LDAP_SEARCH, false, args1); // failed to search Object[] args = { e.getLocalizedMessage() }; throw new AuthenticationException("authentication.err.connection.ldap.search", diagnostic, args, e); } finally { if (result != null) { try { Context context = (Context) result.getObject(); if (context != null) { context.close(); } } catch (Exception e) { logger.debug("error when closing result block context", e); } } if (searchResults != null) { try { searchResults.close(); } catch (Exception e) { logger.debug("error when closing searchResults context", e); } } if (ctx != null) { try { ctx.close(); } catch (NamingException e) { logger.debug("error when closing ldap context", e); } } } }
From source file:org.wso2.carbon.user.core.ldap.ReadWriteLDAPUserStoreManager.java
@Override public void doUpdateCredentialByAdmin(String userName, Object newCredential) throws UserStoreException { DirContext dirContext = this.connectionSource.getContext(); DirContext subDirContext = null; // first search the existing user entry. String searchBase = realmConfig.getUserStoreProperty(LDAPConstants.USER_SEARCH_BASE); String searchFilter = realmConfig.getUserStoreProperty(LDAPConstants.USER_NAME_SEARCH_FILTER); searchFilter = searchFilter.replace("?", escapeSpecialCharactersForFilter(userName)); SearchControls searchControls = new SearchControls(); searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE); searchControls.setReturningAttributes(new String[] { "userPassword" }); NamingEnumeration<SearchResult> namingEnumeration = null; NamingEnumeration passwords = null; try {//from www.j a v a2 s .c om namingEnumeration = dirContext.search(escapeDNForSearch(searchBase), searchFilter, searchControls); // here we assume only one user // TODO: what to do if there are more than one user // there can be only only on user SearchResult searchResult = null; while (namingEnumeration.hasMore()) { searchResult = namingEnumeration.next(); String passwordHashMethod = realmConfig.getUserStoreProperty(PASSWORD_HASH_METHOD); if (!UserCoreConstants.RealmConfig.PASSWORD_HASH_METHOD_PLAIN_TEXT .equalsIgnoreCase(passwordHashMethod)) { Attributes attributes = searchResult.getAttributes(); Attribute userPassword = attributes.get("userPassword"); // When admin changes other user passwords he do not have to // provide the old password. Here it is only possible to have one password, if there // are more every one should match with the given old password passwords = userPassword.getAll(); if (passwords.hasMore()) { byte[] byteArray = (byte[]) passwords.next(); String password = new String(byteArray); if (password.startsWith("{")) { passwordHashMethod = password.substring(password.indexOf('{') + 1, password.indexOf('}')); } } } String dnName = searchResult.getName(); subDirContext = (DirContext) dirContext.lookup(searchBase); Attribute passwordAttribute = new BasicAttribute("userPassword"); passwordAttribute.add( UserCoreUtil.getPasswordToStore((String) newCredential, passwordHashMethod, kdcEnabled)); BasicAttributes basicAttributes = new BasicAttributes(true); basicAttributes.put(passwordAttribute); subDirContext.modifyAttributes(dnName, DirContext.REPLACE_ATTRIBUTE, basicAttributes); } // we check whether both carbon admin entry and ldap connection // entry are the same if (searchResult.getNameInNamespace() .equals(realmConfig.getUserStoreProperty(LDAPConstants.CONNECTION_NAME))) { this.connectionSource.updateCredential((String) newCredential); } } catch (NamingException e) { String errorMessage = "Can not access the directory service for user : " + userName; if (log.isDebugEnabled()) { log.debug(errorMessage, e); } throw new UserStoreException(errorMessage, e); } finally { JNDIUtil.closeNamingEnumeration(passwords); JNDIUtil.closeNamingEnumeration(namingEnumeration); JNDIUtil.closeContext(subDirContext); JNDIUtil.closeContext(dirContext); } }
From source file:org.wso2.carbon.user.core.ldap.ReadWriteLDAPUserStoreManager.java
protected void deleteLDAPRole(RoleContext context) throws UserStoreException { String roleName = context.getRoleName(); String groupSearchFilter = ((LDAPRoleContext) context).getSearchFilter(); groupSearchFilter = groupSearchFilter.replace("?", escapeSpecialCharactersForFilter(context.getRoleName())); String[] returningAttributes = { ((LDAPRoleContext) context).getRoleNameProperty() }; String searchBase = ((LDAPRoleContext) context).getSearchBase(); DirContext mainDirContext = null; DirContext groupContext = null; NamingEnumeration<SearchResult> groupSearchResults = null; try {//from ww w .ja v a 2 s. co m mainDirContext = this.connectionSource.getContext(); groupSearchResults = searchInGroupBase(groupSearchFilter, returningAttributes, SearchControls.SUBTREE_SCOPE, mainDirContext, searchBase); SearchResult resultedGroup = null; while (groupSearchResults.hasMoreElements()) { resultedGroup = groupSearchResults.next(); } if (resultedGroup == null) { throw new UserStoreException("Could not find specified group/role - " + roleName); } String groupName = resultedGroup.getName(); groupContext = (DirContext) mainDirContext.lookup(groupSearchBase); String groupNameAttributeValue = (String) resultedGroup.getAttributes() .get(realmConfig.getUserStoreProperty(LDAPConstants.GROUP_NAME_ATTRIBUTE)).get(); if (groupNameAttributeValue.equals(roleName)) { groupContext.destroySubcontext(groupName); } } catch (NamingException e) { String errorMessage = "Error occurred while deleting the role: " + roleName; if (log.isDebugEnabled()) { log.debug(errorMessage, e); } throw new UserStoreException(errorMessage, e); } finally { JNDIUtil.closeNamingEnumeration(groupSearchResults); JNDIUtil.closeContext(groupContext); JNDIUtil.closeContext(mainDirContext); } }
From source file:org.wso2.carbon.user.core.ldap.ReadWriteLDAPUserStoreManager.java
/** * Update the set of users belong to a LDAP role. * * @param roleName//from w w w.j a v a 2 s.com * @param deletedUsers * @param newUsers */ @SuppressWarnings("deprecation") @Override public void doUpdateUserListOfRole(String roleName, String[] deletedUsers, String[] newUsers) throws UserStoreException { String errorMessage = null; NamingEnumeration<SearchResult> groupSearchResults = null; LDAPRoleContext ctx = (LDAPRoleContext) createRoleContext(roleName); roleName = ctx.getRoleName(); String searchFilter = ctx.getSearchFilter(); if (isExistingLDAPRole(ctx)) { DirContext mainDirContext = this.connectionSource.getContext(); try { searchFilter = searchFilter.replace("?", escapeSpecialCharactersForFilter(roleName)); String membershipAttributeName = realmConfig .getUserStoreProperty(LDAPConstants.MEMBERSHIP_ATTRIBUTE); String[] returningAttributes = new String[] { membershipAttributeName }; String searchBase = ctx.getSearchBase(); groupSearchResults = searchInGroupBase(searchFilter, returningAttributes, SearchControls.SUBTREE_SCOPE, mainDirContext, searchBase); SearchResult resultedGroup = null; String groupName = null; while (groupSearchResults.hasMoreElements()) { resultedGroup = groupSearchResults.next(); groupName = resultedGroup.getName(); } // check whether update operations are going to violate non // empty role // restriction specified in user-mgt.xml by // checking whether all users are trying to be deleted // before updating LDAP. Attribute returnedMemberAttribute = resultedGroup.getAttributes().get(membershipAttributeName); if (!emptyRolesAllowed && newUsers.length - deletedUsers.length + returnedMemberAttribute.size() == 0) { errorMessage = "There should be at least one member in the role. " + "Hence can not delete all the members."; throw new UserStoreException(errorMessage); } else { List<String> newUserList = new ArrayList<String>(); List<String> deleteUserList = new ArrayList<String>(); if (newUsers != null && newUsers.length != 0) { String invalidUserList = ""; String existingUserList = ""; for (String newUser : newUsers) { if (StringUtils.isEmpty(newUser)) { continue; } String userNameDN = getNameInSpaceForUserName(newUser); if (userNameDN == null) { invalidUserList += newUser + " "; } else if (isUserInRole(userNameDN, resultedGroup)) { existingUserList += userNameDN + ","; } else { newUserList.add(userNameDN); } } if (!StringUtils.isEmpty(invalidUserList) || !StringUtils.isEmpty(existingUserList)) { errorMessage = (StringUtils.isEmpty(invalidUserList) ? "" : "'" + invalidUserList + "' not in the user store. ") + (StringUtils.isEmpty(existingUserList) ? "" : "'" + existingUserList + "' already belong to the role : " + roleName); throw new UserStoreException(errorMessage); } } if (deletedUsers != null && deletedUsers.length != 0) { String invalidUserList = ""; for (String deletedUser : deletedUsers) { if (StringUtils.isEmpty(deletedUser)) { continue; } String userNameDN = getNameInSpaceForUserName(deletedUser); if (userNameDN == null) { invalidUserList += deletedUser + ","; } else { deleteUserList.add(userNameDN); } } if (!StringUtils.isEmpty(invalidUserList)) { errorMessage = "'" + invalidUserList + "' not in the user store."; throw new UserStoreException(errorMessage); } } for (String userNameDN : newUserList) { modifyUserInRole(userNameDN, groupName, DirContext.ADD_ATTRIBUTE, searchBase); } for (String userNameDN : deleteUserList) { modifyUserInRole(userNameDN, groupName, DirContext.REMOVE_ATTRIBUTE, searchBase); // needs to clear authz cache for deleted users userRealm.getAuthorizationManager().clearUserAuthorization(userNameDN); } } } catch (NamingException e) { errorMessage = "Error occurred while modifying the user list of role: " + roleName; if (log.isDebugEnabled()) { log.debug(errorMessage, e); } throw new UserStoreException(errorMessage, e); } finally { JNDIUtil.closeNamingEnumeration(groupSearchResults); JNDIUtil.closeContext(mainDirContext); } } else { errorMessage = "The role: " + roleName + " does not exist."; if (log.isDebugEnabled()) { log.debug(errorMessage); } throw new UserStoreException(errorMessage); } }