Java Code Examples for javax.naming.directory.SearchResult#getNameInNamespace()

The following examples show how to use javax.naming.directory.SearchResult#getNameInNamespace() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: OpenLdapUserManagerImpl.java    From cosmic with Apache License 2.0 6 votes vote down vote up
protected LdapUser createUser(final SearchResult result) throws NamingException {
    final Attributes attributes = result.getAttributes();

    final String username = LdapUtils.getAttributeValue(attributes, _ldapConfiguration.getUsernameAttribute());
    final String email = LdapUtils.getAttributeValue(attributes, _ldapConfiguration.getEmailAttribute());
    final String firstname = LdapUtils.getAttributeValue(attributes, _ldapConfiguration.getFirstnameAttribute());
    final String lastname = LdapUtils.getAttributeValue(attributes, _ldapConfiguration.getLastnameAttribute());
    final String principal = result.getNameInNamespace();

    String domain = principal.replace("cn=" + LdapUtils.getAttributeValue(attributes, _ldapConfiguration.getCommonNameAttribute()) + ",", "");
    domain = domain.replace("," + _ldapConfiguration.getBaseDn(), "");
    domain = domain.replace("ou=", "");

    final boolean disabled = isUserDisabled(result);

    return new LdapUser(username, email, firstname, lastname, principal, domain, disabled);
}
 
Example 2
Source File: LdapAuthentication.java    From glowroot with Apache License 2.0 6 votes vote down vote up
@Instrumentation.TraceEntry(message = "get ldap user DN for username: {{1}}", timer = "ldap")
private static @Nullable String getUserDn(LdapContext ldapContext, String username,
        LdapConfig ldapConfig) throws NamingException {
    SearchControls searchCtls = new SearchControls();
    searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);
    NamingEnumeration<?> namingEnum = ldapContext.search(ldapConfig.userBaseDn(),
            ldapConfig.userSearchFilter(), new String[] {username}, searchCtls);
    try {
        if (!namingEnum.hasMore()) {
            return null;
        }
        SearchResult result = (SearchResult) checkNotNull(namingEnum.next());
        String userDn = result.getNameInNamespace();
        if (namingEnum.hasMore()) {
            throw new IllegalStateException("More than matching user: " + username);
        }
        return userDn;
    } finally {
        namingEnum.close();
    }
}
 
Example 3
Source File: Organization2Activedirectory.java    From MaxKey with Apache License 2.0 6 votes vote down vote up
@Override
public boolean delete(Organizations organization) throws Exception {
	try {
		SearchControls constraints = new SearchControls();
		constraints.setSearchScope(ldapUtils.getSearchScope());
		NamingEnumeration<SearchResult> results = ldapUtils.getConnection()
				.search(ldapUtils.getBaseDN(), "(&(objectClass=organizationalUnit)(description="+organization.getId()+"))", constraints);
		String dn="";
		if (results == null || !results.hasMore()) {
			
		}else{
			SearchResult sr = (SearchResult) results.next();
			dn =sr.getNameInNamespace();
			ldapUtils.getCtx().destroySubcontext(dn);
		}
		
		ldapUtils.close();
	} catch (NamingException e) {
		e.printStackTrace();
	}
	return super.delete(organization);
}
 
Example 4
Source File: LdapServer.java    From MaxKey with Apache License 2.0 5 votes vote down vote up
@Override
public boolean authenticate(String username, String password) {
	String queryFilter = "("+filterAttribute+"="+username+")";
	_logger.info(" filter : " + queryFilter);
	String dn="";
	SearchControls constraints = new SearchControls();
	constraints.setSearchScope(ldapUtils.getSearchScope());
	try {
		NamingEnumeration<SearchResult> results = ldapUtils.getConnection()
				.search(ldapUtils.getBaseDN(), queryFilter, constraints);
		
		if (results == null || !results.hasMore()) {
			_logger.error("Ldap user "+username +" not found . ");
			return false;
		}else{
			while (results != null && results.hasMore()) {
				SearchResult sr = (SearchResult) results.next();
				//String rdn = sr.getName();
				dn = sr.getNameInNamespace();
				_logger.debug("Directory user dn is "+dn+" .");
			}
		}
	} catch (NamingException e) {
		_logger.error("query throw NamingException:" + e.getMessage());
	} finally {
		ldapUtils.close();
	}
	
	LdapUtils ldapPassWordValid=new LdapUtils(ldapUtils.getProviderUrl(),dn,password);
	ldapPassWordValid.openConnection();
	if(ldapPassWordValid.getCtx()!=null){
		_logger.debug("Directory user " + username + "  is validate .");
		ldapPassWordValid.close();
		return true;
	}
	return false;
}
 
Example 5
Source File: LDAPLoginManagerImpl.java    From olat with Apache License 2.0 5 votes vote down vote up
/**
 * Find the user dn with its uid
 * 
 * @param uid
 * @param ctx
 * @return user's dn
 */
private String searchUserDN(final String uid, final DirContext ctx) {
    if (ctx == null) {
        return null;
    }

    final List<String> ldapBases = LDAPLoginModule.getLdapBases();
    final String objctClass = LDAPLoginModule.getLdapUserObjectClass();
    final String[] serachAttr = { "dn" };

    final String ldapUserIDAttribute = LDAPLoginModule.mapOlatPropertyToLdapAttribute(LDAPConstants.LDAP_USER_IDENTIFYER);
    final String filter = "(&(objectClass=" + objctClass + ")(" + ldapUserIDAttribute + "=" + uid + "))";
    final SearchControls ctls = new SearchControls();
    ctls.setSearchScope(SearchControls.SUBTREE_SCOPE);
    ctls.setReturningAttributes(serachAttr);

    String userDN = null;
    for (final String ldapBase : ldapBases) {
        try {
            final NamingEnumeration<SearchResult> enm = ctx.search(ldapBase, filter, ctls);
            while (enm.hasMore()) {
                final SearchResult result = enm.next();
                userDN = result.getNameInNamespace();
            }
            if (userDN != null) {
                break;
            }
        } catch (final NamingException e) {
            log.error("NamingException when trying to bind user with username::" + uid + " on ldapBase::" + ldapBase, e);
        }
    }

    return userDN;
}
 
Example 6
Source File: ReadOnlyLDAPUsersDAO.java    From james-project with Apache License 2.0 5 votes vote down vote up
/**
 * For a given name, this method makes ldap search in userBase with filter {@link LdapRepositoryConfiguration#userIdAttribute}=name
 * and objectClass={@link LdapRepositoryConfiguration#userObjectClass} and builds {@link User} based on search result.
 *
 * @param name
 *            The userId which should be value of the field {@link LdapRepositoryConfiguration#userIdAttribute}
 * @return A {@link ReadOnlyLDAPUser} instance which is initialized with the
 *         userId of this user and ldap connection information with which
 *         the user was searched. Return null if such a user was not found.
 * @throws NamingException
 *             Propagated by the underlying LDAP communication layer.
 */
private ReadOnlyLDAPUser searchAndBuildUser(Username name) throws NamingException {
    SearchControls sc = new SearchControls();
    sc.setSearchScope(SearchControls.SUBTREE_SCOPE);
    sc.setReturningAttributes(new String[] { ldapConfiguration.getUserIdAttribute() });
    sc.setCountLimit(1);

    String filterTemplate = "(&({0}={1})(objectClass={2})" +
        StringUtils.defaultString(ldapConfiguration.getFilter(), "") +
        ")";

    String sanitizedFilter = FilterEncoder.format(
        filterTemplate,
        ldapConfiguration.getUserIdAttribute(),
        name.asString(),
        ldapConfiguration.getUserObjectClass());

    NamingEnumeration<SearchResult> sr = ldapContext.search(ldapConfiguration.getUserBase(), sanitizedFilter, sc);

    if (!sr.hasMore()) {
        return null;
    }

    SearchResult r = sr.next();
    Attribute userName = r.getAttributes().get(ldapConfiguration.getUserIdAttribute());

    if (!ldapConfiguration.getRestriction().isActivated()
        || userInGroupsMembershipList(r.getNameInNamespace(), ldapConfiguration.getRestriction().getGroupMembershipLists(ldapContext))) {
        return new ReadOnlyLDAPUser(Username.of(userName.get().toString()), r.getNameInNamespace(), ldapContext);
    }

    return null;
}
 
Example 7
Source File: LdapGroupsMapping.java    From big-c with Apache License 2.0 5 votes vote down vote up
List<String> doGetGroups(String user) throws NamingException {
  List<String> groups = new ArrayList<String>();

  DirContext ctx = getDirContext();

  // Search for the user. We'll only ever need to look at the first result
  NamingEnumeration<SearchResult> results = ctx.search(baseDN,
      userSearchFilter,
      new Object[]{user},
      SEARCH_CONTROLS);
  if (results.hasMoreElements()) {
    SearchResult result = results.nextElement();
    String userDn = result.getNameInNamespace();

    NamingEnumeration<SearchResult> groupResults =
        ctx.search(baseDN,
            "(&" + groupSearchFilter + "(" + groupMemberAttr + "={0}))",
            new Object[]{userDn},
            SEARCH_CONTROLS);
    while (groupResults.hasMoreElements()) {
      SearchResult groupResult = groupResults.nextElement();
      Attribute groupName = groupResult.getAttributes().get(groupNameAttr);
      groups.add(groupName.get().toString());
    }
  }

  return groups;
}
 
Example 8
Source File: LDAPLoginManagerImpl.java    From olat with Apache License 2.0 5 votes vote down vote up
/**
 * Find the user dn with its uid
 * 
 * @param uid
 * @param ctx
 * @return user's dn
 */
private String searchUserDN(final String uid, final DirContext ctx) {
    if (ctx == null) {
        return null;
    }

    final List<String> ldapBases = LDAPLoginModule.getLdapBases();
    final String objctClass = LDAPLoginModule.getLdapUserObjectClass();
    final String[] serachAttr = { "dn" };

    final String ldapUserIDAttribute = LDAPLoginModule.mapOlatPropertyToLdapAttribute(LDAPConstants.LDAP_USER_IDENTIFYER);
    final String filter = "(&(objectClass=" + objctClass + ")(" + ldapUserIDAttribute + "=" + uid + "))";
    final SearchControls ctls = new SearchControls();
    ctls.setSearchScope(SearchControls.SUBTREE_SCOPE);
    ctls.setReturningAttributes(serachAttr);

    String userDN = null;
    for (final String ldapBase : ldapBases) {
        try {
            final NamingEnumeration<SearchResult> enm = ctx.search(ldapBase, filter, ctls);
            while (enm.hasMore()) {
                final SearchResult result = enm.next();
                userDN = result.getNameInNamespace();
            }
            if (userDN != null) {
                break;
            }
        } catch (final NamingException e) {
            log.error("NamingException when trying to bind user with username::" + uid + " on ldapBase::" + ldapBase, e);
        }
    }

    return userDN;
}
 
Example 9
Source File: Organization2Ldap.java    From MaxKey with Apache License 2.0 5 votes vote down vote up
@Override
public boolean update(Organizations organization)  throws Exception{
	logger.info("update");
		SearchControls constraints = new SearchControls();
		constraints.setSearchScope(ldapUtils.getSearchScope());
		NamingEnumeration<SearchResult> results = ldapUtils.getConnection()
				.search(ldapUtils.getBaseDN(), "(&(objectClass=organizationalUnit)(description="+organization.getId()+"))", constraints);
		String oldDn="";
		String rdn="";
		if (results == null || !results.hasMore()) {
			return create(organization);
		}else{
			SearchResult sr = (SearchResult) results.next();
			oldDn =sr.getNameInNamespace();
			String[] dnSplit=oldDn.split(",");
			rdn=oldDn.substring(oldDn.indexOf(",")+1, oldDn.length());
			
			String ouName=dnSplit[0].split("=")[1];
			if(organization.getName()!=ouName){
				String newDn="ou="+organization.getName()+","+rdn;
				logger.debug("oldDn : "+oldDn);
				logger.debug("newDn : "+newDn);
				ldapUtils.getCtx().rename(oldDn, newDn);
				ModificationItem[] modificationItems = new ModificationItem[1];
				modificationItems[0]=new ModificationItem(DirContext.REMOVE_ATTRIBUTE,new BasicAttribute("ou",ouName));
				//modificationItems[1]=new ModificationItem(DirContext.REPLACE_ATTRIBUTE,new BasicAttribute("name",organization.getName()));
				//modificationItems[2]=new ModificationItem(DirContext.REPLACE_ATTRIBUTE,new BasicAttribute("id",organization.getId()));
				//modificationItems[3]=new ModificationItem(DirContext.REPLACE_ATTRIBUTE,new BasicAttribute("porgname",organization.getpName()));
				//modificationItems[4]=new ModificationItem(DirContext.REPLACE_ATTRIBUTE,new BasicAttribute("porgid",organization.getpId()));
				ldapUtils.getCtx().modifyAttributes(newDn, modificationItems);
			}
		}
		
		ldapUtils.close();
	
	return super.update(organization);
}
 
Example 10
Source File: Group2Activedirectory.java    From MaxKey with Apache License 2.0 5 votes vote down vote up
@Override
public boolean deleteMember(GroupMember groupMember)  throws Exception{
	try {
		SearchControls constraints = new SearchControls();
		constraints.setSearchScope(ldapUtils.getSearchScope());
		NamingEnumeration<SearchResult> results = ldapUtils.getConnection()
				.search(ldapUtils.getBaseDN(), "(cn="+groupMember.getGroupName()+")", constraints);
		if (results == null || !results.hasMore()) {
			return true;
		}
		
		String uniqueMember="";
		SearchControls memberSearchControls = new SearchControls();
		memberSearchControls.setSearchScope(ldapUtils.getSearchScope());
		NamingEnumeration<SearchResult> memberResults = ldapUtils.getConnection()
				.search(ldapUtils.getBaseDN(), "(sAMAccountName="+groupMember.getMemberName()+")", memberSearchControls);
		if (memberResults == null || !memberResults.hasMore()) {
			
		}else{
			SearchResult memberSr = (SearchResult) memberResults.next();
			uniqueMember =memberSr.getNameInNamespace();
			logger.debug("uniqueMember : "+uniqueMember);
			ModificationItem[] modificationItems = new ModificationItem[1];
			modificationItems[0]=new ModificationItem(DirContext.REMOVE_ATTRIBUTE,new BasicAttribute("member",uniqueMember));
			
			String dn="cn="+groupMember.getGroupName()+",cn=groups,"+ldapUtils.getBaseDN();
			
			ldapUtils.getCtx().modifyAttributes(dn, modificationItems);
		}

		ldapUtils.close();
	} catch (NamingException e) {
		e.printStackTrace();
	}
	return true;
}
 
Example 11
Source File: Organization2Ldap.java    From MaxKey with Apache License 2.0 5 votes vote down vote up
@Override
public boolean create(Organizations organization) throws Exception {
	logger.info("create");
		SearchControls constraints = new SearchControls();
		constraints.setSearchScope(ldapUtils.getSearchScope());
		NamingEnumeration<SearchResult> results = ldapUtils.getConnection()
				.search(ldapUtils.getBaseDN(), "(&(objectClass=organizationalUnit)(description="+organization.getpId()+"))", constraints);
		String rdn="";
		if (results == null || !results.hasMore()) {
			rdn=ldapUtils.getBaseDN();
		}else{
			SearchResult sr = (SearchResult) results.next();
			rdn =sr.getNameInNamespace();
		}
		
		Attributes attributes = new BasicAttributes();
		attributes.put(new BasicAttribute("objectClass","organizationalUnit"));
		attributes.put(new BasicAttribute("ou",organization.getName()));
		//attributes.put(new BasicAttribute("name",organization.getName()));
		//attributes.put(new BasicAttribute("id",organization.getId()));
		//attributes.put(new BasicAttribute("porgname",organization.getpName()));
		//attributes.put(new BasicAttribute("porgid",organization.getpId()));
		attributes.put(new BasicAttribute("description",organization.getId()));
		
		String dn="ou="+organization.getName()+","+rdn;
		
		ldapUtils.getCtx().createSubcontext(dn, attributes);
		ldapUtils.close();
		
	return super.create(organization);
}
 
Example 12
Source File: Organization2Activedirectory.java    From MaxKey with Apache License 2.0 5 votes vote down vote up
@Override
public boolean create(Organizations organization) throws Exception {
	try {
		SearchControls constraints = new SearchControls();
		constraints.setSearchScope(ldapUtils.getSearchScope());
		NamingEnumeration<SearchResult> results = ldapUtils.getConnection()
				.search(ldapUtils.getBaseDN(), "(&(objectClass=organizationalUnit)(description="+organization.getpId()+"))", constraints);
		String rdn="";
		if (results == null || !results.hasMore()) {
			rdn=ldapUtils.getBaseDN();
		}else{
			SearchResult sr = (SearchResult) results.next();
			rdn =sr.getNameInNamespace();
		}
		
		Attributes attributes = new BasicAttributes();
		attributes.put(new BasicAttribute("objectClass","organizationalUnit"));
		attributes.put(new BasicAttribute("ou",organization.getName()));
		//attributes.put(new BasicAttribute("name",organization.getName()));
		//attributes.put(new BasicAttribute("id",organization.getId()));
		//attributes.put(new BasicAttribute("porgname",organization.getpName()));
		//attributes.put(new BasicAttribute("porgid",organization.getpId()));
		attributes.put(new BasicAttribute("description",organization.getId()));
		
		String dn="ou="+organization.getName()+","+rdn;
		
		ldapUtils.getCtx().createSubcontext(dn, attributes);
		ldapUtils.close();
		
	} catch (NamingException e) {
		e.printStackTrace();
	}
	return super.create(organization);
}
 
Example 13
Source File: Organization2Activedirectory.java    From MaxKey with Apache License 2.0 5 votes vote down vote up
@Override
public boolean update(Organizations organization)  throws Exception{
	try {
		SearchControls constraints = new SearchControls();
		constraints.setSearchScope(ldapUtils.getSearchScope());
		NamingEnumeration<SearchResult> results = ldapUtils.getConnection()
				.search(ldapUtils.getBaseDN(), "(&(objectClass=organizationalUnit)(description="+organization.getId()+"))", constraints);
		String oldDn="";
		String rdn="";
		if (results == null || !results.hasMore()) {
			return create(organization);
		}else{
			SearchResult sr = (SearchResult) results.next();
			oldDn =sr.getNameInNamespace();
			String[] dnSplit=oldDn.split(",");
			rdn=oldDn.substring(oldDn.indexOf(",")+1, oldDn.length());
			
			String ouName=dnSplit[0].split("=")[1];
			if(organization.getName()!=ouName){
				String newDn="ou="+organization.getName()+","+rdn;
				logger.debug("oldDn : "+oldDn);
				logger.debug("newDn : "+newDn);
				ldapUtils.getCtx().rename(oldDn, newDn);
				
				//ModificationItem[] modificationItems = new ModificationItem[1];
				//modificationItems[0]=new ModificationItem(DirContext.REMOVE_ATTRIBUTE,new BasicAttribute("ou",ouName));
				//modificationItems[0]=new ModificationItem(DirContext.REPLACE_ATTRIBUTE,new BasicAttribute("name",organization.getName()));
				//ldapUtils.getCtx().modifyAttributes(newDn, modificationItems);
			}
		}
		
		ldapUtils.close();
	} catch (NamingException e) {
		e.printStackTrace();
	}
	return super.update(organization);
}
 
Example 14
Source File: UserInfo2Activedirectory.java    From MaxKey with Apache License 2.0 4 votes vote down vote up
@Override
public boolean update(UserInfo userInfo) throws Exception{
	try {
		String dn=null;
		SearchControls searchControls = new SearchControls();
		searchControls.setSearchScope(ldapUtils.getSearchScope());
		NamingEnumeration<SearchResult> results = ldapUtils.getConnection()
				.search(ldapUtils.getBaseDN(), "(sAMAccountName="+userInfo.getUsername()+")", searchControls);
		if (results == null || !results.hasMore()) {
			return create(loadUser(userInfo));
		}
		
		SearchResult sr = (SearchResult) results.next();
		dn =sr.getNameInNamespace();
		
		ModificationItem[] modificationItems = new ModificationItem[8];
		//modificationItems[0]=new ModificationItem(DirContext.REPLACE_ATTRIBUTE,new BasicAttribute("displayName",userInfo.getDisplayName()));
		//modificationItems[1]=new ModificationItem(DirContext.REPLACE_ATTRIBUTE,new BasicAttribute("cn",userInfo.getDisplayName()));
		//modificationItems[2]=new ModificationItem(DirContext.REPLACE_ATTRIBUTE,new BasicAttribute("givenName",userInfo.getGivenName()));
		//modificationItems[3]=new ModificationItem(DirContext.REPLACE_ATTRIBUTE,new BasicAttribute("sn",userInfo.getFamilyName()));
		
		modificationItems[0]=new ModificationItem(DirContext.REPLACE_ATTRIBUTE,new BasicAttribute("mobile",userInfo.getWorkPhoneNumber()==null?"00000000000":userInfo.getWorkPhoneNumber()));
		modificationItems[1]=new ModificationItem(DirContext.REPLACE_ATTRIBUTE,new BasicAttribute("mail",userInfo.getWorkEmail()==null?"[email protected]":userInfo.getWorkEmail()));
		
		modificationItems[2]=new ModificationItem(DirContext.REPLACE_ATTRIBUTE,new BasicAttribute("employeeNumber",userInfo.getEmployeeNumber()==null?"default":userInfo.getEmployeeNumber()));
		modificationItems[3]=new ModificationItem(DirContext.REPLACE_ATTRIBUTE,new BasicAttribute("ou",userInfo.getDepartment()==null?"default":userInfo.getDepartment()));
		
		modificationItems[4]=new ModificationItem(DirContext.REPLACE_ATTRIBUTE,new BasicAttribute("department",userInfo.getDepartmentId()==null?"default":userInfo.getDepartment()));
		modificationItems[5]=new ModificationItem(DirContext.REPLACE_ATTRIBUTE,new BasicAttribute("departmentNumber",userInfo.getDepartmentId()==null?"default":userInfo.getDepartmentId()));
		modificationItems[6]=new ModificationItem(DirContext.REPLACE_ATTRIBUTE,new BasicAttribute("title",userInfo.getJobTitle()==null?"default":userInfo.getJobTitle()));
		
		String managerDn="CN=dummy,"+ldapUtils.getBaseDN();
		if(userInfo.getManagerId()==null||userInfo.getManagerId().equals("")){

		}else{
			UserInfo queryManager=new UserInfo();
			queryManager.setId(userInfo.getManagerId());
			UserInfo manager=loadUser(queryManager);
			SearchControls managerSearchControls = new SearchControls();
			managerSearchControls.setSearchScope(ldapUtils.getSearchScope());
			NamingEnumeration<SearchResult> managerResults = ldapUtils.getConnection()
					.search(ldapUtils.getBaseDN(), "(sAMAccountName="+manager.getUsername()+")", managerSearchControls);
			if (managerResults == null || !managerResults.hasMore()) {
				
			}else{
				SearchResult managerSr = (SearchResult) managerResults.next();
				managerDn =managerSr.getNameInNamespace();
			}
		}
		
		modificationItems[7]=new ModificationItem(DirContext.REPLACE_ATTRIBUTE,new BasicAttribute("manager",managerDn));
		
		
		ldapUtils.getCtx().modifyAttributes(dn, modificationItems);
		
		if(userInfo.getDepartmentId()!=null&&
				!userInfo.getDepartmentId().equals("")){
			//get organization dn
			SearchControls orgSearchControls = new SearchControls();
			orgSearchControls.setSearchScope(ldapUtils.getSearchScope());
			NamingEnumeration<SearchResult> orgResults = ldapUtils.getConnection()
					.search(ldapUtils.getBaseDN(), "(&(objectClass=organizationalUnit)(description="+userInfo.getDepartmentId()+"))", orgSearchControls);
			String orgRdn="";
			if (orgResults == null || !orgResults.hasMore()) {
				orgRdn=ldapUtils.getBaseDN();
			}else{
				SearchResult orgSearchResult = (SearchResult) orgResults.next();
				orgRdn =orgSearchResult.getNameInNamespace();
			}
			
			//String newDn="CN="+userInfo.getDisplayName()+","+orgRdn;
			String newDn="CN="+userInfo.getUsername()+","+orgRdn;
			
			if(!dn.equals(newDn)){
				logger.debug("oldDn : "+dn);
				logger.debug("newDn : "+newDn);
				ldapUtils.getCtx().rename(dn, newDn);
			}
		}
		
		ldapUtils.close();
	} catch (NamingException e) {
		e.printStackTrace();
	}
	return true;
}
 
Example 15
Source File: JNDIProviderImpl.java    From ldapchai with GNU Lesser General Public License v2.1 4 votes vote down vote up
private void parseSearchResults(
        final NamingEnumeration<SearchResult> answer
)
        throws NamingException
{
    while ( answer.hasMore() )
    {
        final SearchResult searchResult = answer.next();

        String entryDN = null;
        if ( chaiConfiguration.getBooleanSetting( ChaiSetting.JNDI_RESOLVE_IN_NAMESPACE ) )
        {
            try
            {
                entryDN = searchResult.getNameInNamespace();
                entryDN = removeJndiEscapes( entryDN );
            }
            catch ( UnsupportedOperationException e )
            {
                LOGGER.debug( "unable to use jndi NameInNamespace api: " + e.getMessage() );
            }
        }

        if ( entryDN == null )
        {
            final StringBuilder entryDNbuilder = new StringBuilder();
            entryDNbuilder.append( removeJndiEscapes( searchResult.getName() ) );
            if ( baseDN.length() > 0 )
            {
                if ( entryDNbuilder.length() > 0 )
                {
                    entryDNbuilder.append( ',' );
                }
                entryDNbuilder.append( baseDN );
            }

            entryDN = entryDNbuilder.toString();
        }

        final Map<String, List<String>> attrValues = new HashMap<String, List<String>>();
        {
            final NamingEnumeration attributeEnum = searchResult.getAttributes().getAll();
            attrValues.putAll( parseAttributeValues( attributeEnum, returnAllValues ) );
        }

        if ( results.containsKey( entryDN ) )
        {
            LOGGER.warn( "ignoring duplicate DN in search result from ldap server: " + entryDN );
        }
        else
        {
            results.put( entryDN, Collections.unmodifiableMap( attrValues ) );
        }
    }
}
 
Example 16
Source File: LDAPUserRegistry.java    From alfresco-repository with GNU Lesser General Public License v3.0 4 votes vote down vote up
private NodeDescription mapToNode(Map<String, String> attributeMapping, Map<String, String> attributeDefaults,
        SearchResult result) throws NamingException
{
    NodeDescription nodeDescription = new NodeDescription(result.getNameInNamespace());
    Attributes ldapAttributes = result.getAttributes();

    // Parse the timestamp
    Attribute modifyTimestamp = ldapAttributes.get(this.modifyTimestampAttributeName);
    if (modifyTimestamp != null)
    {
        try
        {
            nodeDescription.setLastModified(this.timestampFormat.parse(modifyTimestamp.get().toString()));
        }
        catch (ParseException e)
        {
            throw new AlfrescoRuntimeException("Failed to parse timestamp.", e);
        }
    }

    // Apply the mapped attributes
    PropertyMap properties = nodeDescription.getProperties();
    for (String key : attributeMapping.keySet())
    {
        QName keyQName = QName.createQName(key, this.namespaceService);

        // cater for null
        String attributeName = attributeMapping.get(key);
        if (attributeName != null)
        {
            Attribute attribute = ldapAttributes.get(attributeName);
            String defaultAttribute = attributeDefaults.get(key);
            
            if (attribute != null)
            {
                String value = (String) attribute.get(0);
                if (value != null)
                {
                    properties.put(keyQName, value);
                }
            }
            else if (defaultAttribute != null)
            {
                properties.put(keyQName, defaultAttribute);
            }
            else
            {
                // Make sure that a 2nd sync, updates deleted ldap attributes(MNT-14026)
                properties.put(keyQName, null);
            }
        }
        else
        {
            String defaultValue = attributeDefaults.get(key);
            if (defaultValue != null)
            {
                properties.put(keyQName, defaultValue);
            }
        }
    }
    return nodeDescription;
}
 
Example 17
Source File: Group2Activedirectory.java    From MaxKey with Apache License 2.0 4 votes vote down vote up
@Override
public boolean addMember(GroupMember groupMember) throws Exception {
	try {
		SearchControls constraints = new SearchControls();
		constraints.setSearchScope(ldapUtils.getSearchScope());
		NamingEnumeration<SearchResult> results = ldapUtils.getConnection()
				.search(ldapUtils.getBaseDN(), "(cn="+groupMember.getGroupName()+")", constraints);
		if (results == null || !results.hasMore()) {
			Groups  group =new Groups();
			group.setName(groupMember.getGroupName());
			return create(group);
		}
		
		
		String uniqueMember="";
		SearchControls memberSearchControls = new SearchControls();
		logger.debug("user Search : "+"(sAMAccountName="+groupMember.getMemberName()+")");
		memberSearchControls.setSearchScope(ldapUtils.getSearchScope());
		NamingEnumeration<SearchResult> memberResults = ldapUtils.getConnection()
				.search(ldapUtils.getBaseDN(), "(sAMAccountName="+groupMember.getMemberName()+")", memberSearchControls);
		if (memberResults == null || !memberResults.hasMore()) {
			
		}else{
			SearchResult memberSr = (SearchResult) memberResults.next();
			uniqueMember =memberSr.getNameInNamespace();
			logger.debug("uniqueMember : "+uniqueMember);
			ModificationItem[] modificationItems = new ModificationItem[1];
			modificationItems[0]=new ModificationItem(DirContext.ADD_ATTRIBUTE,new BasicAttribute("member",uniqueMember));
			
			String dn="cn="+groupMember.getGroupName()+",cn=groups,"+ldapUtils.getBaseDN();
			
			ldapUtils.getCtx().modifyAttributes(dn, modificationItems);
		}
		
		
		ldapUtils.close();
	} catch (NamingException e) {
		e.printStackTrace();
	}
	return true;
}
 
Example 18
Source File: UserSync.java    From ranger with Apache License 2.0 4 votes vote down vote up
private void findAdvGroupProperties(LdapContext ldapContext) throws Throwable {
    int noOfGroups = 0;
    NamingEnumeration<SearchResult> groupSearchResultEnum = null;
    SearchControls groupSearchControls = new SearchControls();
    groupSearchControls.setSearchScope(config.getGroupSearchScope());
    Set<String> groupSearchAttributes = new HashSet<>();
    groupSearchAttributes.add(groupNameAttrName);
    groupSearchAttributes.add(groupMemberName);
    groupSearchAttributes.add("distinguishedName");
    groupSearchControls.setReturningAttributes(groupSearchAttributes.toArray(
            new String[groupSearchAttributes.size()]));
    String extendedGroupSearchFilter = "(objectclass=" + groupObjClassName + ")";

    try {
        HashMap<String, Integer> ouOccurences = new HashMap<>();
        if (groupSearchBase == null || groupSearchBase.isEmpty()) {
        	groupSearchResultEnum = ldapContext.search(searchBase, extendedGroupSearchFilter,
                groupSearchControls);
        } else {
        	groupSearchResultEnum = ldapContext.search(groupSearchBase, extendedGroupSearchFilter,
                    groupSearchControls);
        }

        while (groupSearchResultEnum.hasMore()) {
            if (noOfGroups >= 20) {
                break;
            }

            final SearchResult groupEntry = groupSearchResultEnum.next();
            if (groupEntry == null) {
                continue;
            }
            Attributes groupAttributes = groupEntry.getAttributes();
            if (groupAttributes == null) {
                logFile.println("WARN: Attributes missing for entry " + groupEntry.getNameInNamespace());
                continue;
            }

            String dnValue;

            Attribute dnAttr = groupAttributes.get("distinguishedName");
            if (dnAttr != null) {
                dnValue = dnAttr.get().toString();
                String ouStr = "OU=";
                int indexOfOU = dnValue.indexOf(ouStr);
                if (indexOfOU > 0) {
                    dnValue = dnValue.substring(indexOfOU);

                } else {
                    dnValue = dnValue.substring(dnValue.indexOf(",") + 1);
                }

            } else {
                // If distinguishedName is not found,
                // strip off the userName from the long name for OU or sub domain
                dnValue = groupEntry.getNameInNamespace();
                dnValue = dnValue.substring(dnValue.indexOf(",") + 1);
            }
            //System.out.println("OU from dn = " + dnValue);
            Integer ouOccrs = ouOccurences.get(dnValue);
            if (ouOccrs == null) {
                //System.out.println("value = 0");
                ouOccrs = Integer.valueOf(0);
            }
            int val = ouOccrs.intValue();
            ouOccrs = Integer.valueOf(++val);
            ouOccurences.put(dnValue, ouOccrs);

            noOfGroups++;
        }

        if (!ouOccurences.isEmpty()) {
            Set<String> keys = ouOccurences.keySet();
            int maxOUOccr = 0;
            for (String key : keys) {
                int ouOccurVal = ouOccurences.get(key).intValue();
                logFile.println("INFO: No. of groups from " + key + " = " + ouOccurVal);
                if (ouOccurVal > maxOUOccr) {
                    maxOUOccr = ouOccurVal;
                    groupSearchBase = key;
                }
            }
        }

        if (groupSearchFilter == null || groupSearchFilter.isEmpty()) {
        	groupSearchFilter = groupNameAttrName + "=*";
        }

        installProps.println("SYNC_GROUP_SEARCH_BASE=" + groupSearchBase);
        installProps.println("SYNC_LDAP_GROUP_SEARCH_FILTER=" + groupSearchFilter);

        ambariProps.println("ranger.usersync.group.searchbase=" + groupSearchBase);
        ambariProps.println("ranger.usersync.group.searchfilter=" + groupSearchFilter);

    } finally {

        if (groupSearchResultEnum != null) {
            groupSearchResultEnum.close();
        }
    }
}
 
Example 19
Source File: SimpleLDAPAuthenticationManagerImpl.java    From qpid-broker-j with Apache License 2.0 4 votes vote down vote up
private String getNameFromId(final String id, final Subject gssapiIdentity)
        throws NamingException
{
    if (!isBindWithoutSearch())
    {
        InitialDirContext ctx = createSearchInitialDirContext(gssapiIdentity);

        try
        {
            SearchControls searchControls = new SearchControls();
            searchControls.setReturningAttributes(new String[]{});
            searchControls.setCountLimit(1L);
            searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);

            LOGGER.debug("Searching for '{}'", id);
            NamingEnumeration<?> namingEnum = invokeContextOperationAs(gssapiIdentity,
                                                  (PrivilegedExceptionAction<NamingEnumeration<?>>) () -> ctx.search(
                                                          _searchContext,
                                                          _searchFilter,
                                                          new String[]{id},
                                                          searchControls));

            if (namingEnum.hasMore())
            {
                SearchResult result = (SearchResult) namingEnum.next();
                String name = result.getNameInNamespace();
                LOGGER.debug("Found '{}' DN '{}'", id, name);
                return name;
            }
            else
            {
                LOGGER.debug("Not found '{}'", id);
                return null;
            }
        }
        finally
        {
            closeSafely(ctx);
        }
    }
    else
    {
        return id;
    }
}
 
Example 20
Source File: LDAPUserRegistry.java    From alfresco-repository with GNU Lesser General Public License v3.0 4 votes vote down vote up
/**
 * Instantiates a new person collection.
 * 
 * @param modifiedSince
 *            if non-null, then only descriptions of users modified since this date should be returned; if
 *            <code>null</code> then descriptions of all users should be returned.
 */
public PersonCollection(Date modifiedSince)
{
    // Choose / generate the appropriate query
    if (modifiedSince == null)
    {
        this.query = LDAPUserRegistry.this.personQuery;
    }
    else
    {
        this.query = MessageFormat.format(LDAPUserRegistry.this.personDifferentialQuery,
                LDAPUserRegistry.this.timestampFormat.format(modifiedSince));
    }

    // Estimate the size of this collection by running the entire query once, if progress
    // estimation is enabled
    if (LDAPUserRegistry.this.enableProgressEstimation)
    {
        class CountingCallback extends AbstractSearchCallback
        {
            int count;

            /*
             * (non-Javadoc)
             * @see
             * org.alfresco.repo.security.sync.ldap.LDAPUserRegistry.SearchCallback#process(javax.naming.directory
             * .SearchResult)
             */
            protected void doProcess(SearchResult result) throws NamingException, ParseException
            {
                this.count++;
                if (LDAPUserRegistry.logger.isDebugEnabled())
                {
                    String personName = result.getNameInNamespace();
                    LDAPUserRegistry.logger.debug("Processing person: " + personName);
                }
            }

            /*
             * (non-Javadoc)
             * @see org.alfresco.repo.security.sync.ldap.LDAPUserRegistry.SearchCallback#close()
             */
            public void close() throws NamingException
            {
            }

        }
        CountingCallback countingCallback = new CountingCallback();
        processQuery(countingCallback, LDAPUserRegistry.this.userSearchBase, this.query, new String[] {});
        this.totalEstimatedSize = countingCallback.count;
    }
    else
    {
        this.totalEstimatedSize = -1;
    }
}