List of usage examples for javax.naming NamingEnumeration hasMore
public boolean hasMore() throws NamingException;
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); }//ww w. j a va2s .com 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
/** * Update role list of user by writing to LDAP. * * @param userName//from w w w. j a v a2 s .c om * @param deletedRoles * @param newRoles * @throws UserStoreException */ @SuppressWarnings("deprecation") @Override public void doUpdateRoleListOfUser(String userName, String[] deletedRoles, String[] newRoles) throws UserStoreException { // get the DN of the user entry String userNameDN = this.getNameInSpaceForUserName(userName); String membershipAttribute = realmConfig.getUserStoreProperty(LDAPConstants.MEMBERSHIP_ATTRIBUTE); /* * check deleted roles and delete member entries from relevant groups. */ String errorMessage = null; String roleSearchFilter = null; DirContext mainDirContext = this.connectionSource.getContext(); try { if (deletedRoles != null && deletedRoles.length != 0) { // perform validation for empty role occurrences before // updating in LDAP // check whether this is shared roles and where shared roles are // enable for (String deletedRole : deletedRoles) { LDAPRoleContext context = (LDAPRoleContext) createRoleContext(deletedRole); deletedRole = context.getRoleName(); String searchFilter = context.getSearchFilter(); roleSearchFilter = searchFilter.replace("?", escapeSpecialCharactersForFilter(deletedRole)); String[] returningAttributes = new String[] { membershipAttribute }; String searchBase = context.getSearchBase(); NamingEnumeration<SearchResult> groupResults = searchInGroupBase(roleSearchFilter, returningAttributes, SearchControls.SUBTREE_SCOPE, mainDirContext, searchBase); SearchResult resultedGroup = null; if (groupResults.hasMore()) { resultedGroup = groupResults.next(); } if (resultedGroup != null && isOnlyUserInRole(userNameDN, resultedGroup) && !emptyRolesAllowed) { errorMessage = userName + " is the only user in the role: " + deletedRole + ". Hence can not delete user from role."; throw new UserStoreException(errorMessage); } JNDIUtil.closeNamingEnumeration(groupResults); } // if empty role violation does not happen, continue // updating the LDAP. for (String deletedRole : deletedRoles) { LDAPRoleContext context = (LDAPRoleContext) createRoleContext(deletedRole); deletedRole = context.getRoleName(); String searchFilter = context.getSearchFilter(); if (isExistingRole(deletedRole)) { roleSearchFilter = searchFilter.replace("?", escapeSpecialCharactersForFilter(deletedRole)); String[] returningAttributes = new String[] { membershipAttribute }; String searchBase = context.getSearchBase(); NamingEnumeration<SearchResult> groupResults = searchInGroupBase(roleSearchFilter, returningAttributes, SearchControls.SUBTREE_SCOPE, mainDirContext, searchBase); SearchResult resultedGroup = null; String groupDN = null; if (groupResults.hasMore()) { resultedGroup = groupResults.next(); groupDN = resultedGroup.getName(); } this.modifyUserInRole(userNameDN, groupDN, DirContext.REMOVE_ATTRIBUTE, searchBase); JNDIUtil.closeNamingEnumeration(groupResults); // need to update authz cache of user since roles // are deleted userRealm.getAuthorizationManager().clearUserAuthorization(userName); } else { errorMessage = "The role: " + deletedRole + " does not exist."; throw new UserStoreException(errorMessage); } } } if (newRoles != null && newRoles.length != 0) { for (String newRole : newRoles) { LDAPRoleContext context = (LDAPRoleContext) createRoleContext(newRole); newRole = context.getRoleName(); String searchFilter = context.getSearchFilter(); if (isExistingRole(newRole)) { roleSearchFilter = searchFilter.replace("?", escapeSpecialCharactersForFilter(newRole)); String[] returningAttributes = new String[] { membershipAttribute }; String searchBase = context.getSearchBase(); NamingEnumeration<SearchResult> groupResults = searchInGroupBase(roleSearchFilter, returningAttributes, SearchControls.SUBTREE_SCOPE, mainDirContext, searchBase); SearchResult resultedGroup = null; // assume only one group with given group name String groupDN = null; if (groupResults.hasMore()) { resultedGroup = groupResults.next(); groupDN = resultedGroup.getName(); } if (resultedGroup != null && !isUserInRole(userNameDN, resultedGroup)) { modifyUserInRole(userNameDN, groupDN, DirContext.ADD_ATTRIBUTE, searchBase); } else { errorMessage = "User: " + userName + " already belongs to role: " + groupDN; throw new UserStoreException(errorMessage); } JNDIUtil.closeNamingEnumeration(groupResults); } else { errorMessage = "The role: " + newRole + " does not exist."; throw new UserStoreException(errorMessage); } } } } catch (NamingException e) { errorMessage = "Error occurred while modifying the role list of user: " + userName; if (log.isDebugEnabled()) { log.debug(errorMessage, e); } throw new UserStoreException(errorMessage, e); } finally { JNDIUtil.closeContext(mainDirContext); } }
From source file:org.wso2.carbon.user.core.ldap.ReadWriteLDAPUserStoreManager.java
@Override public void doDeleteUserClaimValues(String userName, String[] claims, String profileName) throws UserStoreException { // get the LDAP Directory context DirContext dirContext = this.connectionSource.getContext(); DirContext subDirContext = null; // search the relevant user entry by user name String userSearchBase = realmConfig.getUserStoreProperty(LDAPConstants.USER_SEARCH_BASE); String userSearchFilter = realmConfig.getUserStoreProperty(LDAPConstants.USER_NAME_SEARCH_FILTER); userSearchFilter = userSearchFilter.replace("?", escapeSpecialCharactersForFilter(userName)); SearchControls searchControls = new SearchControls(); searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE); searchControls.setReturningAttributes(null); NamingEnumeration<SearchResult> returnedResultList = null; String returnedUserEntry = null; try {//w ww . j av a2 s . c o m returnedResultList = dirContext.search(escapeDNForSearch(userSearchBase), userSearchFilter, searchControls); // assume only one user is returned from the search // TODO:what if more than one user is returned if (returnedResultList.hasMore()) { returnedUserEntry = returnedResultList.next().getName(); } } catch (NamingException e) { String errorMessage = "Results could not be retrieved from the directory context for user : " + userName; if (log.isDebugEnabled()) { log.debug(errorMessage, e); } throw new UserStoreException(errorMessage, e); } finally { JNDIUtil.closeNamingEnumeration(returnedResultList); } try { Attributes updatedAttributes = new BasicAttributes(true); // if there is no attribute for profile configuration in LDAP, skip // updating it. // get the claimMapping related to this claimURI for (String claimURI : claims) { String attributeName = getClaimAtrribute(claimURI, userName, null); Attribute currentUpdatedAttribute = new BasicAttribute(attributeName); updatedAttributes.put(currentUpdatedAttribute); } subDirContext = (DirContext) dirContext.lookup(userSearchBase); subDirContext.modifyAttributes(returnedUserEntry, DirContext.REMOVE_ATTRIBUTE, updatedAttributes); } catch (Exception e) { handleException(e, userName); } finally { JNDIUtil.closeContext(subDirContext); JNDIUtil.closeContext(dirContext); } }
From source file:org.wso2.carbon.user.core.ldap.ReadWriteLDAPUserStoreManager.java
@Override public void doDeleteUserClaimValue(String userName, String claimURI, String profileName) throws UserStoreException { // get the LDAP Directory context DirContext dirContext = this.connectionSource.getContext(); DirContext subDirContext = null; // search the relevant user entry by user name String userSearchBase = realmConfig.getUserStoreProperty(LDAPConstants.USER_SEARCH_BASE); String userSearchFilter = realmConfig.getUserStoreProperty(LDAPConstants.USER_NAME_SEARCH_FILTER); userSearchFilter = userSearchFilter.replace("?", escapeSpecialCharactersForFilter(userName)); SearchControls searchControls = new SearchControls(); searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE); searchControls.setReturningAttributes(null); NamingEnumeration<SearchResult> returnedResultList = null; String returnedUserEntry = null; try {/*ww w .j a v a 2s. com*/ returnedResultList = dirContext.search(escapeDNForSearch(userSearchBase), userSearchFilter, searchControls); // assume only one user is returned from the search // TODO:what if more than one user is returned if (returnedResultList.hasMore()) { returnedUserEntry = returnedResultList.next().getName(); } } catch (NamingException e) { String errorMessage = "Results could not be retrieved from the directory context for user : " + userName; if (log.isDebugEnabled()) { log.debug(errorMessage, e); } throw new UserStoreException(errorMessage, e); } finally { JNDIUtil.closeNamingEnumeration(returnedResultList); } try { Attributes updatedAttributes = new BasicAttributes(true); // if there is no attribute for profile configuration in LDAP, skip // updating it. // get the claimMapping related to this claimURI String attributeName = null; attributeName = getClaimAtrribute(claimURI, userName, null); Attribute currentUpdatedAttribute = new BasicAttribute(attributeName); updatedAttributes.put(currentUpdatedAttribute); subDirContext = (DirContext) dirContext.lookup(userSearchBase); subDirContext.modifyAttributes(returnedUserEntry, DirContext.REMOVE_ATTRIBUTE, updatedAttributes); } catch (Exception e) { handleException(e, userName); } finally { JNDIUtil.closeContext(subDirContext); JNDIUtil.closeContext(dirContext); } }
From source file:org.wso2.carbon.user.core.ldap.ReadWriteLDAPUserStoreManager.java
@Override public void doSetUserClaimValue(String userName, String claimURI, String value, String profileName) throws UserStoreException { // get the LDAP Directory context DirContext dirContext = this.connectionSource.getContext(); DirContext subDirContext = null; // search the relevant user entry by user name String userSearchBase = realmConfig.getUserStoreProperty(LDAPConstants.USER_SEARCH_BASE); String userSearchFilter = realmConfig.getUserStoreProperty(LDAPConstants.USER_NAME_SEARCH_FILTER); // if user name contains domain name, remove domain name String[] userNames = userName.split(CarbonConstants.DOMAIN_SEPARATOR); if (userNames.length > 1) { userName = userNames[1];// ww w . j a v a 2s. c om } userSearchFilter = userSearchFilter.replace("?", escapeSpecialCharactersForFilter(userName)); SearchControls searchControls = new SearchControls(); searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE); searchControls.setReturningAttributes(null); NamingEnumeration<SearchResult> returnedResultList = null; String returnedUserEntry = null; try { returnedResultList = dirContext.search(escapeDNForSearch(userSearchBase), userSearchFilter, searchControls); // assume only one user is returned from the search // TODO:what if more than one user is returned if (returnedResultList.hasMore()) { returnedUserEntry = returnedResultList.next().getName(); } } catch (NamingException e) { String errorMessage = "Results could not be retrieved from the directory context for user : " + userName; if (log.isDebugEnabled()) { log.debug(errorMessage, e); } throw new UserStoreException(errorMessage, e); } finally { JNDIUtil.closeNamingEnumeration(returnedResultList); } try { Attributes updatedAttributes = new BasicAttributes(true); // if there is no attribute for profile configuration in LDAP, skip // updating it. // get the claimMapping related to this claimURI String attributeName = null; attributeName = getClaimAtrribute(claimURI, userName, null); Attribute currentUpdatedAttribute = new BasicAttribute(attributeName); /* if updated attribute value is null, remove its values. */ if (EMPTY_ATTRIBUTE_STRING.equals(value)) { currentUpdatedAttribute.clear(); } else { if (attributeName.equals("uid") || attributeName.equals("sn")) { currentUpdatedAttribute.add(value); } else { String userAttributeSeparator = ","; String claimSeparator = realmConfig.getUserStoreProperty(MULTI_ATTRIBUTE_SEPARATOR); if (claimSeparator != null && !claimSeparator.trim().isEmpty()) { userAttributeSeparator = claimSeparator; } if (value.contains(userAttributeSeparator)) { StringTokenizer st = new StringTokenizer(value, userAttributeSeparator); while (st.hasMoreElements()) { String newVal = st.nextElement().toString(); if (newVal != null && newVal.trim().length() > 0) { currentUpdatedAttribute.add(newVal.trim()); } } } else { currentUpdatedAttribute.add(value); } } } updatedAttributes.put(currentUpdatedAttribute); // update the attributes in the relevant entry of the directory // store subDirContext = (DirContext) dirContext.lookup(userSearchBase); subDirContext.modifyAttributes(returnedUserEntry, DirContext.REPLACE_ATTRIBUTE, updatedAttributes); } catch (Exception e) { handleException(e, userName); } finally { JNDIUtil.closeContext(subDirContext); JNDIUtil.closeContext(dirContext); } }
From source file:org.apache.ranger.ldapusersync.process.LdapDeltaUserGroupBuilder.java
private void goUpGroupHierarchyLdap(Set<String> groupDNs, int groupHierarchyLevels) throws Throwable { if (groupHierarchyLevels <= 0 || groupDNs.isEmpty()) { return;//ww w . java 2 s. c om } Set<String> nextLevelGroups = new HashSet<String>(); NamingEnumeration<SearchResult> groupSearchResultEnum = null; try { createLdapContext(); int total; // Activate paged results if (pagedResultsEnabled) { ldapContext.setRequestControls( new Control[] { new PagedResultsControl(pagedResultsSize, Control.NONCRITICAL) }); } String groupFilter = "(&(objectclass=" + groupObjectClass + ")"; if (groupSearchFilter != null && !groupSearchFilter.trim().isEmpty()) { String customFilter = groupSearchFilter.trim(); if (!customFilter.startsWith("(")) { customFilter = "(" + customFilter + ")"; } groupFilter += customFilter + "(|"; } StringBuilder filter = new StringBuilder(); for (String groupDN : groupDNs) { filter.append("(").append(groupMemberAttributeName).append("=").append(groupDN).append(")"); } filter.append("))"); groupFilter += filter; LOG.info("extendedAllGroupsSearchFilter = " + groupFilter); for (int ou = 0; ou < groupSearchBase.length; ou++) { byte[] cookie = null; int counter = 0; try { do { groupSearchResultEnum = ldapContext.search(groupSearchBase[ou], groupFilter, groupSearchControls); while (groupSearchResultEnum.hasMore()) { final SearchResult groupEntry = groupSearchResultEnum.next(); if (groupEntry == null) { if (LOG.isInfoEnabled()) { LOG.info("groupEntry null, skipping sync for the entry"); } continue; } counter++; Attribute groupNameAttr = groupEntry.getAttributes().get(groupNameAttribute); if (groupNameAttr == null) { if (LOG.isInfoEnabled()) { LOG.info(groupNameAttribute + " empty for entry " + groupEntry.getNameInNamespace() + ", skipping sync"); } continue; } nextLevelGroups.add(groupEntry.getNameInNamespace()); String gName = (String) groupNameAttr.get(); Attribute groupMemberAttr = groupEntry.getAttributes().get(groupMemberAttributeName); int userCount = 0; if (groupMemberAttr == null || groupMemberAttr.size() <= 0) { LOG.info("No members available for " + gName); continue; } NamingEnumeration<?> userEnum = groupMemberAttr.getAll(); while (userEnum.hasMore()) { String originalUserFullName = (String) userEnum.next(); if (originalUserFullName == null || originalUserFullName.trim().isEmpty()) { continue; } userCount++; originalUserFullName = originalUserFullName.toLowerCase(); if (userNameMap.get(originalUserFullName) != null) { groupUserTable.put(gName, originalUserFullName, userNameMap.get(originalUserFullName)); } else { groupUserTable.put(gName, originalUserFullName, originalUserFullName); } groupNameMap.put(groupEntry.getNameInNamespace().toLowerCase(), gName); } LOG.info("No. of members in the group " + gName + " = " + userCount); } // Examine the paged results control response Control[] controls = ldapContext.getResponseControls(); if (controls != null) { for (int i = 0; i < controls.length; i++) { if (controls[i] instanceof PagedResultsResponseControl) { PagedResultsResponseControl prrc = (PagedResultsResponseControl) controls[i]; total = prrc.getResultSize(); if (total != 0) { LOG.debug("END-OF-PAGE total : " + total); } else { LOG.debug("END-OF-PAGE total : unknown"); } cookie = prrc.getCookie(); } } } else { LOG.debug("No controls were sent from the server"); } // Re-activate paged results if (pagedResultsEnabled) { ldapContext.setRequestControls(new Control[] { new PagedResultsControl(pagedResultsSize, cookie, Control.CRITICAL) }); } } while (cookie != null); LOG.info("LdapDeltaUserGroupBuilder.goUpGroupHierarchyLdap() completed with group count: " + counter); } catch (RuntimeException re) { LOG.error("LdapDeltaUserGroupBuilder.goUpGroupHierarchyLdap() failed with runtime exception: ", re); throw re; } catch (Exception t) { LOG.error("LdapDeltaUserGroupBuilder.goUpGroupHierarchyLdap() failed with exception: ", t); LOG.info("LdapDeltaUserGroupBuilder.goUpGroupHierarchyLdap() group count: " + counter); } } } catch (RuntimeException re) { LOG.error("LdapDeltaUserGroupBuilder.goUpGroupHierarchyLdap() failed with exception: ", re); throw re; } finally { if (groupSearchResultEnum != null) { groupSearchResultEnum.close(); } closeLdapContext(); } goUpGroupHierarchyLdap(nextLevelGroups, groupHierarchyLevels - 1); }
From source file:org.wso2.carbon.user.core.ldap.ReadWriteLDAPUserStoreManager.java
/** * This method overwrites the method in LDAPUserStoreManager. This implements the functionality * of updating user's profile information in LDAP user store. * * @param userName/*from w w w.ja va 2s . c o m*/ * @param claims * @param profileName * @throws UserStoreException */ @Override public void doSetUserClaimValues(String userName, Map<String, String> claims, String profileName) throws UserStoreException { // get the LDAP Directory context DirContext dirContext = this.connectionSource.getContext(); DirContext subDirContext = null; // search the relevant user entry by user name String userSearchBase = realmConfig.getUserStoreProperty(LDAPConstants.USER_SEARCH_BASE); String userSearchFilter = realmConfig.getUserStoreProperty(LDAPConstants.USER_NAME_SEARCH_FILTER); // if user name contains domain name, remove domain name String[] userNames = userName.split(CarbonConstants.DOMAIN_SEPARATOR); if (userNames.length > 1) { userName = userNames[1]; } userSearchFilter = userSearchFilter.replace("?", escapeSpecialCharactersForFilter(userName)); SearchControls searchControls = new SearchControls(); searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE); searchControls.setReturningAttributes(null); NamingEnumeration<SearchResult> returnedResultList = null; String returnedUserEntry = null; try { returnedResultList = dirContext.search(escapeDNForSearch(userSearchBase), userSearchFilter, searchControls); // assume only one user is returned from the search // TODO:what if more than one user is returned if (returnedResultList.hasMore()) { returnedUserEntry = returnedResultList.next().getName(); } } catch (NamingException e) { String errorMessage = "Results could not be retrieved from the directory context for user : " + userName; if (log.isDebugEnabled()) { log.debug(errorMessage, e); } throw new UserStoreException(errorMessage, e); } finally { JNDIUtil.closeNamingEnumeration(returnedResultList); } if (profileName == null) { profileName = UserCoreConstants.DEFAULT_PROFILE; } if (claims.get(UserCoreConstants.PROFILE_CONFIGURATION) == null) { claims.put(UserCoreConstants.PROFILE_CONFIGURATION, UserCoreConstants.DEFAULT_PROFILE_CONFIGURATION); } try { Attributes updatedAttributes = new BasicAttributes(true); for (Map.Entry<String, String> claimEntry : claims.entrySet()) { String claimURI = claimEntry.getKey(); // if there is no attribute for profile configuration in LDAP, // skip updating it. if (claimURI.equals(UserCoreConstants.PROFILE_CONFIGURATION)) { continue; } // get the claimMapping related to this claimURI String attributeName = getClaimAtrribute(claimURI, userName, null); //remove user DN from cache if changing username attribute if (realmConfig.getUserStoreProperty(LDAPConstants.USER_NAME_ATTRIBUTE).equals(attributeName)) { userCache.remove(userName); } // if uid attribute value contains domain name, remove domain // name if (attributeName.equals("uid")) { // if user name contains domain name, remove domain name String uidName = claimEntry.getValue(); String[] uidNames = uidName.split(CarbonConstants.DOMAIN_SEPARATOR); if (uidNames.length > 1) { uidName = uidNames[1]; claimEntry.setValue(uidName); } // claimEntry.setValue(escapeISSpecialCharacters(uidName)); } Attribute currentUpdatedAttribute = new BasicAttribute(attributeName); /* if updated attribute value is null, remove its values. */ if (EMPTY_ATTRIBUTE_STRING.equals(claimEntry.getValue())) { currentUpdatedAttribute.clear(); } else { String userAttributeSeparator = ","; if (claimEntry.getValue() != null && !attributeName.equals("uid") && !attributeName.equals("sn")) { String claimSeparator = realmConfig.getUserStoreProperty(MULTI_ATTRIBUTE_SEPARATOR); if (claimSeparator != null && !claimSeparator.trim().isEmpty()) { userAttributeSeparator = claimSeparator; } if (claimEntry.getValue().contains(userAttributeSeparator)) { StringTokenizer st = new StringTokenizer(claimEntry.getValue(), userAttributeSeparator); while (st.hasMoreElements()) { String newVal = st.nextElement().toString(); if (newVal != null && newVal.trim().length() > 0) { currentUpdatedAttribute.add(newVal.trim()); } } } else { currentUpdatedAttribute.add(claimEntry.getValue()); } } else { currentUpdatedAttribute.add(claimEntry.getValue()); } } updatedAttributes.put(currentUpdatedAttribute); } // update the attributes in the relevant entry of the directory // store subDirContext = (DirContext) dirContext.lookup(userSearchBase); subDirContext.modifyAttributes(returnedUserEntry, DirContext.REPLACE_ATTRIBUTE, updatedAttributes); } catch (Exception e) { handleException(e, userName); } finally { JNDIUtil.closeContext(subDirContext); JNDIUtil.closeContext(dirContext); } }
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 w ww . ja v a 2 s . c o m 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
@SuppressWarnings("rawtypes") @Override//from w ww. j a v a 2s . c om public void doUpdateCredential(String userName, Object newCredential, Object oldCredential) 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 { namingEnumeration = dirContext.search(escapeDNForSearch(searchBase), searchFilter, searchControls); // here we assume only one user // TODO: what to do if there are more than one user SearchResult searchResult = null; String passwordHashMethod = realmConfig.getUserStoreProperty(PASSWORD_HASH_METHOD); while (namingEnumeration.hasMore()) { searchResult = namingEnumeration.next(); 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
@SuppressWarnings("deprecation") @Override/* ww w. j a v a 2 s. c om*/ public void doDeleteUser(String userName) throws UserStoreException { boolean debug = log.isDebugEnabled(); if (debug) { log.debug("Deleting user: " + userName); } // delete user from LDAP group if read-write enabled. String userNameAttribute = realmConfig.getUserStoreProperty(LDAPConstants.USER_NAME_ATTRIBUTE); String searchFilter = realmConfig.getUserStoreProperty(LDAPConstants.USER_NAME_SEARCH_FILTER); searchFilter = searchFilter.replace("?", escapeSpecialCharactersForFilter(userName)); String[] returningUserAttributes = new String[] { userNameAttribute }; DirContext mainDirContext = this.connectionSource.getContext(); NamingEnumeration<SearchResult> userResults = searchInUserBase(searchFilter, returningUserAttributes, SearchControls.SUBTREE_SCOPE, mainDirContext); NamingEnumeration<SearchResult> groupResults = null; DirContext subDirContext = null; try { SearchResult userResult = null; String userDN = null; // here we assume only one user // TODO: what to do if there are more than one user while (userResults.hasMore()) { userResult = userResults.next(); userDN = userResult.getName(); log.debug("User DN: " + userDN); } // LDAP roles of user to delete the mapping List<String> roles = new ArrayList<String>(); String[] externalRoles = doGetExternalRoleListOfUser(userName, "*"); roles.addAll(Arrays.asList(externalRoles)); if (isSharedGroupEnabled()) { String[] sharedRoles = doGetSharedRoleListOfUser(null, userName, "*"); if (sharedRoles != null) { roles.addAll(Arrays.asList(sharedRoles)); } } String[] rolesOfUser = roles.toArray(new String[roles.size()]); if (rolesOfUser.length != 0) { String[] returningGroupAttributes = new String[] { realmConfig.getUserStoreProperty(LDAPConstants.MEMBERSHIP_ATTRIBUTE) }; for (String role : rolesOfUser) { RoleContext context = createRoleContext(role); String searchBase = ((LDAPRoleContext) context).getSearchBase(); searchFilter = ((LDAPRoleContext) context).getSearchFilter(); role = context.getRoleName(); if (role.indexOf("/") > -1) { role = (role.split("/"))[1]; } String grpSearchFilter = searchFilter.replace("?", escapeSpecialCharactersForFilter(role)); groupResults = searchInGroupBase(grpSearchFilter, returningGroupAttributes, SearchControls.SUBTREE_SCOPE, mainDirContext, searchBase); SearchResult groupResult = null; while (groupResults.hasMore()) { groupResult = groupResults.next(); } if (isOnlyUserInRole(userDN, groupResult) && !emptyRolesAllowed) { String errorMessage = "User: " + userName + " is the only user " + "in " + role + "." + "There should be at " + "least one user" + " in the role. Hence can" + " not delete the user."; throw new UserStoreException(errorMessage); } } // delete role list doUpdateRoleListOfUser(userName, rolesOfUser, new String[] {}); } // delete user entry if it exist if (userResult != null && userResult.getAttributes().get(userNameAttribute).get().toString() .toLowerCase().equals(userName.toLowerCase())) { if (log.isDebugEnabled()) { log.debug("Deleting " + userDN + " with search base " + userSearchBase); } subDirContext = (DirContext) mainDirContext.lookup(userSearchBase); subDirContext.destroySubcontext(userDN); } userCache.remove(userName); } catch (NamingException e) { String errorMessage = "Error occurred while deleting the user : " + userName; if (log.isDebugEnabled()) { log.debug(errorMessage, e); } throw new UserStoreException(errorMessage, e); } finally { JNDIUtil.closeNamingEnumeration(groupResults); JNDIUtil.closeNamingEnumeration(userResults); JNDIUtil.closeContext(subDirContext); JNDIUtil.closeContext(mainDirContext); } }