List of usage examples for javax.naming.directory Attribute size
int size();
From source file:de.fiz.ddb.aas.utils.LDAPEngineUtility.java
private Privilege convertLdapGroupToOrgPriv(SearchResult sr) throws NamingException, IllegalAccessException { Privilege vOrgPrivilege = null;/*from w w w . j a va 2 s. c o m*/ String vCnPrivileg = null, vPrivEntryDN = null, vOrgEntryDN = null; PrivilegeEnum vPrivilege; Attribute vAttr; String vMemberRef; String[] vStrs; if (sr != null) { try { // -- Beispiel fr entryDN: // Organisationeles Privileg: // cn=ddb_ingest,o=99900189,o=00001475,dc=ddb,dc=iais,dc=fraunhofer,dc=de // construct privileges vCnPrivileg = (String) sr.getAttributes().get(Constants.ldap_ddbPrivilege_Cn).get(); vPrivilege = this.mapToPrivilege(sr.getAttributes(), Constants.ldap_ddbPrivilege_Cn); // vPrivEntryDN = (vAttr = sr.getAttributes().get("entryDN")) != // null ? String.valueOf(vAttr.get()) : null; // // organizationName vPrivEntryDN = sr.getNameInNamespace(); // liefert das gleiche // wie oben... if ((vPrivilege != null) && (vPrivEntryDN != null)) { // vOrgEntryDN = // vPrivEntryDN.substring(vPrivEntryDN.indexOf(",") + 1, // vPrivEntryDN.indexOf(",dc") ); vOrgEntryDN = vPrivEntryDN.substring(vPrivEntryDN.indexOf(",") + 1); vOrgPrivilege = new Privilege(vPrivilege); vAttr = sr.getAttributes().get(Constants.ldap_ddbPrivilege_Member); for (int i = 0; i < vAttr.size(); i++) { if (((vMemberRef = String.valueOf(vAttr.get(i))) != null) && (vMemberRef.length() > 0)) { if (((vStrs = vMemberRef.split(",")).length >= 1) && ((vStrs = vStrs[0].split("=")).length == 2) && (vStrs[0].trim().equalsIgnoreCase(Constants.ldap_ddbPerson_Id))) { vOrgPrivilege.add(vStrs[1].trim()); } } } } else { LOG.log(Level.WARNING, "Ein fehlerhaftes Privileg: Privileg: ''{0}'', Privileg-Entry: ''{1}''.", new Object[] { vCnPrivileg, vPrivEntryDN }); } } catch (NamingException ex) { LOG.log(Level.SEVERE, "CnPrivileg: '" + vCnPrivileg + "', PrivEntryDN: '" + vPrivEntryDN + "', OrgEntryDN: '" + vOrgEntryDN + "'"); throw ex; } } return vOrgPrivilege; }
From source file:org.wso2.carbon.identity.agent.onprem.userstore.manager.ldap.LDAPUserStoreManager.java
/** * Check whether this is the last/only user in this group. * * @param userDN DN of the User./* w w w . j av a2 s . c om*/ * @param groupEntry SearchResult Representing the Group. * @return true if user is the only one in role, false otherwise. */ 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 = userStoreProperties.get(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:org.wso2.carbon.identity.agent.onprem.userstore.manager.ldap.LDAPUserStoreManager.java
/** * Check whether user is in the group by searching through its member attributes. * * @param userDN DN of the User whose existence in the group is searched. * @param groupEntry SearchResult representation of the Group. * @return true if the user exists in the role, false otherwise. * @throws UserStoreException If an error occurs while retrieving data. *//*from ww w .j a va 2 s .c o m*/ 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 = userStoreProperties.get(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.springframework.ldap.core.DirContextAdapter.java
/** * Compare the existing attribute <code>name</code> with the values on the * array <code>values</code>. The order of the array must be the same order * as the existing multivalued attribute. * <p>/*www . j a va 2s.c o m*/ * Also handles the case where the values have been reset to the original * values after a previous change. For example, changing * <code>[a,b,c]</code> to <code>[a,b]</code> and then back to * <code>[a,b,c]</code> again must result in this method returning * <code>true</code> so the first change can be overwritten with the latest * change. * * @param name Name of the original multi-valued attribute. * @param values Array of values to check if they have been changed. * @return true if there has been a change compared to original attribute, * or a previous update */ private boolean isChanged(String name, Object[] values, boolean orderMatters) { Attribute orig = originalAttrs.get(name); Attribute prev = updatedAttrs.get(name); // values == null and values.length == 0 is treated the same way boolean emptyNewValue = (values == null || values.length == 0); // Setting to empty --------------------- if (emptyNewValue) { // FALSE: if both are null, it is not changed (both don't exist) // TRUE: if new value is null and old value exists (should be // removed) // TODO Also include prev in null check // TODO Also check if there is a single null element if (orig != null) { return true; } return false; } // NOT setting to empty ------------------- // TRUE if existing value is null if (orig == null) { return true; } // TRUE if different length compared to original attributes if (orig.size() != values.length) { return true; } // TRUE if different length compared to previously updated attributes if (prev != null && prev.size() != values.length) { return true; } // Check contents of arrays // Order DOES matter, e.g. first names try { for (int i = 0; i < orig.size(); i++) { Object obj = orig.get(i); // TRUE if one value is not equal if (!(obj instanceof String)) { return true; } if (orderMatters) { // check only the string with same index if (!values[i].equals(obj)) { return true; } } else { // check all strings if (!ArrayUtils.contains(values, obj)) { return true; } } } } catch (NamingException e) { // TRUE if we can't access the value return true; } if (prev != null) { // Also check against updatedAttrs, since there might have been // a previous update try { for (int i = 0; i < prev.size(); i++) { Object obj = prev.get(i); // TRUE if one value is not equal if (!(obj instanceof String)) { return true; } if (orderMatters) { // check only the string with same index if (!values[i].equals(obj)) { return true; } } else { // check all strings if (!ArrayUtils.contains(values, obj)) { return true; } } } } catch (NamingException e) { // TRUE if we can't access the value return true; } } // FALSE since we have compared all values return false; }
From source file:org.cggh.repo.security.sync.ldap.LDAPUserRegistry.java
public Collection<NodeDescription> getGroups(Date modifiedSince) { // Work out whether the user and group trees are disjoint. This may allow us to optimize reverse DN // resolution. final LdapName groupDistinguishedNamePrefix; try {//from w ww .j av a 2 s. com groupDistinguishedNamePrefix = fixedLdapName(this.groupSearchBase.toLowerCase()); } catch (InvalidNameException e) { Object[] params = { this.groupSearchBase.toLowerCase(), e.getLocalizedMessage() }; throw new AlfrescoRuntimeException("synchronization.err.ldap.search.base.invalid", params, e); } final LdapName userDistinguishedNamePrefix; try { userDistinguishedNamePrefix = fixedLdapName(this.userSearchBase.toLowerCase()); } catch (InvalidNameException e) { Object[] params = { this.userSearchBase.toLowerCase(), e.getLocalizedMessage() }; throw new AlfrescoRuntimeException("synchronization.err.ldap.search.base.invalid", params, e); } final boolean disjoint = !groupDistinguishedNamePrefix.startsWith(userDistinguishedNamePrefix) && !userDistinguishedNamePrefix.startsWith(groupDistinguishedNamePrefix); // Choose / generate the query String query; if (modifiedSince == null) { query = this.groupQuery; } else { query = MessageFormat.format(this.groupDifferentialQuery, this.timestampFormat.format(modifiedSince)); } // Run the query and process the results final Map<String, NodeDescription> lookup = new TreeMap<String, NodeDescription>(); processQuery(new AbstractSearchCallback() { // We get a whole new context to avoid interference with cookies from paged results private DirContext ctx = LDAPUserRegistry.this.ldapInitialContextFactory.getDefaultIntialDirContext(); protected void doProcess(SearchResult result) throws NamingException, ParseException { Attributes attributes = result.getAttributes(); Attribute gidAttribute = attributes.get(LDAPUserRegistry.this.groupIdAttributeName); if (gidAttribute == null) { if (LDAPUserRegistry.this.errorOnMissingGID) { Object[] params = { result.getNameInNamespace(), LDAPUserRegistry.this.groupIdAttributeName }; throw new AlfrescoRuntimeException("synchronization.err.ldap.get.group.id.missing", params); } else { LDAPUserRegistry.logger.warn( "Missing GID2 on " + result.getNameInNamespace() + " attributes:" + attributes); return; } } String groupShortName = gidAttribute.get(0).toString(); String gid = "GROUP_" + groupShortName; NodeDescription group = lookup.get(gid); if (group == null) { // Apply the mapped properties to the node description group = mapToNode(LDAPUserRegistry.this.groupAttributeMapping, LDAPUserRegistry.this.groupAttributeDefaults, result); // Make sure the "GROUP_" prefix is applied group.getProperties().put(ContentModel.PROP_AUTHORITY_NAME, gid); lookup.put(gid, group); } else if (LDAPUserRegistry.this.errorOnDuplicateGID) { throw new AlfrescoRuntimeException("Duplicate group id found for " + gid); } else { LDAPUserRegistry.logger.warn("Duplicate gid found for " + gid + " -> merging definitions"); } Set<String> childAssocs = group.getChildAssociations(); // Get the repeating (and possibly range restricted) member attribute Attribute memAttribute = getRangeRestrictedAttribute(attributes, LDAPUserRegistry.this.memberAttributeName); int nextStart = LDAPUserRegistry.this.attributeBatchSize; if (LDAPUserRegistry.logger.isDebugEnabled()) { LDAPUserRegistry.logger .debug("Processing group: " + gid + ", from source: " + group.getSourceId()); } // Loop until we get to the end of the range while (memAttribute != null) { for (int i = 0; i < memAttribute.size(); i++) { String attribute = (String) memAttribute.get(i); if (attribute != null && attribute.length() > 0) { try { // Attempt to parse the member attribute as a DN. If this fails we have a fallback // in the catch block LdapName distinguishedNameForComparison = fixedLdapName(attribute.toLowerCase()); Attribute nameAttribute; // If the user and group search bases are different we may be able to recognize user // and group DNs without a secondary lookup if (disjoint) { LdapName distinguishedName = fixedLdapName(attribute); Attributes nameAttributes = distinguishedName .getRdn(distinguishedName.size() - 1).toAttributes(); // Recognize user DNs if (distinguishedNameForComparison.startsWith(userDistinguishedNamePrefix) && (nameAttribute = nameAttributes .get(LDAPUserRegistry.this.userIdAttributeName)) != null) { if (LDAPUserRegistry.logger.isDebugEnabled()) { LDAPUserRegistry.logger .debug("User DN recognized: " + nameAttribute.get()); } childAssocs.add((String) nameAttribute.get()); continue; } // Recognize group DNs if (distinguishedNameForComparison.startsWith(groupDistinguishedNamePrefix) && (nameAttribute = nameAttributes .get(LDAPUserRegistry.this.groupIdAttributeName)) != null) { if (LDAPUserRegistry.logger.isDebugEnabled()) { LDAPUserRegistry.logger.debug( "Group DN recognized: " + "GROUP_" + nameAttribute.get()); } childAssocs.add("GROUP_" + nameAttribute.get()); continue; } } // If we can't determine the name and type from the DN alone, try a directory lookup if (distinguishedNameForComparison.startsWith(userDistinguishedNamePrefix) || distinguishedNameForComparison .startsWith(groupDistinguishedNamePrefix)) { try { Attributes childAttributes = this.ctx.getAttributes(jndiName(attribute), new String[] { "objectclass", LDAPUserRegistry.this.groupIdAttributeName, LDAPUserRegistry.this.userIdAttributeName }); Attribute objectClass = childAttributes.get("objectclass"); if (hasAttributeValue(objectClass, LDAPUserRegistry.this.personType)) { nameAttribute = childAttributes .get(LDAPUserRegistry.this.userIdAttributeName); if (nameAttribute == null) { if (LDAPUserRegistry.this.errorOnMissingUID) { throw new AlfrescoRuntimeException( "User missing user id attribute DN =" + attribute + " att = " + LDAPUserRegistry.this.userIdAttributeName); } else { LDAPUserRegistry.logger .warn("User missing user id attribute DN =" + attribute + " att = " + LDAPUserRegistry.this.userIdAttributeName); continue; } } if (LDAPUserRegistry.logger.isDebugEnabled()) { LDAPUserRegistry.logger .debug("User DN recognized by directory lookup: " + nameAttribute.get()); } childAssocs.add((String) nameAttribute.get()); continue; } else if (hasAttributeValue(objectClass, LDAPUserRegistry.this.groupType)) { nameAttribute = childAttributes .get(LDAPUserRegistry.this.groupIdAttributeName); if (nameAttribute == null) { if (LDAPUserRegistry.this.errorOnMissingGID) { Object[] params = { result.getNameInNamespace(), LDAPUserRegistry.this.groupIdAttributeName }; throw new AlfrescoRuntimeException( "synchronization.err.ldap.get.group.id.missing", params); } else { LDAPUserRegistry.logger.warn( "Missing GID3 on " + distinguishedNameForComparison + " attributes:" + childAttributes); continue; } } if (LDAPUserRegistry.logger.isDebugEnabled()) { LDAPUserRegistry.logger .debug("Group DN recognized by directory lookup: " + "GROUP_" + nameAttribute.get()); } childAssocs.add("GROUP_" + nameAttribute.get()); continue; } } catch (NamingException e) { // Unresolvable name if (LDAPUserRegistry.this.errorOnMissingMembers) { Object[] params = { groupShortName, attribute, e.getLocalizedMessage() }; throw new AlfrescoRuntimeException( "synchronization.err.ldap.group.member.missing.exception", params, e); } LDAPUserRegistry.logger.warn("Failed to resolve member of group '" + groupShortName + "' with distinguished name: " + attribute, e); continue; } } if (LDAPUserRegistry.this.errorOnMissingMembers) { Object[] params = { groupShortName, attribute }; throw new AlfrescoRuntimeException( "synchronization.err.ldap.group.member.missing", params); } LDAPUserRegistry.logger.warn("Failed to resolve member of group '" + groupShortName + "' with distinguished name: " + attribute); } catch (InvalidNameException e) { // The member attribute didn't parse as a DN. So assume we have a group class like // posixGroup (FDS) that directly lists user names if (LDAPUserRegistry.logger.isDebugEnabled()) { LDAPUserRegistry.logger .debug("Member DN recognized as posixGroup: " + attribute); } childAssocs.add(attribute); } } } // If we are using attribute matching and we haven't got to the end (indicated by an asterisk), // fetch the next batch if (nextStart > 0 && !LDAPUserRegistry.PATTERN_RANGE_END .matcher(memAttribute.getID().toLowerCase()).find()) { Attributes childAttributes = this.ctx.getAttributes(jndiName(result.getNameInNamespace()), new String[] { LDAPUserRegistry.this.memberAttributeName + ";range=" + nextStart + '-' + (nextStart + LDAPUserRegistry.this.attributeBatchSize - 1) }); memAttribute = getRangeRestrictedAttribute(childAttributes, LDAPUserRegistry.this.memberAttributeName); nextStart += LDAPUserRegistry.this.attributeBatchSize; } else { memAttribute = null; } } } public void close() throws NamingException { this.ctx.close(); } }, this.groupSearchBase, query, this.groupKeys.getFirst()); if (LDAPUserRegistry.logger.isDebugEnabled()) { LDAPUserRegistry.logger.debug("Found " + lookup.size()); } return lookup.values(); }
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.c o m * @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); } }
From source file:org.alfresco.repo.security.sync.ldap.LDAPUserRegistry.java
public Collection<NodeDescription> getGroups(Date modifiedSince) { // Work out whether the user and group trees are disjoint. This may allow us to optimize reverse DN // resolution. final LdapName groupDistinguishedNamePrefix; try {//from w w w . ja v a2 s . c o m groupDistinguishedNamePrefix = fixedLdapName(this.groupSearchBase.toLowerCase()); } catch (InvalidNameException e) { Object[] params = { this.groupSearchBase.toLowerCase(), e.getLocalizedMessage() }; throw new AlfrescoRuntimeException("synchronization.err.ldap.search.base.invalid", params, e); } final LdapName userDistinguishedNamePrefix; try { userDistinguishedNamePrefix = fixedLdapName(this.userSearchBase.toLowerCase()); } catch (InvalidNameException e) { Object[] params = { this.userSearchBase.toLowerCase(), e.getLocalizedMessage() }; throw new AlfrescoRuntimeException("synchronization.err.ldap.search.base.invalid", params, e); } final boolean disjoint = !groupDistinguishedNamePrefix.startsWith(userDistinguishedNamePrefix) && !userDistinguishedNamePrefix.startsWith(groupDistinguishedNamePrefix); // Choose / generate the query String query; if (modifiedSince == null) { query = this.groupQuery; } else { query = MessageFormat.format(this.groupDifferentialQuery, this.timestampFormat.format(modifiedSince)); } // Run the query and process the results final Map<String, NodeDescription> lookup = new TreeMap<String, NodeDescription>(); processQuery(new AbstractSearchCallback() { // We get a whole new context to avoid interference with cookies from paged results private DirContext ctx = LDAPUserRegistry.this.ldapInitialContextFactory.getDefaultIntialDirContext(); protected void doProcess(SearchResult result) throws NamingException, ParseException { Attributes attributes = result.getAttributes(); Attribute gidAttribute = attributes.get(LDAPUserRegistry.this.groupIdAttributeName); if (gidAttribute == null) { if (LDAPUserRegistry.this.errorOnMissingGID) { Object[] params = { result.getNameInNamespace(), LDAPUserRegistry.this.groupIdAttributeName }; throw new AlfrescoRuntimeException("synchronization.err.ldap.get.group.id.missing", params); } else { LDAPUserRegistry.logger.warn("Missing GID on " + attributes); return; } } String groupShortName = gidAttribute.get(0).toString(); String gid = "GROUP_" + groupShortName; NodeDescription group = lookup.get(gid); if (group == null) { // Apply the mapped properties to the node description group = mapToNode(LDAPUserRegistry.this.groupAttributeMapping, LDAPUserRegistry.this.groupAttributeDefaults, result); // Make sure the "GROUP_" prefix is applied group.getProperties().put(ContentModel.PROP_AUTHORITY_NAME, gid); lookup.put(gid, group); } else if (LDAPUserRegistry.this.errorOnDuplicateGID) { throw new AlfrescoRuntimeException("Duplicate group id found for " + gid); } else { LDAPUserRegistry.logger.warn("Duplicate gid found for " + gid + " -> merging definitions"); } Set<String> childAssocs = group.getChildAssociations(); // Get the repeating (and possibly range restricted) member attribute Attribute memAttribute = getRangeRestrictedAttribute(attributes, LDAPUserRegistry.this.memberAttributeName); int nextStart = LDAPUserRegistry.this.attributeBatchSize; if (LDAPUserRegistry.logger.isDebugEnabled()) { LDAPUserRegistry.logger .debug("Processing group: " + gid + ", from source: " + group.getSourceId()); } // Loop until we get to the end of the range while (memAttribute != null) { for (int i = 0; i < memAttribute.size(); i++) { String attribute = (String) memAttribute.get(i); if (attribute != null && attribute.length() > 0) { try { // Attempt to parse the member attribute as a DN. If this fails we have a fallback // in the catch block LdapName distinguishedNameForComparison = fixedLdapName(attribute.toLowerCase()); Attribute nameAttribute; // If the user and group search bases are different we may be able to recognize user // and group DNs without a secondary lookup if (disjoint) { LdapName distinguishedName = fixedLdapName(attribute); Attributes nameAttributes = distinguishedName .getRdn(distinguishedName.size() - 1).toAttributes(); // Recognize user DNs if (distinguishedNameForComparison.startsWith(userDistinguishedNamePrefix) && (nameAttribute = nameAttributes .get(LDAPUserRegistry.this.userIdAttributeName)) != null) { if (LDAPUserRegistry.logger.isDebugEnabled()) { LDAPUserRegistry.logger .debug("User DN recognized: " + nameAttribute.get()); } childAssocs.add((String) nameAttribute.get()); continue; } // Recognize group DNs if (distinguishedNameForComparison.startsWith(groupDistinguishedNamePrefix) && (nameAttribute = nameAttributes .get(LDAPUserRegistry.this.groupIdAttributeName)) != null) { if (LDAPUserRegistry.logger.isDebugEnabled()) { LDAPUserRegistry.logger.debug( "Group DN recognized: " + "GROUP_" + nameAttribute.get()); } childAssocs.add("GROUP_" + nameAttribute.get()); continue; } } // If we can't determine the name and type from the DN alone, try a directory lookup if (distinguishedNameForComparison.startsWith(userDistinguishedNamePrefix) || distinguishedNameForComparison .startsWith(groupDistinguishedNamePrefix)) { try { Attributes childAttributes = this.ctx.getAttributes(jndiName(attribute), new String[] { "objectclass", LDAPUserRegistry.this.groupIdAttributeName, LDAPUserRegistry.this.userIdAttributeName }); Attribute objectClass = childAttributes.get("objectclass"); if (hasAttributeValue(objectClass, LDAPUserRegistry.this.personType)) { nameAttribute = childAttributes .get(LDAPUserRegistry.this.userIdAttributeName); if (nameAttribute == null) { if (LDAPUserRegistry.this.errorOnMissingUID) { throw new AlfrescoRuntimeException( "User missing user id attribute DN =" + attribute + " att = " + LDAPUserRegistry.this.userIdAttributeName); } else { LDAPUserRegistry.logger .warn("User missing user id attribute DN =" + attribute + " att = " + LDAPUserRegistry.this.userIdAttributeName); continue; } } if (LDAPUserRegistry.logger.isDebugEnabled()) { LDAPUserRegistry.logger .debug("User DN recognized by directory lookup: " + nameAttribute.get()); } childAssocs.add((String) nameAttribute.get()); continue; } else if (hasAttributeValue(objectClass, LDAPUserRegistry.this.groupType)) { nameAttribute = childAttributes .get(LDAPUserRegistry.this.groupIdAttributeName); if (nameAttribute == null) { if (LDAPUserRegistry.this.errorOnMissingGID) { Object[] params = { result.getNameInNamespace(), LDAPUserRegistry.this.groupIdAttributeName }; throw new AlfrescoRuntimeException( "synchronization.err.ldap.get.group.id.missing", params); } else { LDAPUserRegistry.logger .warn("Missing GID on " + childAttributes); continue; } } if (LDAPUserRegistry.logger.isDebugEnabled()) { LDAPUserRegistry.logger .debug("Group DN recognized by directory lookup: " + "GROUP_" + nameAttribute.get()); } childAssocs.add("GROUP_" + nameAttribute.get()); continue; } } catch (NamingException e) { // Unresolvable name if (LDAPUserRegistry.this.errorOnMissingMembers) { Object[] params = { groupShortName, attribute, e.getLocalizedMessage() }; throw new AlfrescoRuntimeException( "synchronization.err.ldap.group.member.missing.exception", params, e); } LDAPUserRegistry.logger.warn("Failed to resolve member of group '" + groupShortName + "' with distinguished name: " + attribute, e); continue; } } if (LDAPUserRegistry.this.errorOnMissingMembers) { Object[] params = { groupShortName, attribute }; throw new AlfrescoRuntimeException( "synchronization.err.ldap.group.member.missing", params); } LDAPUserRegistry.logger.warn("Failed to resolve member of group '" + groupShortName + "' with distinguished name: " + attribute); } catch (InvalidNameException e) { // The member attribute didn't parse as a DN. So assume we have a group class like // posixGroup (FDS) that directly lists user names if (LDAPUserRegistry.logger.isDebugEnabled()) { LDAPUserRegistry.logger .debug("Member DN recognized as posixGroup: " + attribute); } childAssocs.add(attribute); } } } // If we are using attribute matching and we haven't got to the end (indicated by an asterisk), // fetch the next batch if (nextStart > 0 && !LDAPUserRegistry.PATTERN_RANGE_END .matcher(memAttribute.getID().toLowerCase()).find()) { Attributes childAttributes = this.ctx.getAttributes(jndiName(result.getNameInNamespace()), new String[] { LDAPUserRegistry.this.memberAttributeName + ";range=" + nextStart + '-' + (nextStart + LDAPUserRegistry.this.attributeBatchSize - 1) }); memAttribute = getRangeRestrictedAttribute(childAttributes, LDAPUserRegistry.this.memberAttributeName); nextStart += LDAPUserRegistry.this.attributeBatchSize; } else { memAttribute = null; } } } public void close() throws NamingException { this.ctx.close(); } }, this.groupSearchBase, query, this.groupKeys.getFirst()); if (LDAPUserRegistry.logger.isDebugEnabled()) { LDAPUserRegistry.logger.debug("Found " + lookup.size()); } return lookup.values(); }
From source file:dk.magenta.ldap.LDAPMultiBaseUserRegistry.java
public Collection<NodeDescription> getGroups(Date modifiedSince) { // Work out whether the user and group trees are disjoint. This may allow us to optimize reverse DN // resolution. final Set<LdapName> groupDistinguishedNamePrefixes = new LinkedHashSet<>(); for (String groupSearchBase : this.groupSearchBases) { try {//from w ww.j a va 2s . c om final LdapName groupDistinguishedNamePrefix = fixedLdapName(groupSearchBase.toLowerCase()); groupDistinguishedNamePrefixes.add(groupDistinguishedNamePrefix); } catch (InvalidNameException e) { Object[] params = { groupSearchBase.toLowerCase(), e.getLocalizedMessage() }; throw new AlfrescoRuntimeException("synchronization.err.ldap.search.base.invalid", params, e); } } final Set<LdapName> userDistinguishedNamePrefixes = new LinkedHashSet<>(); for (String userSearchBase : this.userSearchBases) { try { final LdapName userDistinguishedNamePrefix = fixedLdapName(userSearchBase.toLowerCase()); userDistinguishedNamePrefixes.add(userDistinguishedNamePrefix); } catch (InvalidNameException e) { Object[] params = { userSearchBase.toLowerCase(), e.getLocalizedMessage() }; throw new AlfrescoRuntimeException("synchronization.err.ldap.search.base.invalid", params, e); } } final Set<LdapName> distinctGroupDNPrefixes = new LinkedHashSet<>(groupDistinguishedNamePrefixes); final Set<LdapName> distinctUserDNPrefixes = new LinkedHashSet<>(userDistinguishedNamePrefixes); removeCommonPrefixedNamesFromSets(distinctGroupDNPrefixes, distinctUserDNPrefixes); // If there exist either distinct user DNs or group DNs, then the // sets are disjoint, and we may be able to recognize user or group // DNs without secondary lookup final boolean disjoint = !distinctUserDNPrefixes.isEmpty() || !distinctGroupDNPrefixes.isEmpty(); if (LDAPMultiBaseUserRegistry.logger.isDebugEnabled()) { if (disjoint) { LDAPMultiBaseUserRegistry.logger.debug("Distinct user " + "DN prefixes: " + distinctUserDNPrefixes); LDAPMultiBaseUserRegistry.logger .debug("Distinct group " + "DN prefixes: " + distinctGroupDNPrefixes); } } // Choose / generate the query String query; if (modifiedSince == null) { query = this.groupQuery; } else { query = MessageFormat.format(this.groupDifferentialQuery, this.timestampFormat.format(modifiedSince)); } // Run the query and process the results final Map<String, NodeDescription> lookup = new TreeMap<String, NodeDescription>(); processQuery(new SearchCallback() { // We get a whole new context to avoid interference with cookies from paged results private DirContext ctx = LDAPMultiBaseUserRegistry.this.ldapInitialContextFactory .getDefaultIntialDirContext(); public void process(SearchResult result) throws NamingException, ParseException { Attributes attributes = result.getAttributes(); Attribute gidAttribute = attributes.get(LDAPMultiBaseUserRegistry.this.groupIdAttributeName); if (gidAttribute == null) { if (LDAPMultiBaseUserRegistry.this.errorOnMissingGID) { Object[] params = { result.getNameInNamespace(), LDAPMultiBaseUserRegistry.this.groupIdAttributeName }; throw new AlfrescoRuntimeException("synchronization.err.ldap.get.group.id.missing", params); } else { LDAPMultiBaseUserRegistry.logger.warn("Missing GID on " + attributes); return; } } String groupShortName = gidAttribute.get(0).toString(); String gid = "GROUP_" + groupShortName; NodeDescription group = lookup.get(gid); if (group == null) { // Apply the mapped properties to the node description group = mapToNode(LDAPMultiBaseUserRegistry.this.groupAttributeMapping, LDAPMultiBaseUserRegistry.this.groupAttributeDefaults, result); // Make sure the "GROUP_" prefix is applied group.getProperties().put(ContentModel.PROP_AUTHORITY_NAME, gid); lookup.put(gid, group); } else if (LDAPMultiBaseUserRegistry.this.errorOnDuplicateGID) { throw new AlfrescoRuntimeException("Duplicate group id found for " + gid); } else { LDAPMultiBaseUserRegistry.logger .warn("Duplicate gid found for " + gid + " -> merging definitions"); } Set<String> childAssocs = group.getChildAssociations(); // Get the repeating (and possibly range restricted) member attribute Attribute memAttribute = getRangeRestrictedAttribute(attributes, LDAPMultiBaseUserRegistry.this.memberAttributeName); int nextStart = LDAPMultiBaseUserRegistry.this.attributeBatchSize; if (LDAPMultiBaseUserRegistry.logger.isDebugEnabled()) { LDAPMultiBaseUserRegistry.logger .debug("Processing group: " + gid + ", from source: " + group.getSourceId()); } // Loop until we get to the end of the range while (memAttribute != null) { for (int i = 0; i < memAttribute.size(); i++) { String attribute = (String) memAttribute.get(i); if (attribute != null && attribute.length() > 0) { try { // Attempt to parse the member attribute as a DN. If this fails we have a fallback // in the catch block LdapName distinguishedNameForComparison = fixedLdapName(attribute.toLowerCase()); Attribute nameAttribute; // If the user and group search bases are different we may be able to recognize user // and group DNs without a secondary lookup if (disjoint) { LdapName distinguishedName = fixedLdapName(attribute); Attributes nameAttributes = distinguishedName .getRdn(distinguishedName.size() - 1).toAttributes(); // Recognize user DNs if (nameStartsWithNameInSet(distinguishedNameForComparison, distinctUserDNPrefixes) && (nameAttribute = nameAttributes.get( LDAPMultiBaseUserRegistry.this.userIdAttributeName)) != null) { if (LDAPMultiBaseUserRegistry.logger.isDebugEnabled()) { LDAPMultiBaseUserRegistry.logger .debug("User DN recognized: " + nameAttribute.get()); } childAssocs.add((String) nameAttribute.get()); continue; } // Recognize group DNs if (nameStartsWithNameInSet(distinguishedNameForComparison, distinctGroupDNPrefixes) && (nameAttribute = nameAttributes.get( LDAPMultiBaseUserRegistry.this.groupIdAttributeName)) != null) { if (LDAPMultiBaseUserRegistry.logger.isDebugEnabled()) { LDAPMultiBaseUserRegistry.logger.debug( "Group DN recognized: " + "GROUP_" + nameAttribute.get()); } childAssocs.add("GROUP_" + nameAttribute.get()); continue; } } // If we can't determine the name and type from the DN alone, try a directory lookup if (nameStartsWithNameInSet(distinguishedNameForComparison, userDistinguishedNamePrefixes) || nameStartsWithNameInSet(distinguishedNameForComparison, groupDistinguishedNamePrefixes)) { try { Attributes childAttributes = this.ctx.getAttributes(jndiName(attribute), new String[] { "objectclass", LDAPMultiBaseUserRegistry.this.groupIdAttributeName, LDAPMultiBaseUserRegistry.this.userIdAttributeName }); Attribute objectClass = childAttributes.get("objectclass"); if (hasAttributeValue(objectClass, LDAPMultiBaseUserRegistry.this.personType)) { nameAttribute = childAttributes .get(LDAPMultiBaseUserRegistry.this.userIdAttributeName); if (nameAttribute == null) { if (LDAPMultiBaseUserRegistry.this.errorOnMissingUID) { throw new AlfrescoRuntimeException( "User missing user id attribute DN =" + attribute + " att = " + LDAPMultiBaseUserRegistry.this.userIdAttributeName); } else { LDAPMultiBaseUserRegistry.logger .warn("User missing user id attribute DN =" + attribute + " att = " + LDAPMultiBaseUserRegistry.this.userIdAttributeName); continue; } } if (LDAPMultiBaseUserRegistry.logger.isDebugEnabled()) { LDAPMultiBaseUserRegistry.logger .debug("User DN recognized by directory lookup: " + nameAttribute.get()); } childAssocs.add((String) nameAttribute.get()); continue; } else if (hasAttributeValue(objectClass, LDAPMultiBaseUserRegistry.this.groupType)) { nameAttribute = childAttributes .get(LDAPMultiBaseUserRegistry.this.groupIdAttributeName); if (nameAttribute == null) { if (LDAPMultiBaseUserRegistry.this.errorOnMissingGID) { Object[] params = { result.getNameInNamespace(), LDAPMultiBaseUserRegistry.this.groupIdAttributeName }; throw new AlfrescoRuntimeException( "synchronization.err.ldap.get.group.id.missing", params); } else { LDAPMultiBaseUserRegistry.logger .warn("Missing GID on " + childAttributes); continue; } } if (LDAPMultiBaseUserRegistry.logger.isDebugEnabled()) { LDAPMultiBaseUserRegistry.logger .debug("Group DN recognized by directory lookup: " + "GROUP_" + nameAttribute.get()); } childAssocs.add("GROUP_" + nameAttribute.get()); continue; } } catch (NamingException e) { // Unresolvable name if (LDAPMultiBaseUserRegistry.this.errorOnMissingMembers) { Object[] params = { groupShortName, attribute, e.getLocalizedMessage() }; throw new AlfrescoRuntimeException( "synchronization.err.ldap.group.member.missing.exception", params, e); } LDAPMultiBaseUserRegistry.logger.warn("Failed to resolve member of group '" + groupShortName + "' with distinguished name: " + attribute, e); continue; } } if (LDAPMultiBaseUserRegistry.this.errorOnMissingMembers) { Object[] params = { groupShortName, attribute }; throw new AlfrescoRuntimeException( "synchronization.err.ldap.group.member.missing", params); } LDAPMultiBaseUserRegistry.logger.warn("Failed to resolve member of group '" + groupShortName + "' with distinguished name: " + attribute); } catch (InvalidNameException e) { // The member attribute didn't parse as a DN. So assume we have a group class like // posixGroup (FDS) that directly lists user names if (LDAPMultiBaseUserRegistry.logger.isDebugEnabled()) { LDAPMultiBaseUserRegistry.logger .debug("Member DN recognized as posixGroup: " + attribute); } childAssocs.add(attribute); } } } // If we are using attribute matching and we haven't got to the end (indicated by an asterisk), // fetch the next batch if (nextStart > 0 && !LDAPMultiBaseUserRegistry.PATTERN_RANGE_END .matcher(memAttribute.getID().toLowerCase()).find()) { Attributes childAttributes = this.ctx.getAttributes(jndiName(result.getNameInNamespace()), new String[] { LDAPMultiBaseUserRegistry.this.memberAttributeName + ";range=" + nextStart + '-' + (nextStart + LDAPMultiBaseUserRegistry.this.attributeBatchSize - 1) }); memAttribute = getRangeRestrictedAttribute(childAttributes, LDAPMultiBaseUserRegistry.this.memberAttributeName); nextStart += LDAPMultiBaseUserRegistry.this.attributeBatchSize; } else { memAttribute = null; } } } public void close() throws NamingException { this.ctx.close(); } }, this.groupSearchBases, query, this.groupKeys.getFirst()); if (LDAPMultiBaseUserRegistry.logger.isDebugEnabled()) { LDAPMultiBaseUserRegistry.logger.debug("Found " + lookup.size()); } return lookup.values(); }
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 a2 s . c o 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: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 w w . j a v a 2 s. 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; }