Examples of InitialDirContext


Examples of javax.naming.directory.InitialDirContext

    String ldapUrl = LDAPLoginModule.getLdapUrl();
    List<String> ldapBases = LDAPLoginModule.getLdapBases();
    String objctClass = LDAPLoginModule.getLdapUserObjectClass();
    String[] userAttr = LDAPLoginModule.getUserAttrs();
    String[] serachAttr = { "dn" };
    InitialDirContext ctx;

    if (uid == null || pwd == null) {
      if (log.isDebug()) log.debug("Error when trying to bind user, missing username or password. Username::" + uid + " pwd::" + pwd);
      errors.insert("Username and passwort must be selected");
      return null;
    }
    String ldapUserIDAttribute = LDAPHelper.mapOlatPropertyToLdapAttribute(LDAPConstants.LDAP_USER_IDENTIFYER);
    String filter = "(&(objectClass=" + objctClass + ")(" + ldapUserIDAttribute + "=" + uid + "))";
    SearchControls ctls = new SearchControls();
    ctls.setSearchScope(SearchControls.SUBTREE_SCOPE);
    ctls.setReturningAttributes(serachAttr);
    ctx = bindSystem();
    if (ctx == null) {
      errors.insert("LDAP connection error");
      return null;
    }
    String userDN = null;
    for (String ldapBase : ldapBases) {
      try {
        NamingEnumeration<SearchResult> enm = ctx.search(ldapBase, filter, ctls);
        while (enm.hasMore()) {
          SearchResult result = enm.next();
          userDN = result.getNameInNamespace();
        }
        if (userDN != null) break;
      } catch (NamingException e) {
        log.error("NamingException when trying to bind user with username::" + uid + " on ldapBase::" + ldapBase, e);
      }
    }
    if (userDN == null) {
      log.info("Error when trying to bind user with username::" + uid + " - user not found on LDAP server"
          + (LDAPLoginModule.isCacheLDAPPwdAsOLATPwdOnLogin() ? ", trying with OLAT login provider" : ""));
      errors.insert("Username or passwort incorrect");
      return null;
    }
    // Ok, so far so good, user exists. Now try to fetch attributes using the
    // users credentials
    Hashtable<String, String> env = new Hashtable<String, String>();
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    env.put(Context.PROVIDER_URL, ldapUrl);
    env.put(Context.SECURITY_AUTHENTICATION, "simple");
    env.put(Context.SECURITY_PRINCIPAL, userDN);
    env.put(Context.SECURITY_CREDENTIALS, pwd);
    if (LDAPLoginModule.isSslEnabled()) {
      enableSSL(env);
    }

    try {
      InitialDirContext userBind = new InitialDirContext(env);
      Attributes attributes = userBind.getAttributes(userDN, userAttr);
      userBind.close();
      return attributes;
    } catch (AuthenticationException e) {
      log.info("Error when trying to bind user with username::" + uid + " - invalid LDAP password");
      errors.insert("Username or passwort incorrect");
      return null;
View Full Code Here

Examples of javax.naming.directory.InitialDirContext

        return false;
      }
    }
    try {
      acquireSyncLock();
      InitialDirContext ctx;
      List<Attributes> ldapUserList;
      List<Attributes> newLdapUserList;
      Map<Identity, Map<String, String>> changedMapIdenityMap;
      List<Identity> deletedUserList;
      String user;
      LDAPLoginManager ldapMan = LDAPLoginManager.getInstance();

      ctx = ldapMan.bindSystem();
      if (ctx == null) {
        errors.insert("LDAP connection ERROR");
        log.error("Error in LDAP batch sync: LDAP connection empty");
        freeSyncLock();
        return false;
      }
      // Get time before sync to have a save sync time when sync is successful
      Date timeBeforeSync = new Date();
      String sinceSentence = (lastSyncDate == null ? " (full sync)" : " since last sync from " + lastSyncDate);
      // create User to Delete List
      deletedUserList = ldapMan.getIdentitysDeletedInLdap(ctx);
      // delete old users
      if (deletedUserList == null || deletedUserList.size() == 0) {
        log.info("LDAP batch sync: no users to delete" + sinceSentence);
      } else {
        if (LDAPLoginModule.isDeleteRemovedLDAPUsersOnSync()) {
          // check if more not more than the defined percentages of
          // users managed in LDAP should be deleted
          // if they are over the percentage, they will not be deleted
          // by the sync job
          Manager securityManager = ManagerFactory.getManager();
          SecurityGroup ldapGroup = securityManager
              .findSecurityGroupByName(LDAPConstants.SECURITY_GROUP_LDAP);
          List<Identity> olatListIdentity = securityManager
              .getIdentitiesOfSecurityGroup(ldapGroup);
          if (olatListIdentity.size() == 0)
            log
                .info("No users managed by LDAP, can't delete users");
          else {
            int prozente = (int) (((float)deletedUserList.size() / (float) olatListIdentity.size())*100);
            if (prozente >= LDAPLoginModule.getDeleteRemovedLDAPUsersPercentage()) {
              log
                  .info("LDAP batch sync: more than "
                      + LDAPLoginModule
                          .getDeleteRemovedLDAPUsersPercentage()
                      + "% of LDAP managed users should be deleted. Please use Admin Deletion Job. Or increase deleteRemovedLDAPUsersPercentage. "
                      + prozente
                      + "% tried to delete.");
            } else {
              // delete users
              ldapMan.deletIdentities(deletedUserList);
              log.info("LDAP batch sync: "
                  + deletedUserList.size() + " users deleted"
                  + sinceSentence);
            }
          }
        } else {
          // Do nothing, only log users to logfile
          StringBuffer users = new StringBuffer();
          for (Iterator iterator = deletedUserList.iterator(); iterator
              .hasNext();) {
            Identity toBeDeleted = (Identity) iterator.next();
            users.append(toBeDeleted.getName());
            if (iterator.hasNext())
              users.append(",");
          }
          log
              .info("LDAP batch sync: "
                  + deletedUserList.size()
                  + " users detected as to be deleted"
                  + sinceSentence
                  + ". Automatic deleting is disabled in LDAPLoginModule, delete these users manually::["
                  + users.toString() + "]");
        }
      }
      // Get new and modified users from LDAP
      ldapUserList = ldapMan.getUserAttributesModifiedSince(lastSyncDate, ctx);
      Identity identity;
      // Check for new and modified users
      Map<String, String> changedAttrMap;
      newLdapUserList = new LinkedList<Attributes>();
      changedMapIdenityMap = new HashMap<Identity, Map<String, String>>();
      for (int i = 0; i < ldapUserList.size(); i++) {
        user = LDAPHelper.getAttributeValue(ldapUserList.get(i).get(
            LDAPHelper.mapOlatPropertyToLdapAttribute(LDAPConstants.LDAP_USER_IDENTIFYER)));
        identity = ldapMan.findIdentyByLdapAuthentication(user, errors);
        if (identity != null) {
          changedAttrMap = ldapMan.prepareUserPropertyForSync(ldapUserList.get(i), identity);
          if (changedAttrMap != null) changedMapIdenityMap.put(identity, changedAttrMap);
        } else {
          if (errors.isEmpty()) {
            String[] reqAttrs = LDAPHelper.checkReqAttr(ldapUserList.get(i));
            if (reqAttrs == null) newLdapUserList.add(ldapUserList.get(i));
            else log.warn("Error in LDAP batch sync: can't create user with username::" + user + " : missing required attributes::"
                + ArrayUtils.toString(reqAttrs));
          } else {
            log.warn(errors.get());
          }
        }
      }
      // sync existing users
      if (changedMapIdenityMap == null || changedMapIdenityMap.size() == 0) {
        log.info("LDAP batch sync: no users to sync" + sinceSentence);
      } else {
        Iterator<Identity> itrIdent = changedMapIdenityMap.keySet().iterator();
        while (itrIdent.hasNext()) {
          Identity ident = itrIdent.next();
          ldapMan.syncUser(changedMapIdenityMap.get(ident), ident);
        }
        log.info("LDAP batch sync: " + changedMapIdenityMap.size() + " users synced" + sinceSentence);
      }
      // create new users
      if (newLdapUserList.size() == 0) {
        log.info("LDAP batch sync: no users to create" + sinceSentence);
      } else {
        for (int i = 0; i < newLdapUserList.size(); i++) {
          ldapMan.createAndPersistUser(newLdapUserList.get(i));
          // commit new users after 100 users
          DBFactory.getInstance().intermediateCommit();
        }
        log.info("LDAP batch sync: " + newLdapUserList.size() + " users created" + sinceSentence);
      }
      // update sync time and set running flag
      lastSyncDate = timeBeforeSync;
      freeSyncLock();
      ctx.close();
      return true;
    } catch (Exception e) {
      // don't block following retries
      freeSyncLock();
      errors.insert("Unknown error");
View Full Code Here

Examples of javax.naming.directory.InitialDirContext

  public void testSystemBind() {
    if (!LDAPLoginModule.isLDAPEnabled()) return;

    //edit olatextconfig.xml for testing
    LDAPLoginManager ldapManager = LDAPLoginManager.getInstance();
    InitialDirContext ctx = ldapManager.bindSystem();
    assertEquals(true, (ctx != null));
  }
View Full Code Here

Examples of javax.naming.directory.InitialDirContext

    LDAPLoginManager ldapManager = LDAPLoginManager.getInstance();
    Manager securityManager = ManagerFactory.getManager();
    List<Identity> deletList;
   
    //should be empty
    InitialDirContext ctx = ldapManager.bindSystem();
    deletList = ldapManager.getIdentitysDeletedInLdap(ctx);
    assertEquals(0, (deletList.size()));
   
    // simulate closed session (user adding from startup job)
    DBFactory.getInstance().intermediateCommit();
View Full Code Here

Examples of javax.naming.directory.InitialDirContext

 
 
  public void testCronSync() {
    if (!LDAPLoginModule.isLDAPEnabled()) return;

    InitialDirContext ctx;
    List<Attributes> ldapUserList;
    List<Attributes> newLdapUserList;
    Map<Identity, Map<String, String>> changedMapIdenityMap;
    List<Identity> deletedUserList;
    String user;
View Full Code Here

Examples of javax.naming.directory.InitialDirContext

      if(!ldap_auth_type.equals(LDAP_AUTH_TYPE_NONE) && ldap_admin_dn.length() > 0){
        log.debug("\n\nAuthentification to LDAP - Server start");
        try {
          loginToLdapServer();
       
          authContext = new InitialDirContext(ldapAuthenticateProperties);
        } catch (Exception ae){
          log.error("\n\nAuthentification on LDAP Server failed : " + ae.getMessage());
          log.error("[Authentification on LDAP Server failed]",ae);
          return false;
        }
      }
     
      else{
        log.debug("\n\nConnection to LDAP - Server start (without Server login)");
        try{
          authContext = new InitialDirContext(ldapAuthenticateProperties);
        }catch(Exception e){
          log.error("\n\nConnection to LDAP Server failed : " + e.getMessage());
          log.error("[Connection to LDAP Server failed]",e);
          return false;
        }
View Full Code Here

Examples of javax.naming.directory.InitialDirContext

    env.put(Context.PROVIDER_URL, ldap_connection_url);
    env.put(Context.SECURITY_AUTHENTICATION, ldap_auth_type);
    env.put(Context.SECURITY_PRINCIPAL, ldap_admin_dn);
    env.put(Context.SECURITY_CREDENTIALS, ldap_passwd);
   
    authContext = new InitialDirContext(env);
   
  }
View Full Code Here

Examples of javax.naming.directory.InitialDirContext

    try {
      Hashtable env = new Hashtable();

      env.putAll(_jndiEnv);

      InitialDirContext ic = new InitialDirContext(env);

      String query = _userAttribute + '=' + userName;

      if (_baseDn != null && ! _baseDn.equals(""))
        query = _baseDn + ',' + query;

      if (_dnPrefix != null && ! _dnPrefix.equals(""))
        query = _dnPrefix + ',' + query;

      if (_dnSuffix != null && ! _dnSuffix.equals(""))
        query = query + ',' + _dnSuffix;

      Attributes attributes = ic.getAttributes(query);

      if (log.isLoggable(Level.FINE))
        log.fine("ldap-authenticator: " + query + "->" + (attributes != null));

      if (attributes == null)
View Full Code Here

Examples of javax.naming.directory.InitialDirContext

        }
        env.put(Context.REFERRAL, "throw"); // $NON-NLS-1$
        env.put("java.naming.batchsize", "0"); // $NON-NLS-1$  // $NON-NLS-2$
        env.put(Context.SECURITY_CREDENTIALS, password);
        env.put(Context.SECURITY_PRINCIPAL, username);
        dirContext = new InitialDirContext(env);
        return dirContext;
    }
View Full Code Here

Examples of javax.naming.directory.InitialDirContext

        env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory"); //$NON-NLS-1$
        env.put(Context.PROVIDER_URL, "ldap://" + host + ":" + port + "/" + rootdn); //$NON-NLS-1$ $NON-NLS-2$ $NON-NLS-3$
        env.put(Context.REFERRAL, "throw"); //$NON-NLS-1$
        env.put(Context.SECURITY_CREDENTIALS, password);
        env.put(Context.SECURITY_PRINCIPAL, username);
        dirContext = new InitialDirContext(env);
    }
View Full Code Here
TOP
Copyright © 2018 www.massapi.com. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.