Index: lams_central/conf/xdoclet/web-settings.xml =================================================================== diff -u -r59c2c195b0b2884adbd5618fda9b8aa09050c3d2 -r43dfd9f833c87c58f4dc4a61f386b6c2cf961720 --- lams_central/conf/xdoclet/web-settings.xml (.../web-settings.xml) (revision 59c2c195b0b2884adbd5618fda9b8aa09050c3d2) +++ lams_central/conf/xdoclet/web-settings.xml (.../web-settings.xml) (revision 43dfd9f833c87c58f4dc4a61f386b6c2cf961720) @@ -14,6 +14,7 @@ classpath:/org/lamsfoundation/lams/workspace/workspaceApplicationContext.xml classpath:/org/lamsfoundation/lams/web/webApplicationContext.xml classpath:/org/lamsfoundation/lams/integrationContext.xml + classpath:/org/lamsfoundation/lams/usermanagement/ldapContext.xml classpath:/org/lamsfoundation/lams/lesson/lessonApplicationContext.xml classpath:/org/lamsfoundation/lams/learning/learningApplicationContext.xml Index: lams_central/src/java/org/lamsfoundation/lams/security/LDAPAuthenticator.java =================================================================== diff -u -r54f5e17d1a5e8baae23bb9332f83ad8d8e5ac405 -r43dfd9f833c87c58f4dc4a61f386b6c2cf961720 --- lams_central/src/java/org/lamsfoundation/lams/security/LDAPAuthenticator.java (.../LDAPAuthenticator.java) (revision 54f5e17d1a5e8baae23bb9332f83ad8d8e5ac405) +++ lams_central/src/java/org/lamsfoundation/lams/security/LDAPAuthenticator.java (.../LDAPAuthenticator.java) (revision 43dfd9f833c87c58f4dc4a61f386b6c2cf961720) @@ -23,26 +23,19 @@ /* $$Id$$ */ package org.lamsfoundation.lams.security; -import java.util.ArrayList; -import java.util.Date; -import java.util.List; import java.util.Properties; import javax.naming.AuthenticationException; import javax.naming.AuthenticationNotSupportedException; import javax.naming.Context; import javax.naming.NamingEnumeration; -import javax.naming.NamingException; -import javax.naming.directory.Attribute; import javax.naming.directory.Attributes; import javax.naming.ldap.InitialLdapContext; import org.apache.commons.lang.StringUtils; import org.apache.log4j.Logger; -import org.lamsfoundation.lams.usermanagement.AuthenticationMethod; -import org.lamsfoundation.lams.usermanagement.Organisation; -import org.lamsfoundation.lams.usermanagement.Role; import org.lamsfoundation.lams.usermanagement.User; +import org.lamsfoundation.lams.usermanagement.service.LdapService; import org.lamsfoundation.lams.usermanagement.service.UserManagementService; import org.lamsfoundation.lams.util.Configuration; import org.lamsfoundation.lams.util.ConfigurationKeys; @@ -54,6 +47,7 @@ private static Logger log = Logger.getLogger(LDAPAuthenticator.class); private static UserManagementService service; + private static LdapService ldapService; private static final String INITIAL_CONTEXT_FACTORY_VALUE = "com.sun.jndi.ldap.LdapCtxFactory"; private Attributes attrs = null; @@ -68,6 +62,15 @@ } return service; } + + private LdapService getLdapService() { + if (ldapService==null) { + WebApplicationContext ctx = WebApplicationContextUtils + .getWebApplicationContext(HttpSessionManager.getInstance().getServletContext()); + ldapService = (LdapService) ctx.getBean("ldapService"); + } + return ldapService; + } public Attributes getAttrs() { return attrs; @@ -117,15 +120,21 @@ Attributes attrs = ctx.getAttributes(userDN); setAttrs(attrs); - UserManagementService service = getService(); - if (service.getUserByLogin(username)!=null) { - // update user's attributes and org membership + if (log.isDebugEnabled()) { + NamingEnumeration enumAttrs = attrs.getAll(); + while (enumAttrs.hasMoreElements()) { + log.debug(enumAttrs.next()); + } } - // debug attrs - NamingEnumeration enumAttrs = attrs.getAll(); - while (enumAttrs.hasMoreElements()) { - System.out.println(enumAttrs.next()); + if (Configuration.getAsBoolean(ConfigurationKeys.LDAP_UPDATE_ON_LOGIN)) { + UserManagementService service = getService(); + User user = service.getUserByLogin(username); + if (user != null) { + // update user's attributes and org membership + getLdapService().updateLDAPUser(user, attrs); + getLdapService().addLDAPUser(attrs, user.getUserId()); + } } return true; @@ -136,7 +145,7 @@ } catch (AuthenticationException e) { log.info("===> Incorrect username ("+userDN+") or password ("+credential+"): "+e.getMessage()); } catch (Exception e) { - log.error("===> LDAP exception: " + e); + log.error("===> LDAP exception: " + e, e); } finally { try { @@ -156,139 +165,5 @@ return false; } - - protected boolean createLDAPUser(Attributes attrs) { - UserManagementService service = getService(); - User user = new User(); - try { - String login = getSingleAttributeString(attrs.get(Configuration.get(ConfigurationKeys.LDAP_LOGIN_ATTR))); - String fname = getSingleAttributeString(attrs.get(Configuration.get(ConfigurationKeys.LDAP_FIRST_NAME_ATTR))); - String lname = getSingleAttributeString(attrs.get(Configuration.get(ConfigurationKeys.LDAP_LAST_NAME_ATTR))); - String email = getSingleAttributeString(attrs.get(Configuration.get(ConfigurationKeys.LDAP_EMAIL_ATTR))); - String phone = getSingleAttributeString(attrs.get(Configuration.get(ConfigurationKeys.LDAP_PHONE_ATTR))); - String fax = getSingleAttributeString(attrs.get(Configuration.get(ConfigurationKeys.LDAP_FAX_ATTR))); - String mobile = getSingleAttributeString(attrs.get(Configuration.get(ConfigurationKeys.LDAP_MOBILE_ATTR))); - if (login!=null && login.trim().length()>0) { - log.debug("===> using LDAP attributes: "+login+","+fname+","+lname+","+email+","+phone+","+fax+","+mobile); - user.setLogin(login); - user.setPassword("dummy"); // password column is not-null - user.setFirstName(fname); - user.setLastName(lname); - user.setEmail(email); - user.setDayPhone(phone); - user.setFax(fax); - user.setMobilePhone(mobile); - user.setAuthenticationMethod((AuthenticationMethod)service - .findById(AuthenticationMethod.class, AuthenticationMethod.LDAP)); - user.setFlashTheme(service.getDefaultFlashTheme()); - user.setHtmlTheme(service.getDefaultHtmlTheme()); - user.setDisabledFlag(false); - user.setCreateDate(new Date()); - user.setLocale(service.getDefaultLocale()); - service.save(user); - // TODO write audit log - return true; - } else { - log.error("===> Login name from LDAP is empty - user not created."); - } - } catch (Exception e) { - log.error("===> Exception occurred while creating LDAP user: ", e); - } - return false; - } - - protected boolean addLDAPUser(Attributes attrs, Integer userId) { - UserManagementService service = getService(); - String orgCode = getSingleAttributeString(attrs.get(Configuration.get(ConfigurationKeys.LDAP_ORG_CODE_ATTR))); - List ldapRoles = getAttributeStrings(attrs.get(Configuration.get(ConfigurationKeys.LDAP_ROLES_ATTR))); - log.debug("orgCode: "+orgCode); - log.debug("ldapRoles: "+ldapRoles); - List orgList = (List)service.findByProperty(Organisation.class, "code", orgCode); - if (orgList!=null && !orgList.isEmpty()) { - if (orgList.size()==1) { - Organisation org = (Organisation)orgList.get(0); - List roleIds = getRoleIds(ldapRoles); - if (roleIds!=null && !roleIds.isEmpty()) { - User user = (User)service.findById(User.class, userId); - log.debug("userId: "+userId); - log.debug("orgId: "+org.getOrganisationId()); - log.debug("roleIds: "+roleIds); - service.setRolesForUserOrganisation(user, org.getOrganisationId(), roleIds); - return true; - } - } else { - log.warn("More than one LAMS organisation found with the code: "+orgCode); - } - } else { - log.warn("LDAP organisation code: "+orgCode+" doesn't correspond to any LAMS organisation code."); - } - return false; - } - - // get list of LAMS role ids from list of ldap roles - private List getRoleIds(List ldapRoles) { - if (ldapRoles!=null) { - ArrayList roleIds = new ArrayList(); - for (String role : ldapRoles) { - if (Configuration.get(ConfigurationKeys.LDAP_LEARNER_MAP).indexOf(role) > 0 - && !roleIds.contains(Role.ROLE_LEARNER.toString())) { - roleIds.add(Role.ROLE_LEARNER.toString()); - } - if (Configuration.get(ConfigurationKeys.LDAP_MONITOR_MAP).indexOf(role) > 0 - && !roleIds.contains(Role.ROLE_MONITOR.toString())) { - roleIds.add(Role.ROLE_MONITOR.toString()); - } - if (Configuration.get(ConfigurationKeys.LDAP_AUTHOR_MAP).indexOf(role) > 0 - && !roleIds.contains(Role.ROLE_AUTHOR.toString())) { - roleIds.add(Role.ROLE_AUTHOR.toString()); - } - if (Configuration.get(ConfigurationKeys.LDAP_GROUP_ADMIN_MAP).indexOf(role) > 0 - && !roleIds.contains(Role.ROLE_GROUP_ADMIN.toString())) { - roleIds.add(Role.ROLE_GROUP_ADMIN.toString()); - } - if (Configuration.get(ConfigurationKeys.LDAP_GROUP_MANAGER_MAP).indexOf(role) > 0 - && !roleIds.contains(Role.ROLE_GROUP_MANAGER.toString())) { - roleIds.add(Role.ROLE_GROUP_MANAGER.toString()); - } - } - return roleIds; - } - return null; - } - - // get the multiple values of an ldap attribute - private List getAttributeStrings(Attribute attr) { - try { - ArrayList attrValues = new ArrayList(); - if (attr!=null) { - NamingEnumeration attrEnum = attr.getAll(); - while (attrEnum.hasMore()) { - Object attrValue = attrEnum.next(); - if (attrValue!=null) { - attrValues.add(attrValue.toString()); - } - } - return attrValues; - } - } catch (NamingException e) { - log.error("===> Naming exception occurred: "+e.getMessage()); - } - return null; - } - - // get the single (string) value of an ldap attribute - private String getSingleAttributeString(Attribute attr) { - try { - if (attr!=null) { - Object attrValue = attr.get(); - if (attrValue!=null) { - return attrValue.toString(); - } - } - } catch (NamingException e) { - log.error("===> Naming exception occurred: "+e.getMessage()); - } - return null; - } } \ No newline at end of file Index: lams_central/src/java/org/lamsfoundation/lams/security/UniversalLoginModule.java =================================================================== diff -u -r54f5e17d1a5e8baae23bb9332f83ad8d8e5ac405 -r43dfd9f833c87c58f4dc4a61f386b6c2cf961720 --- lams_central/src/java/org/lamsfoundation/lams/security/UniversalLoginModule.java (.../UniversalLoginModule.java) (revision 54f5e17d1a5e8baae23bb9332f83ad8d8e5ac405) +++ lams_central/src/java/org/lamsfoundation/lams/security/UniversalLoginModule.java (.../UniversalLoginModule.java) (revision 43dfd9f833c87c58f4dc4a61f386b6c2cf961720) @@ -40,7 +40,6 @@ import java.sql.SQLException; import java.util.ArrayList; import java.util.HashMap; -import java.util.List; import java.util.Map; import javax.naming.InitialContext; @@ -53,11 +52,10 @@ import javax.sql.DataSource; import org.apache.log4j.Logger; -import org.lamsfoundation.lams.usermanagement.AuthenticationMethod; -import org.lamsfoundation.lams.usermanagement.AuthenticationMethodParameter; import org.lamsfoundation.lams.usermanagement.AuthenticationMethodType; import org.lamsfoundation.lams.usermanagement.Role; import org.lamsfoundation.lams.usermanagement.User; +import org.lamsfoundation.lams.usermanagement.service.LdapService; import org.lamsfoundation.lams.usermanagement.service.UserManagementService; import org.lamsfoundation.lams.util.Configuration; import org.lamsfoundation.lams.util.ConfigurationKeys; @@ -77,12 +75,12 @@ protected String dsJndiName; protected String rolesQuery; protected String principalsQuery; - //protected String propertyFilePath; public void initialize(Subject subject, CallbackHandler callbackHandler, Map sharedState, Map options) { super.initialize(subject, callbackHandler, sharedState, options); + // TODO cleanup unneeded authentication method related classes //from options to get path to property file -> authentication.xml //propertyFilePath = (String) options.get("authenticationPropertyFile"); //load authentication property file @@ -108,6 +106,7 @@ String username = getUsername(); WebApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(HttpSessionManager.getInstance().getServletContext()); UserManagementService service = (UserManagementService) ctx.getBean("userManagementService"); + LdapService ldapService = (LdapService) ctx.getBean("ldapService"); User user = service.getUserByLogin(username); log.debug("===> authenticating user: " + username); @@ -119,9 +118,9 @@ isValid = ldap.authenticate(username, inputPassword); if (isValid) { // create a new user log.info("===> Creating new user for LDAP username: " + username); - if (ldap.createLDAPUser(ldap.getAttrs())) { + if (ldapService.createLDAPUser(ldap.getAttrs())) { user = service.getUserByLogin(username); - if (!ldap.addLDAPUser(ldap.getAttrs(), user.getUserId())) { + if (!ldapService.addLDAPUser(ldap.getAttrs(), user.getUserId())) { log.error("===> Couldn't add LDAP user: "+username+" to organisation."); } } else { @@ -141,44 +140,15 @@ return false; } - AuthenticationMethod method = user.getAuthenticationMethod(); - /*try { - AuthenticationMethodConfigurer.configure(method); - - // use User's AuthMethod's dsJndiName and rolesQuery if set, otherwise use LAMS-Database's - AuthenticationMethodParameter dsParam = method.getParameterByName("dsJndiName"); - AuthenticationMethodParameter rolesQueryParam = method.getParameterByName("rolesQuery"); - if (dsParam!=null && rolesQueryParam!=null) { - this.dsJndiName = dsParam.getValue(); - this.rolesQuery = rolesQueryParam.getValue(); - } else { - AuthenticationMethod defaultAuthMethod = (AuthenticationMethod)service - .findById(AuthenticationMethod.class, AuthenticationMethod.DB); - this.dsJndiName = defaultAuthMethod.getParameterByName("dsJndiName").getValue(); - this.rolesQuery = defaultAuthMethod.getParameterByName("rolesQuery").getValue(); - } - } catch (Exception e) { - log.error("===> Error retrieving authentication method parameters : " + e, e); - return false; - } - - //for debug purpose only - if (log.isDebugEnabled()) { - List parameters = method.getAuthenticationMethodParameters(); - for (int i = 0; i < parameters.size(); i++) { - AuthenticationMethodParameter mp = (AuthenticationMethodParameter) parameters.get(i); - log.debug("===>" + mp.getName() + " = " + mp.getValue()); - } - }*/ - if (!isValid) { - String type = method.getAuthenticationMethodType().getDescription(); + String type = user.getAuthenticationMethod().getAuthenticationMethodType().getDescription(); log.debug("===> authentication type: " + type); if (AuthenticationMethodType.LDAP.equals(type)) { LDAPAuthenticator authenticator = new LDAPAuthenticator(); isValid = authenticator.authenticate(username,inputPassword); + // if ldap user profile has updated, udpate user object for dto below + user = service.getUserByLogin(username); } else if (AuthenticationMethodType.LAMS.equals(type)) { - // DatabaseAuthenticator authenticator = new DatabaseAuthenticator(method); DatabaseAuthenticator authenticator = new DatabaseAuthenticator(dsJndiName, principalsQuery); isValid = authenticator.authenticate(username,inputPassword); } else if (AuthenticationMethodType.WEB_AUTH.equals(type)) { Index: lams_common/db/sql/insert_lams_unix_config_data.sql =================================================================== diff -u -raa7e502bb28fa1df94980fadea3876a83e842ae4 -r43dfd9f833c87c58f4dc4a61f386b6c2cf961720 --- lams_common/db/sql/insert_lams_unix_config_data.sql (.../insert_lams_unix_config_data.sql) (revision aa7e502bb28fa1df94980fadea3876a83e842ae4) +++ lams_common/db/sql/insert_lams_unix_config_data.sql (.../insert_lams_unix_config_data.sql) (revision 43dfd9f833c87c58f4dc4a61f386b6c2cf961720) @@ -47,10 +47,13 @@ insert into lams_configuration (config_key, config_value) values ('LDAPPhoneAttr','telephoneNumber'); insert into lams_configuration (config_key, config_value) values ('LDAPFaxAttr','facsimileTelephoneNumber'); insert into lams_configuration (config_key, config_value) values ('LDAPMobileAttr','mobile'); -insert into lams_configuration (config_key, config_value) values ('LDAPOrgCodeAttr','deetITSchoolCode'); +insert into lams_configuration (config_key, config_value) values ('LDAPOrgAttr','deetITSchoolCode'); insert into lams_configuration (config_key, config_value) values ('LDAPRolesAttr','memberOf'); insert into lams_configuration (config_key, config_value) values ('LDAPLearnerMap','Student;SchoolSupportStaff;Teacher;SeniorStaff;Principal'); insert into lams_configuration (config_key, config_value) values ('LDAPMonitorMap','SchoolSupportStaff;Teacher;SeniorStaff;Principal'); insert into lams_configuration (config_key, config_value) values ('LDAPAuthorMap','Teacher;SeniorStaff;Principal'); insert into lams_configuration (config_key, config_value) values ('LDAPGroupAdminMap','Teacher;SeniorStaff'); -insert into lams_configuration (config_key, config_value) values ('LDAPGroupManagerMap','Principal'); \ No newline at end of file +insert into lams_configuration (config_key, config_value) values ('LDAPGroupManagerMap','Principal'); +insert into lams_configuration (config_key, config_value) values ('LDAPUpdateOnLogin', 'true'); +insert into lams_configuration (config_key, config_value) values ('LDAPOrgField', 'code'); +insert into lams_configuration (config_key, config_value) values ('LDAPOnlyOneOrg', 'true'); \ No newline at end of file Index: lams_common/db/sql/insert_lams_windows_config_data.sql =================================================================== diff -u -raa7e502bb28fa1df94980fadea3876a83e842ae4 -r43dfd9f833c87c58f4dc4a61f386b6c2cf961720 --- lams_common/db/sql/insert_lams_windows_config_data.sql (.../insert_lams_windows_config_data.sql) (revision aa7e502bb28fa1df94980fadea3876a83e842ae4) +++ lams_common/db/sql/insert_lams_windows_config_data.sql (.../insert_lams_windows_config_data.sql) (revision 43dfd9f833c87c58f4dc4a61f386b6c2cf961720) @@ -47,10 +47,13 @@ insert into lams_configuration (config_key, config_value) values ('LDAPPhoneAttr','telephoneNumber'); insert into lams_configuration (config_key, config_value) values ('LDAPFaxAttr','facsimileTelephoneNumber'); insert into lams_configuration (config_key, config_value) values ('LDAPMobileAttr','mobile'); -insert into lams_configuration (config_key, config_value) values ('LDAPOrgCodeAttr','deetITSchoolCode'); +insert into lams_configuration (config_key, config_value) values ('LDAPOrgAttr','deetITSchoolCode'); insert into lams_configuration (config_key, config_value) values ('LDAPRolesAttr','memberOf'); insert into lams_configuration (config_key, config_value) values ('LDAPLearnerMap','Student;SchoolSupportStaff;Teacher;SeniorStaff;Principal'); insert into lams_configuration (config_key, config_value) values ('LDAPMonitorMap','SchoolSupportStaff;Teacher;SeniorStaff;Principal'); insert into lams_configuration (config_key, config_value) values ('LDAPAuthorMap','Teacher;SeniorStaff;Principal'); insert into lams_configuration (config_key, config_value) values ('LDAPGroupAdminMap','Teacher;SeniorStaff'); -insert into lams_configuration (config_key, config_value) values ('LDAPGroupManagerMap','Principal'); \ No newline at end of file +insert into lams_configuration (config_key, config_value) values ('LDAPGroupManagerMap','Principal'); +insert into lams_configuration (config_key, config_value) values ('LDAPUpdateOnLogin', 'true'); +insert into lams_configuration (config_key, config_value) values ('LDAPOrgField', 'code'); +insert into lams_configuration (config_key, config_value) values ('LDAPOnlyOneOrg', 'true'); \ No newline at end of file Index: lams_common/src/java/org/lamsfoundation/lams/usermanagement/ldapContext.xml =================================================================== diff -u --- lams_common/src/java/org/lamsfoundation/lams/usermanagement/ldapContext.xml (revision 0) +++ lams_common/src/java/org/lamsfoundation/lams/usermanagement/ldapContext.xml (revision 43dfd9f833c87c58f4dc4a61f386b6c2cf961720) @@ -0,0 +1,24 @@ + + + + + + + + + + + + + + + true + + + PROPAGATION_REQUIRED + PROPAGATION_REQUIRED + PROPAGATION_REQUIRED + + + + \ No newline at end of file Index: lams_common/src/java/org/lamsfoundation/lams/usermanagement/service/ILdapService.java =================================================================== diff -u --- lams_common/src/java/org/lamsfoundation/lams/usermanagement/service/ILdapService.java (revision 0) +++ lams_common/src/java/org/lamsfoundation/lams/usermanagement/service/ILdapService.java (revision 43dfd9f833c87c58f4dc4a61f386b6c2cf961720) @@ -0,0 +1,41 @@ +/**************************************************************** + * Copyright (C) 2005 LAMS Foundation (http://lamsfoundation.org) + * ============================================================= + * License Information: http://lamsfoundation.org/licensing/lams/2.0/ + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License version 2.0 + * as published by the Free Software Foundation. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 * USA + * + * http://www.gnu.org/licenses/gpl.txt + * **************************************************************** + */ + +/* $Id$ */ +package org.lamsfoundation.lams.usermanagement.service; + +import javax.naming.directory.Attributes; + +import org.lamsfoundation.lams.usermanagement.User; + +/** + * @author jliew + * + */ +public interface ILdapService { + + public void updateLDAPUser(User user, Attributes attrs); + + public boolean createLDAPUser(Attributes attrs); + + public boolean addLDAPUser(Attributes attrs, Integer userId); +} Index: lams_common/src/java/org/lamsfoundation/lams/usermanagement/service/LdapService.java =================================================================== diff -u --- lams_common/src/java/org/lamsfoundation/lams/usermanagement/service/LdapService.java (revision 0) +++ lams_common/src/java/org/lamsfoundation/lams/usermanagement/service/LdapService.java (revision 43dfd9f833c87c58f4dc4a61f386b6c2cf961720) @@ -0,0 +1,261 @@ +/**************************************************************** + * Copyright (C) 2005 LAMS Foundation (http://lamsfoundation.org) + * ============================================================= + * License Information: http://lamsfoundation.org/licensing/lams/2.0/ + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License version 2.0 + * as published by the Free Software Foundation. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 * USA + * + * http://www.gnu.org/licenses/gpl.txt + * **************************************************************** + */ + +/* $Id$ */ +package org.lamsfoundation.lams.usermanagement.service; + +import java.util.ArrayList; +import java.util.Date; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Set; + +import javax.naming.NamingEnumeration; +import javax.naming.NamingException; +import javax.naming.directory.Attribute; +import javax.naming.directory.Attributes; + +import org.apache.log4j.Logger; +import org.lamsfoundation.lams.usermanagement.AuthenticationMethod; +import org.lamsfoundation.lams.usermanagement.Organisation; +import org.lamsfoundation.lams.usermanagement.OrganisationState; +import org.lamsfoundation.lams.usermanagement.OrganisationType; +import org.lamsfoundation.lams.usermanagement.Role; +import org.lamsfoundation.lams.usermanagement.User; +import org.lamsfoundation.lams.usermanagement.UserOrganisation; +import org.lamsfoundation.lams.util.Configuration; +import org.lamsfoundation.lams.util.ConfigurationKeys; + +/** + * @author jliew + * + */ +public class LdapService implements ILdapService { + + private Logger log = Logger.getLogger(LdapService.class); + private IUserManagementService service; + + public IUserManagementService getService() { + return service; + } + + public void setService(IUserManagementService service) { + this.service = service; + } + + public void updateLDAPUser(User user, Attributes attrs) { + HashMap map = getLDAPUserAttributes(attrs); + user.setLogin(map.get("login")); + user.setFirstName(map.get("fname")); + user.setLastName(map.get("lname")); + user.setEmail(map.get("email")); + user.setDayPhone(map.get("phone")); + user.setFax(map.get("fax")); + user.setMobilePhone(map.get("mobile")); + getService().save(user); + } + + public boolean createLDAPUser(Attributes attrs) { + User user = new User(); + try { + HashMap map = getLDAPUserAttributes(attrs); + if (map.get("login")!=null && map.get("login").trim().length()>0) { + if (log.isDebugEnabled()) { + log.debug("===> using LDAP attributes: " + +map.get("login")+","+map.get("fname")+","+map.get("lname")+"," + +map.get("email")+","+map.get("phone")+","+map.get("fax")+"," + +map.get("mobile")); + } + user.setLogin(map.get("login")); + user.setPassword("dummy"); // password column is not-null + user.setFirstName(map.get("fname")); + user.setLastName(map.get("lname")); + user.setEmail(map.get("email")); + user.setDayPhone(map.get("phone")); + user.setFax(map.get("fax")); + user.setMobilePhone(map.get("mobile")); + user.setAuthenticationMethod((AuthenticationMethod)service + .findById(AuthenticationMethod.class, AuthenticationMethod.LDAP)); + user.setFlashTheme(service.getDefaultFlashTheme()); + user.setHtmlTheme(service.getDefaultHtmlTheme()); + user.setDisabledFlag(false); + user.setCreateDate(new Date()); + user.setLocale(service.getDefaultLocale()); + service.save(user); + // TODO write audit log + return true; + } else { + log.error("===> Login name from LDAP is empty - user not created."); + } + } catch (Exception e) { + log.error("===> Exception occurred while creating LDAP user: ", e); + } + return false; + } + + private HashMap getLDAPUserAttributes(Attributes attrs) { + HashMap map = new HashMap(); + try { + map.put("login", getSingleAttributeString(attrs.get(Configuration.get(ConfigurationKeys.LDAP_LOGIN_ATTR)))); + map.put("fname", getSingleAttributeString(attrs.get(Configuration.get(ConfigurationKeys.LDAP_FIRST_NAME_ATTR)))); + map.put("lname", getSingleAttributeString(attrs.get(Configuration.get(ConfigurationKeys.LDAP_LAST_NAME_ATTR)))); + map.put("email", getSingleAttributeString(attrs.get(Configuration.get(ConfigurationKeys.LDAP_EMAIL_ATTR)))); + map.put("phone", getSingleAttributeString(attrs.get(Configuration.get(ConfigurationKeys.LDAP_PHONE_ATTR)))); + map.put("fax", getSingleAttributeString(attrs.get(Configuration.get(ConfigurationKeys.LDAP_FAX_ATTR)))); + map.put("mobile", getSingleAttributeString(attrs.get(Configuration.get(ConfigurationKeys.LDAP_MOBILE_ATTR)))); + } catch (Exception e) { + log.error("===> Exception occurred while getting LDAP user attributes: ", e); + } + return map; + } + + public boolean addLDAPUser(Attributes attrs, Integer userId) { + User user = (User)service.findById(User.class, userId); + // get ldap attributes for lams org and roles + String ldapOrgAttr = getSingleAttributeString(attrs.get(Configuration.get(ConfigurationKeys.LDAP_ORG_ATTR))); + List ldapRoles = getAttributeStrings(attrs.get(Configuration.get(ConfigurationKeys.LDAP_ROLES_ATTR))); + // get column name of lams_organisation to match ldapOrgAttr to + String orgField = Configuration.get(ConfigurationKeys.LDAP_ORG_FIELD); + + if (ldapOrgAttr != null && ldapRoles != null && orgField != null) { + // get list of possible matching organisations + log.debug("Looking for organisation to add ldap user to..."); + List orgList = (List)service.findByProperty(Organisation.class, orgField, ldapOrgAttr); + if (orgList!=null && !orgList.isEmpty()) { + Organisation org = null; + if (orgList.size()==1) { + org = (Organisation)orgList.get(0); + } else if (orgList.size() > 1) { + // if there are multiple orgs, select the one that is active, if there is one + HashMap properties = new HashMap(); + properties.put(orgField, ldapOrgAttr); + properties.put("organisationState.organisationStateId", OrganisationState.ACTIVE); + orgList = (List)service.findByProperties(Organisation.class, properties); + if (orgList.size()==1) { + org = (Organisation)orgList.get(0); + } else { + log.warn("More than one LAMS organisation found with the "+orgField+": "+ldapOrgAttr); + return false; + } + } + // if the user is a member of any other groups, remove them + if (Configuration.getAsBoolean(ConfigurationKeys.LDAP_ONLY_ONE_ORG)) { + Set uos = user.getUserOrganisations(); + Iterator i = uos.iterator(); + while (i.hasNext()) { + UserOrganisation uo = (UserOrganisation)i.next(); + Organisation currentOrg = uo.getOrganisation(); + if (currentOrg.getOrganisationType().getOrganisationTypeId().equals(OrganisationType.COURSE_TYPE)) { + if (!currentOrg.equals(org)) { + i.remove(); + // remove userOrg from the org's collection + Set currentOrgUos = currentOrg.getUserOrganisations(); + currentOrgUos.remove(uo); + currentOrg.setUserOrganisations(currentOrgUos); + // remove subgroups + service.deleteChildUserOrganisations(uo.getUser(), uo.getOrganisation()); + } + } + } + user.setUserOrganisations(uos); + service.save(user); + } + // now convert the roles to lams roles and add the user to the org + List roleIds = getRoleIds(ldapRoles); + if (roleIds!=null && !roleIds.isEmpty()) { + service.setRolesForUserOrganisation(user, org.getOrganisationId(), roleIds); + return true; + } + } else { + log.warn("No LAMS organisations found with the "+orgField+": "+ldapOrgAttr); + } + } + return false; + } + + // get list of LAMS role ids from list of ldap roles + private List getRoleIds(List ldapRoles) { + if (ldapRoles!=null) { + ArrayList roleIds = new ArrayList(); + for (String role : ldapRoles) { + if (Configuration.get(ConfigurationKeys.LDAP_LEARNER_MAP).indexOf(role) >= 0 + && !roleIds.contains(Role.ROLE_LEARNER.toString())) { + roleIds.add(Role.ROLE_LEARNER.toString()); + } + if (Configuration.get(ConfigurationKeys.LDAP_MONITOR_MAP).indexOf(role) >= 0 + && !roleIds.contains(Role.ROLE_MONITOR.toString())) { + roleIds.add(Role.ROLE_MONITOR.toString()); + } + if (Configuration.get(ConfigurationKeys.LDAP_AUTHOR_MAP).indexOf(role) >= 0 + && !roleIds.contains(Role.ROLE_AUTHOR.toString())) { + roleIds.add(Role.ROLE_AUTHOR.toString()); + } + if (Configuration.get(ConfigurationKeys.LDAP_GROUP_ADMIN_MAP).indexOf(role) >= 0 + && !roleIds.contains(Role.ROLE_GROUP_ADMIN.toString())) { + roleIds.add(Role.ROLE_GROUP_ADMIN.toString()); + } + if (Configuration.get(ConfigurationKeys.LDAP_GROUP_MANAGER_MAP).indexOf(role) >= 0 + && !roleIds.contains(Role.ROLE_GROUP_MANAGER.toString())) { + roleIds.add(Role.ROLE_GROUP_MANAGER.toString()); + } + } + return roleIds; + } + return null; + } + + // get the multiple values of an ldap attribute + private List getAttributeStrings(Attribute attr) { + try { + ArrayList attrValues = new ArrayList(); + if (attr!=null) { + NamingEnumeration attrEnum = attr.getAll(); + while (attrEnum.hasMore()) { + Object attrValue = attrEnum.next(); + if (attrValue!=null) { + attrValues.add(attrValue.toString()); + } + } + return attrValues; + } + } catch (NamingException e) { + log.error("===> Naming exception occurred: "+e.getMessage()); + } + return null; + } + + // get the single (string) value of an ldap attribute + private String getSingleAttributeString(Attribute attr) { + try { + if (attr!=null) { + Object attrValue = attr.get(); + if (attrValue!=null) { + return attrValue.toString(); + } + } + } catch (NamingException e) { + log.error("===> Naming exception occurred: "+e.getMessage()); + } + return null; + } +} Index: lams_common/src/java/org/lamsfoundation/lams/util/ConfigurationKeys.java =================================================================== diff -u -raa7e502bb28fa1df94980fadea3876a83e842ae4 -r43dfd9f833c87c58f4dc4a61f386b6c2cf961720 --- lams_common/src/java/org/lamsfoundation/lams/util/ConfigurationKeys.java (.../ConfigurationKeys.java) (revision aa7e502bb28fa1df94980fadea3876a83e842ae4) +++ lams_common/src/java/org/lamsfoundation/lams/util/ConfigurationKeys.java (.../ConfigurationKeys.java) (revision 43dfd9f833c87c58f4dc4a61f386b6c2cf961720) @@ -165,7 +165,7 @@ public static String LDAP_MOBILE_ATTR = "LDAPMobileAttr"; - public static String LDAP_ORG_CODE_ATTR = "LDAPOrgCodeAttr"; + public static String LDAP_ORG_ATTR = "LDAPOrgAttr"; public static String LDAP_ROLES_ATTR = "LDAPRolesAttr"; @@ -178,4 +178,10 @@ public static String LDAP_GROUP_ADMIN_MAP = "LDAPGroupAdminMap"; public static String LDAP_GROUP_MANAGER_MAP = "LDAPGroupManagerMap"; + + public static String LDAP_UPDATE_ON_LOGIN = "LDAPUpdateOnLogin"; + + public static String LDAP_ORG_FIELD = "LDAPOrgField"; + + public static String LDAP_ONLY_ONE_ORG = "LDAPOnlyOneOrg"; } \ No newline at end of file