Search in sources :

Example 66 with Attributes

use of javax.naming.directory.Attributes in project OpenOLAT by OpenOLAT.

the class LDAPLoginManagerImpl method doSyncSingleUser.

@Override
public void doSyncSingleUser(Identity ident) {
    LdapContext ctx = bindSystem();
    if (ctx == null) {
        log.error("could not bind to ldap", null);
    }
    String userDN = ldapDao.searchUserDNByUid(ident.getName(), ctx);
    final List<Attributes> ldapUserList = new ArrayList<Attributes>();
    // TODO: use userDN instead of filter to get users attribs
    ldapDao.searchInLdap(new LDAPVisitor() {

        @Override
        public void visit(SearchResult result) {
            Attributes resAttribs = result.getAttributes();
            log.debug("        found : " + resAttribs.size() + " attributes in result " + result.getName());
            ldapUserList.add(resAttribs);
        }
    }, userDN, syncConfiguration.getUserAttributes(), ctx);
    Attributes attrs = ldapUserList.get(0);
    Map<String, String> olatProToSync = prepareUserPropertyForSync(attrs, ident);
    if (olatProToSync != null) {
        syncUser(olatProToSync, ident);
    }
}
Also used : Attributes(javax.naming.directory.Attributes) ArrayList(java.util.ArrayList) SearchResult(javax.naming.directory.SearchResult) InitialLdapContext(javax.naming.ldap.InitialLdapContext) LdapContext(javax.naming.ldap.LdapContext)

Example 67 with Attributes

use of javax.naming.directory.Attributes in project OpenOLAT by OpenOLAT.

the class LDAPLoginManagerImpl method changePassword.

/**
 * Change the password on the LDAP server.
 * @see org.olat.ldap.LDAPLoginManager#changePassword(org.olat.core.id.Identity, java.lang.String, org.olat.ldap.LDAPError)
 */
@Override
public boolean changePassword(Identity identity, String pwd, LDAPError errors) {
    String uid = identity.getName();
    String ldapUserPasswordAttribute = syncConfiguration.getLdapUserPasswordAttribute();
    try {
        LdapContext ctx = bindSystem();
        String dn = ldapDao.searchUserDNByUid(uid, ctx);
        List<ModificationItem> modificationItemList = new ArrayList<>();
        if (ldapLoginModule.isActiveDirectory()) {
            boolean resetLockoutTime = false;
            if (ldapLoginModule.isResetLockTimoutOnPasswordChange()) {
                String[] attrs = syncConfiguration.getUserAttributes();
                List<String> attrList = new ArrayList<>(Arrays.asList(attrs));
                attrList.add("lockoutTime");
                attrs = attrList.toArray(new String[attrList.size()]);
                Attributes attributes = ctx.getAttributes(dn, attrs);
                Attribute lockoutTimeAttr = attributes.get("lockoutTime");
                if (lockoutTimeAttr != null && lockoutTimeAttr.size() > 0) {
                    Object lockoutTime = lockoutTimeAttr.get();
                    if (lockoutTime != null && !lockoutTime.equals("0")) {
                        resetLockoutTime = true;
                    }
                }
            }
            // active directory need the password enquoted and unicoded (but little-endian)
            String quotedPassword = "\"" + pwd + "\"";
            char[] unicodePwd = quotedPassword.toCharArray();
            byte[] pwdArray = new byte[unicodePwd.length * 2];
            for (int i = 0; i < unicodePwd.length; i++) {
                pwdArray[i * 2 + 1] = (byte) (unicodePwd[i] >>> 8);
                pwdArray[i * 2 + 0] = (byte) (unicodePwd[i] & 0xff);
            }
            BasicAttribute userPasswordAttribute = new BasicAttribute(ldapUserPasswordAttribute, pwdArray);
            modificationItemList.add(new ModificationItem(DirContext.REPLACE_ATTRIBUTE, userPasswordAttribute));
            if (resetLockoutTime) {
                BasicAttribute lockTimeoutAttribute = new BasicAttribute("lockoutTime", "0");
                modificationItemList.add(new ModificationItem(DirContext.REPLACE_ATTRIBUTE, lockTimeoutAttribute));
            }
        } else {
            BasicAttribute userPasswordAttribute = new BasicAttribute(ldapUserPasswordAttribute, pwd);
            modificationItemList.add(new ModificationItem(DirContext.REPLACE_ATTRIBUTE, userPasswordAttribute));
        }
        ModificationItem[] modificationItems = modificationItemList.toArray(new ModificationItem[modificationItemList.size()]);
        ctx.modifyAttributes(dn, modificationItems);
        ctx.close();
        return true;
    } catch (NamingException e) {
        log.error("NamingException when trying to change password with username::" + uid, e);
        errors.insert("Cannot change the password");
        return false;
    } catch (Exception e) {
        log.error("Unexpected exception when trying to change password with username::" + uid, e);
        errors.insert("Cannot change the password");
        return false;
    }
}
Also used : BasicAttribute(javax.naming.directory.BasicAttribute) Attribute(javax.naming.directory.Attribute) BasicAttribute(javax.naming.directory.BasicAttribute) ArrayList(java.util.ArrayList) Attributes(javax.naming.directory.Attributes) NamingException(javax.naming.NamingException) AuthenticationException(javax.naming.AuthenticationException) ModificationItem(javax.naming.directory.ModificationItem) NamingException(javax.naming.NamingException) InitialLdapContext(javax.naming.ldap.InitialLdapContext) LdapContext(javax.naming.ldap.LdapContext)

Example 68 with Attributes

use of javax.naming.directory.Attributes in project OpenOLAT by OpenOLAT.

the class LDAPLoginManagerImpl method authenticate.

@Override
public Identity authenticate(String username, String pwd, LDAPError ldapError) {
    long start = System.nanoTime();
    // authenticate against LDAP server
    Attributes attrs = bindUser(username, pwd, ldapError);
    long takes = System.nanoTime() - start;
    if (takes > LDAPLoginModule.WARNING_LIMIT) {
        log.warn("LDAP Authentication takes (ms): " + (takes / 1000000));
    }
    if (ldapError.isEmpty() && attrs != null) {
        Identity identity = findIdentityByLdapAuthentication(attrs, ldapError);
        if (!ldapError.isEmpty()) {
            return null;
        }
        if (identity == null) {
            if (ldapLoginModule.isCreateUsersOnLogin()) {
                // User authenticated but not yet existing - create as new OLAT user
                createAndPersistUser(attrs);
                identity = findIdentityByLdapAuthentication(attrs, ldapError);
            } else {
                ldapError.insert("login.notauthenticated");
            }
        } else {
            // User does already exist - just sync attributes
            Map<String, String> olatProToSync = prepareUserPropertyForSync(attrs, identity);
            if (olatProToSync != null) {
                syncUser(olatProToSync, identity);
            }
        }
        // Add or update an OLAT authentication token for this user if configured in the module
        if (identity != null && ldapLoginModule.isCacheLDAPPwdAsOLATPwdOnLogin()) {
            // there is no WEBDAV token but an HA1, the HA1 is linked to the OLAT one.
            CoreSpringFactory.getImpl(OLATAuthManager.class).synchronizeOlatPasswordAndUsername(identity, identity, username, pwd);
        }
        return identity;
    }
    return null;
}
Also used : Attributes(javax.naming.directory.Attributes) OLATAuthManager(org.olat.login.auth.OLATAuthManager) Identity(org.olat.core.id.Identity)

Example 69 with Attributes

use of javax.naming.directory.Attributes in project OpenOLAT by OpenOLAT.

the class LDAPLoginManagerImpl method createAndPersistUser.

@Override
public Identity createAndPersistUser(String uid) {
    String ldapUserIDAttribute = syncConfiguration.getOlatPropertyToLdapAttribute(LDAPConstants.LDAP_USER_IDENTIFYER);
    String filter = ldapDao.buildSearchUserFilter(ldapUserIDAttribute, uid);
    LdapContext ctx = bindSystem();
    String userDN = ldapDao.searchUserDNByUid(uid, ctx);
    log.info("create and persist user identifier by userDN: " + userDN + " with filter: " + filter);
    LDAPUserVisitor visitor = new LDAPUserVisitor(syncConfiguration);
    ldapDao.search(visitor, userDN, filter, syncConfiguration.getUserAttributes(), ctx);
    Identity newIdentity = null;
    List<LDAPUser> ldapUser = visitor.getLdapUserList();
    if (ldapUser != null && ldapUser.size() > 0) {
        Attributes userAttributes = ldapUser.get(0).getAttributes();
        newIdentity = createAndPersistUser(userAttributes);
    }
    return newIdentity;
}
Also used : Attributes(javax.naming.directory.Attributes) LDAPUser(org.olat.ldap.model.LDAPUser) Identity(org.olat.core.id.Identity) InitialLdapContext(javax.naming.ldap.InitialLdapContext) LdapContext(javax.naming.ldap.LdapContext)

Example 70 with Attributes

use of javax.naming.directory.Attributes in project OpenOLAT by OpenOLAT.

the class LDAPLoginManagerImpl method doBatchSyncNewAndModifiedUsers.

private List<LDAPUser> doBatchSyncNewAndModifiedUsers(LdapContext ctx, String sinceSentence, Map<String, LDAPUser> dnToIdentityKeyMap, LDAPError errors) {
    // Get new and modified users from LDAP
    int count = 0;
    List<LDAPUser> ldapUserList = ldapDao.getUserAttributesModifiedSince(lastSyncDate, ctx);
    // Check for new and modified users
    List<LDAPUser> newLdapUserList = new ArrayList<LDAPUser>();
    Map<IdentityRef, Map<String, String>> changedMapIdentityMap = new HashMap<>();
    for (LDAPUser ldapUser : ldapUserList) {
        String user = null;
        try {
            Attributes userAttrs = ldapUser.getAttributes();
            String uidProp = syncConfiguration.getOlatPropertyToLdapAttribute(LDAPConstants.LDAP_USER_IDENTIFYER);
            user = getAttributeValue(userAttrs.get(uidProp));
            Identity identity = findIdentityByLdapAuthentication(userAttrs, errors);
            if (identity != null) {
                Map<String, String> changedAttrMap = prepareUserPropertyForSync(userAttrs, identity);
                if (changedAttrMap != null) {
                    changedMapIdentityMap.put(identity, changedAttrMap);
                }
                if (StringHelper.containsNonWhitespace(ldapUser.getDn())) {
                    dnToIdentityKeyMap.put(ldapUser.getDn(), ldapUser);
                    ldapUser.setCachedIdentity(new IdentityRefImpl(identity.getKey()));
                }
            } else if (errors.isEmpty()) {
                String[] reqAttrs = syncConfiguration.checkRequestAttributes(userAttrs);
                if (reqAttrs == null) {
                    newLdapUserList.add(ldapUser);
                } else {
                    log.warn("LDAP batch sync: can't create user with username::" + user + " : missing required attributes::" + ArrayUtils.toString(reqAttrs), null);
                }
            } else {
                log.warn(errors.get(), null);
            }
        } catch (Exception e) {
            // catch here to go on with other users on exeptions!
            log.error("some error occured in looping over set of changed user-attributes, actual user " + user + ". Will still continue with others.", e);
            errors.insert("Cannot sync user: " + user);
        } finally {
            dbInstance.commit();
            if (count % 10 == 0) {
                dbInstance.closeSession();
            }
        }
        if (count % 1000 == 0) {
            log.info("Retrieve " + count + "/" + ldapUserList.size() + " users in LDAP server");
        }
        count++;
    }
    // sync existing users
    if (changedMapIdentityMap == null || changedMapIdentityMap.isEmpty()) {
        log.info("LDAP batch sync: no users to sync" + sinceSentence);
    } else {
        int syncCount = 0;
        for (IdentityRef ident : changedMapIdentityMap.keySet()) {
            // sync user is exception save, no try/catch needed
            try {
                syncCount++;
                syncUser(changedMapIdentityMap.get(ident), ident);
            } catch (Exception e) {
                errors.insert("Cannot sync user: " + ident);
            } finally {
                dbInstance.commit();
                if (syncCount % 20 == 0) {
                    dbInstance.closeSession();
                }
            }
            if (syncCount % 1000 == 0) {
                log.info("Update " + syncCount + "/" + changedMapIdentityMap.size() + " LDAP users");
            }
        }
        log.info("LDAP batch sync: " + changedMapIdentityMap.size() + " users synced" + sinceSentence);
    }
    // create new users
    if (newLdapUserList.isEmpty()) {
        log.info("LDAP batch sync: no users to create" + sinceSentence);
    } else {
        int newCount = 0;
        for (LDAPUser ldapUser : newLdapUserList) {
            Attributes userAttrs = ldapUser.getAttributes();
            try {
                newCount++;
                Identity identity = createAndPersistUser(userAttrs);
                if (identity != null && StringHelper.containsNonWhitespace(ldapUser.getDn())) {
                    dnToIdentityKeyMap.put(ldapUser.getDn(), ldapUser);
                    ldapUser.setCachedIdentity(new IdentityRefImpl(identity.getKey()));
                }
            } catch (Exception e) {
                // catch here to go on with other users on exeptions!
                log.error("some error occured while creating new users, actual userAttribs " + userAttrs + ". Will still continue with others.", e);
            } finally {
                dbInstance.commit();
                if (newCount % 20 == 0) {
                    dbInstance.closeSession();
                }
            }
            if (newCount % 1000 == 0) {
                log.info("Create " + count + "/" + newLdapUserList.size() + " LDAP users");
            }
        }
        log.info("LDAP batch sync: " + newLdapUserList.size() + " users created" + sinceSentence);
    }
    dbInstance.commitAndCloseSession();
    return ldapUserList;
}
Also used : HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) Attributes(javax.naming.directory.Attributes) LDAPUser(org.olat.ldap.model.LDAPUser) NamingException(javax.naming.NamingException) AuthenticationException(javax.naming.AuthenticationException) IdentityRefImpl(org.olat.basesecurity.model.IdentityRefImpl) IdentityRef(org.olat.basesecurity.IdentityRef) Identity(org.olat.core.id.Identity) Map(java.util.Map) HashMap(java.util.HashMap)

Aggregations

Attributes (javax.naming.directory.Attributes)252 Attribute (javax.naming.directory.Attribute)135 SearchResult (javax.naming.directory.SearchResult)87 NamingException (javax.naming.NamingException)84 BasicAttributes (javax.naming.directory.BasicAttributes)72 ArrayList (java.util.ArrayList)61 BasicAttribute (javax.naming.directory.BasicAttribute)56 SearchControls (javax.naming.directory.SearchControls)55 DirContext (javax.naming.directory.DirContext)49 NamingEnumeration (javax.naming.NamingEnumeration)44 Test (org.junit.Test)34 InitialDirContext (javax.naming.directory.InitialDirContext)32 LdapContext (javax.naming.ldap.LdapContext)29 HashMap (java.util.HashMap)25 InitialLdapContext (javax.naming.ldap.InitialLdapContext)24 Hashtable (java.util.Hashtable)20 HashSet (java.util.HashSet)18 Map (java.util.Map)17 IOException (java.io.IOException)16 Identity (org.olat.core.id.Identity)16