Search in sources :

Example 1 with LDAPUser

use of org.olat.ldap.model.LDAPUser in project OpenOLAT by OpenOLAT.

the class LDAPLoginTest method testCronSync.

@Test
@Ignore
public void testCronSync() throws Exception {
    Assume.assumeTrue(ldapLoginModule.isLDAPEnabled());
    LdapContext ctx;
    List<LDAPUser> ldapUserList;
    List<Attributes> newLdapUserList;
    Map<Identity, Map<String, String>> changedMapIdenityMap;
    List<Identity> deletedUserList;
    LDAPError errors = new LDAPError();
    // find user changed after 2010,01,09,00,00
    ctx = ldapManager.bindSystem();
    Calendar cal = Calendar.getInstance();
    cal.set(2010, 0, 10, 0, 0, 0);
    Date syncDate = cal.getTime();
    ldapUserList = ldapDao.getUserAttributesModifiedSince(syncDate, ctx);
    assertEquals(1, ldapUserList.size());
    // find all users
    syncDate = null;
    ldapUserList = ldapDao.getUserAttributesModifiedSince(syncDate, ctx);
    assertEquals(6, ldapUserList.size());
    // prepare create- and sync-Lists for each user from defined syncTime
    Identity idenity;
    Map<String, String> changedAttrMap;
    newLdapUserList = new LinkedList<Attributes>();
    changedMapIdenityMap = new HashMap<Identity, Map<String, String>>();
    for (int i = 0; i < ldapUserList.size(); i++) {
        Attributes userAttrs = ldapUserList.get(i).getAttributes();
        String user = getAttributeValue(userAttrs.get(syncConfiguration.getOlatPropertyToLdapAttribute("userID")));
        idenity = ldapManager.findIdentityByLdapAuthentication(userAttrs, errors);
        if (idenity != null) {
            changedAttrMap = ldapManager.prepareUserPropertyForSync(userAttrs, idenity);
            if (changedAttrMap != null)
                changedMapIdenityMap.put(idenity, changedAttrMap);
        } else {
            if (errors.isEmpty()) {
                String[] reqAttrs = syncConfiguration.checkRequestAttributes(userAttrs);
                if (reqAttrs == null)
                    newLdapUserList.add(userAttrs);
                else
                    System.out.println("Cannot create User " + user + " required Attributes are missing");
            } else
                System.out.println(errors.get());
        }
    }
    // create Users in LDAP Group only existing in OLAT
    User user1 = UserManager.getInstance().createUser("hansi", "hürlima", "hansi@hansli.com");
    Identity identity1 = securityManager.createAndPersistIdentityAndUser("hansi", null, user1, "LDAP", "hansi");
    SecurityGroup secGroup1 = securityManager.findSecurityGroupByName(LDAPConstants.SECURITY_GROUP_LDAP);
    securityManager.addIdentityToSecurityGroup(identity1, secGroup1);
    user1 = UserManager.getInstance().createUser("chaspi", "meier", "chaspi@hansli.com");
    identity1 = securityManager.createAndPersistIdentityAndUser("chaspi", null, user1, "LDAP", "chaspi");
    securityManager.addIdentityToSecurityGroup(identity1, secGroup1);
    // create User to Delete List
    deletedUserList = ldapManager.getIdentitysDeletedInLdap(ctx);
    assertEquals(4, (deletedUserList.size()));
    // sync users
    Iterator<Identity> itrIdent = changedMapIdenityMap.keySet().iterator();
    while (itrIdent.hasNext()) {
        Identity ident = itrIdent.next();
        ldapManager.syncUser(changedMapIdenityMap.get(ident), ident);
    }
    // create all users
    for (int i = 0; i < newLdapUserList.size(); i++) {
        ldapManager.createAndPersistUser(newLdapUserList.get(i));
    }
    // delete all users
    ldapManager.deletIdentities(deletedUserList);
    // check if users are deleted
    deletedUserList = ldapManager.getIdentitysDeletedInLdap(ctx);
    assertEquals(0, (deletedUserList.size()));
}
Also used : LDAPUser(org.olat.ldap.model.LDAPUser) User(org.olat.core.id.User) Calendar(java.util.Calendar) Attributes(javax.naming.directory.Attributes) LDAPUser(org.olat.ldap.model.LDAPUser) SecurityGroup(org.olat.basesecurity.SecurityGroup) Date(java.util.Date) Identity(org.olat.core.id.Identity) HashMap(java.util.HashMap) Map(java.util.Map) LdapContext(javax.naming.ldap.LdapContext) Ignore(org.junit.Ignore) Test(org.junit.Test)

Example 2 with LDAPUser

use of org.olat.ldap.model.LDAPUser in project OpenOLAT by OpenOLAT.

the class LDAPLoginManagerImpl method syncRole.

private void syncRole(LdapContext ctx, List<LDAPGroup> groups, String role, Map<String, LDAPUser> dnToIdentityKeyMap, LDAPError errors) {
    if (groups == null || groups.isEmpty())
        return;
    for (LDAPGroup group : groups) {
        List<String> members = group.getMembers();
        if (members != null && members.size() > 0) {
            for (String member : members) {
                LDAPUser ldapUser = getLDAPUser(ctx, member, dnToIdentityKeyMap, errors);
                if (ldapUser != null && ldapUser.getCachedIdentity() != null) {
                    syncRole(ldapUser, role);
                }
            }
        }
        dbInstance.commitAndCloseSession();
    }
}
Also used : LDAPUser(org.olat.ldap.model.LDAPUser) LDAPGroup(org.olat.ldap.model.LDAPGroup)

Example 3 with LDAPUser

use of org.olat.ldap.model.LDAPUser in project OpenOLAT by OpenOLAT.

the class LDAPLoginManagerImpl method doBatchSync.

/**
 * Execute Batch Sync. Will update all Attributes of LDAP users in OLAt, create new users and delete users in OLAT.
 * Can be configured in ldapContext.xml
 *
 * @param LDAPError
 */
@Override
public boolean doBatchSync(LDAPError errors) {
    // property read.
    synchronized (LDAPLoginManagerImpl.class) {
        if (batchSyncIsRunning) {
            // don't run twice, skip this execution
            log.info("LDAP user doBatchSync started, but another job is still running - skipping this sync");
            errors.insert("BatchSync already running by concurrent process");
            return false;
        }
    }
    WorkThreadInformations.setLongRunningTask("ldapSync");
    coordinator.getEventBus().fireEventToListenersOf(new LDAPEvent(LDAPEvent.SYNCHING), ldapSyncLockOres);
    lastSyncDate = null;
    LdapContext ctx = null;
    boolean success = false;
    try {
        acquireSyncLock();
        long startTime = System.currentTimeMillis();
        ctx = bindSystem();
        if (ctx == null) {
            errors.insert("LDAP connection ERROR");
            log.error("LDAP batch sync: LDAP connection empty", null);
            freeSyncLock();
            success = false;
            return success;
        }
        Date timeBeforeSync = new Date();
        // check server capabilities
        // Get time before sync to have a save sync time when sync is successful
        String sinceSentence = (lastSyncDate == null ? "" : " since last sync from " + lastSyncDate);
        doBatchSyncDeletedUsers(ctx, sinceSentence);
        // bind again to use an initial unmodified context. lookup of server-properties might fail otherwise!
        ctx.close();
        ctx = bindSystem();
        Map<String, LDAPUser> dnToIdentityKeyMap = new HashMap<>();
        List<LDAPUser> ldapUsers = doBatchSyncNewAndModifiedUsers(ctx, sinceSentence, dnToIdentityKeyMap, errors);
        ctx.close();
        ctx = bindSystem();
        // sync groups by LDAP groups or attributes
        doBatchSyncGroups(ctx, ldapUsers, dnToIdentityKeyMap, errors);
        // sync roles
        doBatchSyncRoles(ctx, ldapUsers, dnToIdentityKeyMap, errors);
        // update sync time and set running flag
        lastSyncDate = timeBeforeSync;
        ctx.close();
        success = true;
        log.audit("LDAP batch sync done: " + success + " in " + ((System.currentTimeMillis() - startTime) / 1000) + "s");
        return success;
    } catch (Exception e) {
        errors.insert("Unknown error");
        log.error("LDAP batch sync, unknown reason", e);
        success = false;
        return success;
    } finally {
        WorkThreadInformations.unsetLongRunningTask("ldapSync");
        freeSyncLock();
        if (ctx != null) {
            try {
                ctx.close();
            } catch (NamingException e) {
            // try but failed silently
            }
        }
        LDAPEvent endEvent = new LDAPEvent(LDAPEvent.SYNCHING_ENDED);
        endEvent.setTimestamp(new Date());
        endEvent.setSuccess(success);
        endEvent.setErrors(errors);
        coordinator.getEventBus().fireEventToListenersOf(endEvent, ldapSyncLockOres);
    }
}
Also used : HashMap(java.util.HashMap) LDAPUser(org.olat.ldap.model.LDAPUser) LDAPEvent(org.olat.ldap.LDAPEvent) Date(java.util.Date) NamingException(javax.naming.NamingException) AuthenticationException(javax.naming.AuthenticationException) NamingException(javax.naming.NamingException) InitialLdapContext(javax.naming.ldap.InitialLdapContext) LdapContext(javax.naming.ldap.LdapContext)

Example 4 with LDAPUser

use of org.olat.ldap.model.LDAPUser 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 5 with LDAPUser

use of org.olat.ldap.model.LDAPUser 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

LDAPUser (org.olat.ldap.model.LDAPUser)22 Attributes (javax.naming.directory.Attributes)10 IdentityRef (org.olat.basesecurity.IdentityRef)8 Identity (org.olat.core.id.Identity)8 HashMap (java.util.HashMap)6 AuthenticationException (javax.naming.AuthenticationException)6 NamingException (javax.naming.NamingException)6 LdapContext (javax.naming.ldap.LdapContext)6 LDAPGroup (org.olat.ldap.model.LDAPGroup)6 ArrayList (java.util.ArrayList)4 Date (java.util.Date)4 Map (java.util.Map)4 InitialLdapContext (javax.naming.ldap.InitialLdapContext)4 SimpleDateFormat (java.text.SimpleDateFormat)2 Calendar (java.util.Calendar)2 HashSet (java.util.HashSet)2 Ignore (org.junit.Ignore)2 Test (org.junit.Test)2 SecurityGroup (org.olat.basesecurity.SecurityGroup)2 IdentityRefImpl (org.olat.basesecurity.model.IdentityRefImpl)2