UserServiceImpl.java

  1. /*
  2.  * This software was designed and created by Jason Carroll.
  3.  * Copyright (c) 2002, 2003, 2004 Jason Carroll.
  4.  * The author can be reached at jcarroll@cowsultants.com
  5.  * ITracker website: http://www.cowsultants.com
  6.  * ITracker forums: http://www.cowsultants.com/phpBB/index.php
  7.  *
  8.  * This program is free software; you can redistribute it and/or modify
  9.  * it only under the terms of the GNU General Public License as published by
  10.  * the Free Software Foundation; either version 2 of the License, or
  11.  * (at your option) any later version.
  12.  *
  13.  * This program is distributed in the hope that it will be useful,
  14.  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  15.  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  16.  * GNU General Public License for more details.
  17.  */

  18. package org.itracker.services.implementations;

  19. import org.apache.log4j.Logger;
  20. import org.itracker.PasswordException;
  21. import org.itracker.UserException;
  22. import org.itracker.core.AuthenticationConstants;
  23. import org.itracker.model.*;
  24. import org.itracker.model.util.ProjectUtilities;
  25. import org.itracker.model.util.UserUtilities;
  26. import org.itracker.persistence.dao.*;
  27. import org.itracker.services.ConfigurationService;
  28. import org.itracker.services.ProjectService;
  29. import org.itracker.services.UserService;
  30. import org.itracker.services.authentication.ITrackerUserDetails;
  31. import org.itracker.services.authentication.PluggableAuthenticator;
  32. import org.itracker.services.exceptions.AuthenticatorException;
  33. import org.springframework.security.core.userdetails.UserDetails;
  34. import org.springframework.security.core.userdetails.UsernameNotFoundException;

  35. import java.util.*;

  36. /**
  37.  * Implements the UserService interface. See that interface for method
  38.  * descriptions.
  39.  *
  40.  * @see UserService
  41.  */
  42. public class UserServiceImpl implements UserService {

  43.     private static final String DEFAULT_AUTHENTICATOR =
  44.             "org.itracker.services.authentication.DefaultAuthenticator";


  45.     private String authenticatorClassName = null;
  46.     private Class<?> authenticatorClass = null;
  47.     private boolean allowSelfRegister = false;

  48.     private static final Logger logger = Logger.getLogger(UserServiceImpl.class);

  49.     private PermissionDAO permissionDAO = null;

  50.     private UserDAO userDAO = null;
  51.     private UserPreferencesDAO userPreferencesDAO = null;
  52.     private ProjectService projectService;
  53.     private ConfigurationService configurationService;


  54.     public UserServiceImpl(ConfigurationService configurationService,
  55.                            ProjectService projectService,
  56.                            UserDAO userDAO,
  57.                            PermissionDAO permissionDAO,
  58.                            UserPreferencesDAO userPreferencesDAO) {


  59.         this.configurationService = configurationService;
  60.         this.projectService = projectService;
  61.         this.userDAO = userDAO;
  62.         this.userPreferencesDAO = userPreferencesDAO;
  63.         this.permissionDAO = permissionDAO;

  64.         try {
  65.             allowSelfRegister = configurationService.getBooleanProperty("allow_self_register", false);

  66.             authenticatorClassName = configurationService.getProperty("authenticator_class", DEFAULT_AUTHENTICATOR);
  67.             authenticatorClass = Class.forName(authenticatorClassName);
  68.         } catch (ClassNotFoundException ex) {
  69.             throw new RuntimeException(ex);
  70.         }
  71.     }

  72.     /**
  73.      * @deprecated use constructor without projectDA= und reportDAO instead
  74.      */
  75.     public UserServiceImpl(ConfigurationService configurationService,
  76.                            ProjectService projectService,
  77.                            UserDAO userDAO,
  78.                            ProjectDAO projectDAO,
  79.                            ReportDAO reportDAO,
  80.                            PermissionDAO permissionDAO,
  81.                            UserPreferencesDAO userPreferencesDAO) {
  82.         this(configurationService, projectService, userDAO, permissionDAO, userPreferencesDAO);
  83.     }

  84.     public User getUser(Integer userId) {
  85.         User user = userDAO.findByPrimaryKey(userId);
  86.         return user;
  87.     }

  88.     public User getUserByLogin(String login) throws NoSuchEntityException {
  89.         User user = userDAO.findByLogin(login);
  90.         if (user == null)
  91.             throw new NoSuchEntityException("User " + login + " not found.");
  92.         return user;
  93.     }
  94.     @Override
  95.     public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
  96.         try {
  97.             final User model = getUserByLogin(username);
  98.             return new ITrackerUserDetails(model, getPermissionsByUserId(model.getId()));
  99.         } catch (NoSuchEntityException e) {
  100.             throw new UsernameNotFoundException(username, e);
  101.         }
  102.     }

  103.     public String getUserPasswordByLogin(String login) {
  104.         User user = userDAO.findByLogin(login);
  105.         return user.getPassword();
  106.     }

  107.     public List<User> getAllUsers() {
  108.         List<User> users = userDAO.findAll();

  109.         return users;
  110.     }

  111.     public int getNumberUsers() {
  112.         Collection<User> users = userDAO.findAll();
  113.         return users.size();
  114.     }

  115.     public List<User> getActiveUsers() {
  116.         List<User> users = userDAO.findActive();

  117.         return users;
  118.     }

  119.     public List<User> getSuperUsers() {
  120.         List<User> superUsers = userDAO.findSuperUsers();
  121.         return superUsers;
  122.     }


  123.     public User createUser(User user) throws UserException {
  124.         try {
  125.             if (user == null || user.getLogin() == null || user.getLogin().equals("")) {
  126.                 throw new UserException("User data was null, or login was empty.");
  127.             }

  128.             try {
  129.                 this.getUserByLogin(user.getLogin());
  130.                 throw new UserException("User already exists with login: " + user.getLogin());
  131.             } catch (NoSuchEntityException e) {
  132.                 // doesn't exist, we'll create him
  133.             }

  134.             try {
  135.                 PluggableAuthenticator authenticator = (PluggableAuthenticator) authenticatorClass.newInstance();
  136.                 if (authenticator != null) {
  137.                     HashMap<String, Object> values = new HashMap<String, Object>();
  138.                     values.put("userService", this);
  139.                     values.put("configurationService", configurationService);
  140.                     authenticator.initialize(values);
  141.                     authenticator.createProfile(user, null, AuthenticationConstants.AUTH_TYPE_UNKNOWN,
  142.                             AuthenticationConstants.REQ_SOURCE_UNKNOWN);
  143.                 } else {
  144.                     throw new AuthenticatorException("Unable to create new authenticator.", AuthenticatorException.SYSTEM_ERROR);
  145.                 }
  146.             } catch (IllegalAccessException ex) {
  147.                 throw new AuthenticatorException(
  148.                         "Authenticator class " + authenticatorClassName + " can not be instantiated.",
  149.                         AuthenticatorException.SYSTEM_ERROR, ex);
  150.             } catch (InstantiationException ex) {
  151.                 throw new AuthenticatorException(
  152.                         "Authenticator class " + authenticatorClassName + " can not be instantiated.",
  153.                         AuthenticatorException.SYSTEM_ERROR, ex);
  154.             } catch (ClassCastException ex) {
  155.                 throw new AuthenticatorException("Authenticator class " + authenticatorClassName
  156.                         + " does not extend the PluggableAuthenticator class.",
  157.                         AuthenticatorException.SYSTEM_ERROR, ex);
  158.             }
  159.             user.setStatus(UserUtilities.STATUS_ACTIVE);
  160.             user.setRegistrationType(user.getRegistrationType());
  161.             addPreferences(user);
  162.             userDAO.save(user);
  163.             return user;
  164.         } catch (AuthenticatorException ex) {
  165.             throw new UserException("Could not create user.", ex);
  166.         }

  167.     }

  168.     public User updateUser(User user) throws UserException {
  169.         try {
  170.             PluggableAuthenticator authenticator = (PluggableAuthenticator) authenticatorClass.newInstance();
  171.             if (authenticator != null) {
  172.                 HashMap<String, Object> values = new HashMap<String, Object>();
  173.                 values.put("userService", this);
  174.                 values.put("configurationService", configurationService);
  175.                 authenticator.initialize(values);
  176.                 authenticator.updateProfile(user, AuthenticationConstants.UPDATE_TYPE_CORE, null,
  177.                         AuthenticationConstants.AUTH_TYPE_UNKNOWN, AuthenticationConstants.REQ_SOURCE_UNKNOWN);
  178.             } else {
  179.                 logger.warn("updateUser: no authenticator, throwing AuthenticatorException");
  180.                 throw new AuthenticatorException("Unable to create new authenticator.",
  181.                         AuthenticatorException.SYSTEM_ERROR);
  182.             }
  183.         } catch (IllegalAccessException ex) {
  184.             logger.error("updateUser: IllegalAccessException caught, throwing AuthenticatorException", ex);
  185.             throw new AuthenticatorException(
  186.                     "Authenticator class " + authenticatorClassName + " can not be instantiated.",
  187.                     AuthenticatorException.SYSTEM_ERROR, ex);
  188.         } catch (InstantiationException ex) {
  189.             logger.error("updateUser: InstantiationException caught, throwing AuthenticatorException", ex);
  190.             throw new AuthenticatorException(
  191.                     "Authenticator class " + authenticatorClassName + " can not be instantiated.",
  192.                     AuthenticatorException.SYSTEM_ERROR, ex);
  193.         } catch (ClassCastException ex) {
  194.             logger.error("updateUser: ClassCastException caught, throwing AuthenticatorException", ex);
  195.             throw new AuthenticatorException(
  196.                     "Authenticator class " + authenticatorClassName
  197.                             + " does not extend the PluggableAuthenticator class.",
  198.                     AuthenticatorException.SYSTEM_ERROR, ex);
  199.         } catch (AuthenticatorException ex) {
  200.             logger.error("updateUser: AuthenticatorException caught, throwing AuthenticatorException", ex);
  201.             throw new UserException("Unable to update user.", ex);
  202.         }

  203.         // detach, so we can compare the new loaded with changed user
  204.         Integer id = user.getId();
  205.         userDAO.detach(user);

  206.         User existinguser = userDAO.findByPrimaryKey(id);
  207.         userDAO.refresh(existinguser);

  208.         existinguser.setLogin(user.getLogin());
  209.         existinguser.setFirstName(user.getFirstName());
  210.         existinguser.setLastName(user.getLastName());
  211.         existinguser.setEmail(user.getEmail());
  212.         existinguser.setSuperUser(user.isSuperUser());

  213.         existinguser.setStatus(user.getStatus());

  214.         if (user.getPassword() != null && (!user.getPassword().equals(""))) {
  215.             if (logger.isInfoEnabled()) {
  216.                 logger.info("updateUser: setting new password for " + user.getLogin());
  217.             }
  218.             existinguser.setPassword(user.getPassword());
  219.         }

  220.         if (null == existinguser.getPreferences()) {
  221.             addPreferences(existinguser);
  222.         } else {
  223.             updateUserPreferences(user.getPreferences());
  224.         }

  225.         userDAO.saveOrUpdate(existinguser);
  226.         return existinguser;
  227.     }

  228.     private static void addPreferences(User user) {
  229.         UserPreferences prefs = new UserPreferences();
  230.         prefs.setUser(user);
  231.         user.setPreferences(prefs);
  232.     }

  233.     public String generateUserPassword(User user) throws PasswordException {
  234.         String password = UserUtilities.generatePassword();
  235.         user.setPassword(UserUtilities.encryptPassword(password));
  236.         return password;
  237.         // throw new PasswordException(PasswordException.UNKNOWN_USER);
  238.     }

  239.     public UserPreferences updateUserPreferences(UserPreferences userPrefs) throws UserException {
  240.         UserPreferences newUserPrefs;

  241.         try {
  242.             User user = userPrefs.getUser();

  243.             newUserPrefs = userPreferencesDAO.findByUserId(user.getId());

  244.             if (newUserPrefs == null) {
  245.                 newUserPrefs = new UserPreferences();
  246.             }
  247.             newUserPrefs.setUserLocale(userPrefs.getUserLocale());
  248.             newUserPrefs.setNumItemsOnIndex(userPrefs.getNumItemsOnIndex());
  249.             newUserPrefs.setNumItemsOnIssueList(userPrefs.getNumItemsOnIssueList());
  250.             newUserPrefs.setShowClosedOnIssueList(userPrefs.getShowClosedOnIssueList());
  251.             newUserPrefs.setSortColumnOnIssueList(userPrefs.getSortColumnOnIssueList());
  252.             newUserPrefs.setHiddenIndexSections(userPrefs.getHiddenIndexSections());

  253.             newUserPrefs.setRememberLastSearch(userPrefs.getRememberLastSearch());
  254.             newUserPrefs.setUseTextActions(userPrefs.getUseTextActions());

  255.             newUserPrefs.setUser(user);

  256.             if (userPrefs.isNew()) {
  257.                 newUserPrefs.setCreateDate(new Date());
  258.                 newUserPrefs.setLastModifiedDate(userPrefs.getCreateDate());

  259.                 // first time create UserPreferences
  260.                 user.setPreferences(newUserPrefs);
  261.                 userDAO.saveOrUpdate(user);
  262.             } else {
  263.                 this.userPreferencesDAO.saveOrUpdate(newUserPrefs);
  264.                 newUserPrefs = userPreferencesDAO.findByUserId(user.getId());
  265.                 user.setPreferences(newUserPrefs);
  266.             }

  267.             try {
  268.                 PluggableAuthenticator authenticator =
  269.                         (PluggableAuthenticator) authenticatorClass.newInstance();

  270.                 if (authenticator != null) {
  271.                     HashMap<String, Object> values = new HashMap<String, Object>();
  272.                     values.put("userService", this);
  273.                     values.put("configurationService", configurationService);
  274.                     authenticator.initialize(values);
  275.                     authenticator.updateProfile(user, AuthenticationConstants.UPDATE_TYPE_PREFERENCE, null,
  276.                             AuthenticationConstants.AUTH_TYPE_UNKNOWN, AuthenticationConstants.REQ_SOURCE_UNKNOWN);
  277.                 } else {
  278.                     throw new AuthenticatorException("Unable to create new authenticator.",
  279.                             AuthenticatorException.SYSTEM_ERROR);
  280.                 }
  281.             } catch (IllegalAccessException ex) {
  282.                 throw new AuthenticatorException(
  283.                         "Authenticator class " + authenticatorClassName + " can not be instantiated.",
  284.                         AuthenticatorException.SYSTEM_ERROR, ex);
  285.             } catch (InstantiationException ex) {
  286.                 throw new AuthenticatorException(
  287.                         "Authenticator class " + authenticatorClassName + " can not be instantiated.",
  288.                         AuthenticatorException.SYSTEM_ERROR, ex);
  289.             } catch (ClassCastException ex) {
  290.                 throw new AuthenticatorException(
  291.                         "Authenticator class " + authenticatorClassName
  292.                                 + " does not extend the PluggableAuthenticator class.",
  293.                         AuthenticatorException.SYSTEM_ERROR, ex);
  294.             }

  295.             if (newUserPrefs != null)
  296.                 return newUserPrefs;

  297.         } catch (AuthenticatorException ex) {
  298.             throw new UserException("Unable to create new preferences.", ex);
  299.         }
  300. //        } finally {
  301.         return userPrefs;
  302. //        }
  303.     }

  304.     public void clearOwnedProjects(User user) {
  305.         user.getProjects().clear();
  306.         userDAO.save(user);
  307.     }

  308.     @Override
  309.     public List<User> findUsersForProjectByPermissionTypeList(Integer projectID, PermissionType[] permissionTypes) {
  310.         return userDAO.findUsersForProjectByAllPermissionTypeList(projectID, permissionTypes);
  311.     }

  312.     @Override
  313.     public List<User> getUsersWithPermissionLocal(Integer projectId, PermissionType permissionType) {

  314.         List<User> users = new ArrayList<User>();

  315.         if (projectId != null) {
  316.             List<Permission> permissions = permissionDAO.findByProjectIdAndPermission(
  317.                     projectId, permissionType);

  318.             for (Permission permission : permissions) {
  319.                 users.add(permission.getUser());
  320.             }

  321.         }

  322.         return users;
  323.     }

  324.     public List<User> getUsersWithPermissionLocal(Integer projectId, int permissionType) {
  325.         return getUsersWithPermissionLocal(projectId, PermissionType.valueOf(permissionType));
  326.     }

  327.     public List<Permission> getUserPermissionsLocal(User user) {
  328.         List<Permission> permissions = permissionDAO.findByUserId(user.getId());
  329.         return permissions;
  330.     }

  331.     public List<Permission> getPermissionsByUserId(Integer userId) {
  332.         List<Permission> permissions = new ArrayList<Permission>();

  333.         User user = getUser(userId);
  334.         if (user != null) {
  335.             try {
  336.                 PluggableAuthenticator authenticator = (PluggableAuthenticator) authenticatorClass.newInstance();
  337.                 if (authenticator != null) {
  338.                     HashMap<String, Object> values = new HashMap<String, Object>();
  339.                     values.put("userService", this);
  340.                     values.put("configurationService", configurationService);
  341.                     authenticator.initialize(values);
  342.                     permissions = authenticator.getUserPermissions(user, AuthenticationConstants.REQ_SOURCE_UNKNOWN);
  343.                 }
  344.                 logger.debug("Found " + permissions.size() + " permissions for user " + user.getLogin());
  345.             } catch (IllegalAccessException ex) {
  346.                 throw new RuntimeException("Authenticator class "
  347.                         + authenticatorClassName + " can not be instantiated.", ex);
  348.             } catch (InstantiationException ex) {
  349.                 throw new RuntimeException("Authenticator class "
  350.                         + authenticatorClassName + " can not be instantiated.", ex);
  351.             } catch (ClassCastException ex) {
  352.                 throw new RuntimeException("Authenticator class " + authenticatorClassName
  353.                         + " does not extend the PluggableAuthenticator class.", ex);
  354.             } catch (AuthenticatorException ex) {
  355.                 throw new RuntimeException("Authenticator exception: ", ex);
  356.             }
  357.         }
  358.         return permissions;
  359.     }

  360.     public boolean updateAuthenticator(Integer userId, List<Permission> permissions) {
  361.         boolean successful;

  362.         try {
  363.             User user = userDAO.findByPrimaryKey(userId);
  364.             user.getPermissions().addAll(permissions);
  365.             try {
  366.                 PluggableAuthenticator authenticator = (PluggableAuthenticator) authenticatorClass.newInstance();
  367.                 if (authenticator != null) {
  368.                     HashMap<String, Object> values = new HashMap<String, Object>();
  369.                     values.put("userService", this);
  370.                     values.put("configurationService", configurationService);
  371.                     authenticator.initialize(values);
  372.                     if (authenticator
  373.                             .updateProfile(user, AuthenticationConstants.UPDATE_TYPE_PERMISSION_SET, null,
  374.                                     AuthenticationConstants.AUTH_TYPE_UNKNOWN,
  375.                                     AuthenticationConstants.REQ_SOURCE_UNKNOWN)) {
  376.                     }
  377.                 } else {
  378.                     logger.error("Unable to create new authenticator.");
  379.                     throw new AuthenticatorException(AuthenticatorException.SYSTEM_ERROR);
  380.                 }
  381.                 successful = true;
  382.             } catch (IllegalAccessException | InstantiationException iae) {
  383.                 logger.error("Authenticator class " + authenticatorClassName + " can not be instantiated.");
  384.                 throw new AuthenticatorException(AuthenticatorException.SYSTEM_ERROR);
  385.             } catch (ClassCastException cce) {
  386.                 logger.error("Authenticator class " + authenticatorClassName
  387.                         + " does not extend the PluggableAuthenticator class.");
  388.                 throw new AuthenticatorException(AuthenticatorException.SYSTEM_ERROR);
  389.             }

  390.         } catch (AuthenticatorException ae) {
  391.             logger.warn("Error setting user (" + userId + ") permissions.  AuthenticatorException.", ae);
  392.             successful = false;
  393.         }

  394.         return successful;
  395.     }

  396.     public boolean addUserPermissions(Integer userId, List<Permission> newPermissions) {
  397.         boolean successful = false;
  398.         if (newPermissions == null || newPermissions.size() == 0) {
  399.             return false;
  400.         }

  401.         try {
  402.             newPermissions.addAll(getUserPermissionsLocal(getUser(userId)));
  403.             setUserPermissions(userId, newPermissions);
  404.             successful = true;
  405.         } catch (AuthenticatorException ae) {
  406.             logger.warn("Error setting user (" + userId + ") permissions.  AuthenticatorException.", ae);
  407.             successful = false;
  408.         }

  409.         return successful;
  410.     }

  411.     /**
  412.      * private util for collection searching (contains)
  413.      */
  414.     private static Permission find(Collection<Permission> permissions, Permission permission) {

  415.         for (Permission permission2 : permissions) {
  416.             if (Permission.PERMISSION_PROPERTIES_COMPARATOR.compare(permission, permission2) == 0) {
  417.                 // found in list, return the found object
  418.                 return permission2;
  419.             }
  420.         }
  421.         return null;
  422.     }

  423.     /**
  424.      * @param userId         - id of update-user
  425.      * @param newPermissions - set of new permissions for this user
  426.      */
  427.     @Override
  428.     public boolean setUserPermissions(final Integer userId, final List<Permission> newPermissions) {

  429.         boolean hasChanges = false;
  430.         // rewriting this method

  431.         TreeSet<Permission> pSet = new TreeSet<Permission>(Permission.PERMISSION_PROPERTIES_COMPARATOR);
  432.         pSet.addAll(newPermissions);


  433.         User usermodel = this.getUser(userId);

  434.         Set<Permission> current = new TreeSet<Permission>(Permission.PERMISSION_PROPERTIES_COMPARATOR);

  435.         current.addAll(usermodel.getPermissions());

  436.         // setup permissions to be removed
  437.         Set<Permission> remove = new TreeSet<Permission>(Permission.PERMISSION_PROPERTIES_COMPARATOR);
  438.         remove.addAll(current);
  439.         remove.removeAll(pSet);
  440.         // setup permissions to be added
  441.         Set<Permission> add = new TreeSet<Permission>(Permission.PERMISSION_PROPERTIES_COMPARATOR);
  442.         add.addAll(pSet);
  443.         add.removeAll(current);

  444.         // look permission
  445.         Permission p;
  446.         Iterator<Permission> pIt = remove.iterator();
  447.         while (pIt.hasNext()) {
  448.             p = find(usermodel.getPermissions(), (Permission) pIt.next());
  449.             if (null == p) {
  450.                 continue;
  451.             }
  452.             if (usermodel.getPermissions().contains(p)) {
  453.                 usermodel.getPermissions().remove(p);
  454.                 permissionDAO.delete(p);
  455.                 hasChanges = true;
  456.             }
  457.         }

  458.         pIt = add.iterator();
  459.         while (pIt.hasNext()) {
  460.             p = pIt.next();
  461.             if (null == find(usermodel.getPermissions(), p) && !usermodel.getPermissions().contains(p)) {
  462.                 p.setUser(usermodel);
  463.                 usermodel.getPermissions().add(p);
  464.                 permissionDAO.save(p);
  465.                 hasChanges = true;
  466.             }
  467.         }

  468.         if (hasChanges) {
  469.             userDAO.saveOrUpdate(usermodel);
  470.         }

  471.         return hasChanges;
  472.     }

  473.     @Override
  474.     public boolean removeUserPermissions(Integer userId, List<Permission> newPermissions) {
  475.         boolean successful = false;
  476.         if (newPermissions == null || newPermissions.size() == 0) {
  477.             return successful;
  478.         }

  479.         try {
  480.             for (Iterator<Permission> delIterator = newPermissions.iterator(); delIterator.hasNext(); ) {
  481.                 Permission permission = (Permission) delIterator.next();
  482.                 permissionDAO.delete(permission);
  483.             }

  484.             successful = true;

  485.         } catch (AuthenticatorException ae) {
  486.             logger.warn("Error setting user (" + userId + ") permissions.  AuthenticatorException.", ae);
  487.             successful = false;
  488.         }

  489.         return successful;
  490.     }

  491.     @Override
  492.     @Deprecated
  493.     public Map<Integer, Set<PermissionType>> getUsersMapOfProjectIdsAndSetOfPermissionTypes(User user, int reqSource) {
  494.         Map<Integer, Set<PermissionType>> permissionsMap = new HashMap<Integer, Set<PermissionType>>();

  495.         if (user == null) {
  496.             return permissionsMap;
  497.         }

  498.         List<Permission> permissionList = new ArrayList<Permission>();

  499.         try {
  500.             PluggableAuthenticator authenticator =
  501.                     (PluggableAuthenticator) authenticatorClass.newInstance();

  502.             if (authenticator != null) {
  503.                 HashMap<String, Object> values = new HashMap<String, Object>();
  504.                 values.put("userService", this);
  505.                 values.put("configurationService", configurationService);
  506.                 authenticator.initialize(values);
  507.                 permissionList = authenticator.getUserPermissions(user, (reqSource == 0 ? AuthenticationConstants.REQ_SOURCE_UNKNOWN : reqSource));
  508.             }
  509.             logger.debug("Found " + permissionList.size() + " permissions for user " + user.getLogin());
  510.         } catch (IllegalAccessException iae) {
  511.             logger.error("Authenticator class " + authenticatorClassName + " can not be instantiated.");
  512.         } catch (InstantiationException ie) {
  513.             logger.error("Authenticator class " + authenticatorClassName + " can not be instantiated.");
  514.         } catch (ClassCastException cce) {
  515.             logger.error("Authenticator class " + authenticatorClassName
  516.                     + " does not extend the PluggableAuthenticator class.");
  517.         } catch (AuthenticatorException ae) {
  518.             logger.error("Authenticator exception: " + ae.getMessage());
  519.             logger.debug("Authenticator exception: ", ae);
  520.         }

  521.         permissionsMap = UserUtilities.mapPermissionTypesByProjectId(permissionList);

  522.         if (allowSelfRegister) {
  523.             List<Project> projects = projectService.getAllProjects();

  524.             for (int i = 0; i < projects.size(); i++) {
  525.                 Project project = projects.get(i);

  526.                 if (project.getOptions() >= ProjectUtilities.OPTION_ALLOW_SELF_REGISTERED_CREATE) {
  527.                     Set<PermissionType> projectPermissions = permissionsMap.get(project.getId());

  528.                     if (projectPermissions == null) {
  529.                         projectPermissions = new HashSet<PermissionType>();
  530.                         permissionsMap.put(project.getId(), projectPermissions);
  531.                     }

  532.                     if (ProjectUtilities.hasOption(ProjectUtilities.OPTION_ALLOW_SELF_REGISTERED_CREATE, project.getOptions())) {
  533.                         projectPermissions.add(PermissionType.ISSUE_VIEW_USERS);
  534.                         projectPermissions.add(PermissionType.ISSUE_CREATE);
  535.                     }

  536.                     if (ProjectUtilities.hasOption(ProjectUtilities.OPTION_ALLOW_SELF_REGISTERED_VIEW_ALL, project.getOptions())) {
  537.                         projectPermissions.add(PermissionType.ISSUE_VIEW_ALL);
  538.                     }
  539.                 }
  540.             }
  541.         }

  542.         return permissionsMap;
  543.     }

  544.     @Override
  545.     public List<User> getUsersWithProjectPermission(Integer projectId, PermissionType permission) {
  546.         return getUsersWithProjectPermission(projectId, permission, true);
  547.     }

  548.     @Override
  549.     public List<User> getUsersWithProjectPermission(Integer projectId, int permissionType) {
  550.         return getUsersWithProjectPermission(projectId, PermissionType.valueOf(permissionType), true);
  551.     }

  552.     @Override
  553.     public List<User> getUsersWithProjectPermission(Integer projectId, int permissionType, boolean activeOnly) {
  554.         return getUsersWithProjectPermission(projectId, PermissionType.valueOf(permissionType), activeOnly);
  555.     }

  556.     @Override
  557.     public List<User> getUsersWithProjectPermission(Integer projectId, PermissionType permissionType, boolean activeOnly) {
  558.         return getUsersWithAnyProjectPermission(projectId, new PermissionType[]{permissionType}, activeOnly);
  559.     }

  560.     @Override
  561.     public List<User> getUsersWithAnyProjectPermission(Integer projectId, int[] permissions) {
  562.         return getUsersWithAnyProjectPermission(projectId, PermissionType.valueOf(permissions), true);
  563.     }

  564.     @Override
  565.     public List<User> getUsersWithAnyProjectPermission(Integer projectId, PermissionType[] permissions, boolean activeOnly) {
  566.         return getUsersWithProjectPermission(projectId, permissions, false, activeOnly);
  567.     }

  568.     @Override
  569.     public List<User> getUsersWithAnyProjectPermission(Integer projectId, PermissionType[] permissionTypes) {
  570.         return getUsersWithAnyProjectPermission(projectId, permissionTypes, true);
  571.     }

  572.     @Override
  573.     public List<User> getUsersWithAnyProjectPermission(Integer projectId, int[] permissionTypes, boolean activeOnly) {
  574.         return getUsersWithProjectPermission(projectId, permissionTypes, false, activeOnly);
  575.     }

  576.     @Override
  577.     public List<User> getUsersWithProjectPermission(Integer projectId, int[] permissionTypes, boolean requireAll,
  578.                                                     boolean activeOnly) {
  579.         return getUsersWithProjectPermission(projectId, PermissionType.valueOf(permissionTypes), requireAll, activeOnly);
  580.     }

  581.     @Override
  582.     public List<User> getUsersWithProjectPermission(Integer projectId, PermissionType[] permissionTypes, boolean requireAll,
  583.                                                         boolean activeOnly) {

  584.         List<User> userList = new ArrayList<User>();

  585.         try {
  586.             // TODO: use a factory to hide this.
  587.             PluggableAuthenticator authenticator = (PluggableAuthenticator) authenticatorClass.newInstance();

  588.             if (authenticator != null) {
  589.                 Map<String, Object> values = new HashMap<String, Object>();
  590.                 values.put("userService", this);
  591.                 values.put("configurationService", configurationService);
  592.                 authenticator.initialize(values);

  593.                 userList = authenticator.getUsersWithProjectPermission(projectId, permissionTypes, requireAll, activeOnly,
  594.                         AuthenticationConstants.REQ_SOURCE_UNKNOWN);

  595.             }

  596.             if (logger.isDebugEnabled()) {
  597.                 logger.debug("getUsersWithProjectPermission: Found " + userList.size() + " users with project " + projectId + " permissions "
  598.                         + Arrays.toString(permissionTypes) + (requireAll ? "[AllReq," : "[AnyReq,")
  599.                         + (activeOnly ? "ActiveUsersOnly]" : "AllUsers]"));
  600.             }

  601.             // TODO : don't swallow exceptions!! MUST be propagated to the caller!!
  602.         } catch (IllegalAccessException iae) {
  603.             logger.error("getUsersWithProjectPermission: Authenticator class " + authenticatorClassName + " can not be instantiated.", iae);
  604.         } catch (InstantiationException ie) {
  605.             logger.error("getUsersWithProjectPermission: Authenticator class " + authenticatorClassName + " can not be instantiated.", ie);
  606.         } catch (ClassCastException cce) {
  607.             logger.error("getUsersWithProjectPermission: Authenticator class " + authenticatorClassName
  608.                     + " does not extend the PluggableAuthenticator class.", cce);
  609.         } catch (AuthenticatorException ae) {
  610.             logger.error("getUsersWithProjectPermission: Authenticator exception caught.", ae);
  611.         }
  612.         return userList;
  613.     }

  614.     @Override
  615.     public List<User> getPossibleOwners(Issue issue, Integer projectId, Integer userId) {
  616.         HashSet<User> users = new HashSet<User>();

  617.         List<User> editUsers = getUsersWithProjectPermission(projectId, UserUtilities.PERMISSION_EDIT, true);
  618.         for (User editUser : editUsers) {
  619.             users.add(editUser);
  620.         }
  621.         List<User> otherUsers = getUsersWithProjectPermission(projectId,
  622.                 new int[]{UserUtilities.PERMISSION_EDIT_USERS, UserUtilities.PERMISSION_ASSIGNABLE}, true, true);
  623.         for (User otherUser : otherUsers) {
  624.             users.add(otherUser);
  625.         }

  626.         if (issue != null) {
  627.             // Now add in the creator if the have edit own issues, and always
  628.             // the owner
  629.             User creator = issue.getCreator();

  630.             if (UserUtilities.hasPermission(getUsersMapOfProjectIdsAndSetOfPermissionTypes(creator, 0), projectId,
  631.                     PermissionType.ISSUE_EDIT_USERS)) {
  632.                 users.add(creator);
  633.             }
  634.             if (issue.getOwner() != null) {
  635.                 User owner = issue.getOwner();
  636.                 users.add(owner);
  637.             }
  638.         } else if (userId != null) {
  639.             // New issue, so add in the creator if needed
  640.             User creator = getUser(userId);
  641.             if (UserUtilities.hasPermission(getUsersMapOfProjectIdsAndSetOfPermissionTypes(creator, 0), projectId,
  642.                     PermissionType.ISSUE_EDIT_USERS)) {
  643.                 users.add(creator);
  644.             }
  645.         }

  646.         int i = 0;
  647.         List<User> userList = new ArrayList<User>();
  648.         for (Iterator<User> iter = users.iterator(); iter.hasNext(); i++) {
  649.             userList.add((User) iter.next());
  650.         }
  651.         return userList;
  652.     }

  653.     public User checkLogin(String login, Object authentication, int authType, int reqSource)
  654.             throws AuthenticatorException {
  655.         try {
  656.             PluggableAuthenticator authenticator = (PluggableAuthenticator) authenticatorClass.newInstance();
  657.             if (authenticator != null) {
  658.                 HashMap<String, Object> values = new HashMap<String, Object>();
  659.                 values.put("userService", this);
  660.                 values.put("configurationService", configurationService);
  661.                 authenticator.initialize(values);
  662.                 return authenticator.checkLogin(login, authentication, authType,
  663.                         (reqSource == 0 ? AuthenticationConstants.REQ_SOURCE_UNKNOWN : reqSource));
  664.             }

  665.             logger.error("Unable to create new authenticator.");
  666.             throw new AuthenticatorException(AuthenticatorException.SYSTEM_ERROR);
  667.         } catch (IllegalAccessException iae) {
  668.             logger.error("Authenticator class " + authenticatorClassName + " can not be instantiated.");
  669.             throw new AuthenticatorException(AuthenticatorException.SYSTEM_ERROR);
  670.         } catch (InstantiationException ie) {
  671.             logger.error("Authenticator class " + authenticatorClassName + " can not be instantiated.");
  672.             throw new AuthenticatorException(AuthenticatorException.SYSTEM_ERROR);
  673.         } catch (ClassCastException cce) {
  674.             logger.error("Authenticator class " + authenticatorClassName
  675.                     + " does not extend the PluggableAuthenticator class.");
  676.             throw new AuthenticatorException(AuthenticatorException.SYSTEM_ERROR);
  677.         }
  678.     }

  679.     public boolean allowRegistration(User user, Object authentication, int authType, int reqSource)
  680.             throws AuthenticatorException {
  681.         try {
  682.             PluggableAuthenticator authenticator = (PluggableAuthenticator) authenticatorClass.newInstance();
  683.             if (authenticator != null) {
  684.                 HashMap<String, Object> values = new HashMap<String, Object>();
  685.                 values.put("userService", this);
  686.                 values.put("configurationService", configurationService);
  687.                 authenticator.initialize(values);
  688.                 if (authenticator.allowProfileCreation(user, authentication, authType,
  689.                         (reqSource == 0 ? AuthenticationConstants.REQ_SOURCE_UNKNOWN : reqSource))) {
  690.                     return authenticator.allowRegistration(user, authentication, authType,
  691.                             (reqSource == 0 ? AuthenticationConstants.REQ_SOURCE_UNKNOWN : reqSource));
  692.                 }
  693.                 return false;
  694.             }

  695.             logger.error("Unable to create new authenticator.");
  696.             throw new AuthenticatorException(AuthenticatorException.SYSTEM_ERROR);
  697.         } catch (IllegalAccessException iae) {
  698.             logger.error("Authenticator class " + authenticatorClassName + " can not be instantiated.");
  699.             throw new AuthenticatorException(AuthenticatorException.SYSTEM_ERROR);
  700.         } catch (InstantiationException ie) {
  701.             logger.error("Authenticator class " + authenticatorClassName + " can not be instantiated.");
  702.             throw new AuthenticatorException(AuthenticatorException.SYSTEM_ERROR);
  703.         } catch (ClassCastException cce) {
  704.             logger.error("Authenticator class " + authenticatorClassName
  705.                     + " does not extend the PluggableAuthenticator class.");
  706.             throw new AuthenticatorException(AuthenticatorException.SYSTEM_ERROR);
  707.         }
  708.     }

  709.     public boolean allowProfileCreation(User user, Object authentication, int authType, int reqSource)
  710.             throws AuthenticatorException {
  711.         try {
  712.             PluggableAuthenticator authenticator = (PluggableAuthenticator) authenticatorClass.newInstance();
  713.             if (authenticator != null) {
  714.                 HashMap<String, Object> values = new HashMap<String, Object>();
  715.                 values.put("userService", this);
  716.                 values.put("configurationService", configurationService);
  717.                 authenticator.initialize(values);
  718.                 return authenticator.allowProfileCreation(user, authentication, authType,
  719.                         (reqSource == 0 ? AuthenticationConstants.REQ_SOURCE_UNKNOWN : reqSource));
  720.             }

  721.             logger.error("Unable to create new authenticator.");
  722.             throw new AuthenticatorException(AuthenticatorException.SYSTEM_ERROR);
  723.         } catch (IllegalAccessException iae) {
  724.             logger.error("Authenticator class " + authenticatorClassName + " can not be instantiated.");
  725.             throw new AuthenticatorException(AuthenticatorException.SYSTEM_ERROR);
  726.         } catch (InstantiationException ie) {
  727.             logger.error("Authenticator class " + authenticatorClassName + " can not be instantiated.");
  728.             throw new AuthenticatorException(AuthenticatorException.SYSTEM_ERROR);
  729.         } catch (ClassCastException cce) {
  730.             logger.error("Authenticator class " + authenticatorClassName
  731.                     + " does not extend the PluggableAuthenticator class.");
  732.             throw new AuthenticatorException(AuthenticatorException.SYSTEM_ERROR);
  733.         }
  734.     }

  735.     public boolean allowProfileUpdates(User user, Object authentication, int authType, int reqSource)
  736.             throws AuthenticatorException {
  737.         try {
  738.             PluggableAuthenticator authenticator = (PluggableAuthenticator) authenticatorClass.newInstance();
  739.             if (authenticator != null) {
  740.                 HashMap<String, Object> values = new HashMap<String, Object>();
  741.                 values.put("userService", this);
  742.                 values.put("configurationService", configurationService);
  743.                 authenticator.initialize(values);
  744.                 return authenticator.allowProfileUpdates(user, authentication, authType,
  745.                         (reqSource == 0 ? AuthenticationConstants.REQ_SOURCE_UNKNOWN : reqSource));
  746.             }

  747.             logger.error("Unable to create new authenticator.");
  748.             throw new AuthenticatorException(AuthenticatorException.SYSTEM_ERROR);
  749.         } catch (IllegalAccessException iae) {
  750.             logger.error("Authenticator class " + authenticatorClassName + " can not be instantiated.");
  751.             throw new AuthenticatorException(AuthenticatorException.SYSTEM_ERROR);
  752.         } catch (InstantiationException ie) {
  753.             logger.error("Authenticator class " + authenticatorClassName + " can not be instantiated.");
  754.             throw new AuthenticatorException(AuthenticatorException.SYSTEM_ERROR);
  755.         } catch (ClassCastException cce) {
  756.             logger.error("Authenticator class " + authenticatorClassName
  757.                     + " does not extend the PluggableAuthenticator class.");
  758.             throw new AuthenticatorException(AuthenticatorException.SYSTEM_ERROR);
  759.         }
  760.     }

  761.     public boolean allowPasswordUpdates(User user, Object authentication, int authType, int reqSource)
  762.             throws AuthenticatorException {
  763.         try {
  764.             PluggableAuthenticator authenticator = (PluggableAuthenticator) authenticatorClass.newInstance();
  765.             if (authenticator != null) {
  766.                 HashMap<String, Object> values = new HashMap<String, Object>();
  767.                 values.put("userService", this);
  768.                 values.put("configurationService", configurationService);
  769.                 authenticator.initialize(values);
  770.                 return authenticator.allowPasswordUpdates(user, authentication, authType,
  771.                         (reqSource == 0 ? AuthenticationConstants.REQ_SOURCE_UNKNOWN : reqSource));
  772.             }

  773.             logger.error("Unable to create new authenticator.");
  774.             throw new AuthenticatorException(AuthenticatorException.SYSTEM_ERROR);
  775.         } catch (IllegalAccessException iae) {
  776.             logger.error("Authenticator class " + authenticatorClassName + " can not be instantiated.");
  777.             throw new AuthenticatorException(AuthenticatorException.SYSTEM_ERROR);
  778.         } catch (InstantiationException ie) {
  779.             logger.error("Authenticator class " + authenticatorClassName + " can not be instantiated.");
  780.             throw new AuthenticatorException(AuthenticatorException.SYSTEM_ERROR);
  781.         } catch (ClassCastException cce) {
  782.             logger.error("Authenticator class " + authenticatorClassName
  783.                     + " does not extend the PluggableAuthenticator class.");
  784.             throw new AuthenticatorException(AuthenticatorException.SYSTEM_ERROR);
  785.         }
  786.     }

  787.     public boolean allowPermissionUpdates(User user, Object authentication, int authType, int reqSource)
  788.             throws AuthenticatorException {
  789.         try {
  790.             PluggableAuthenticator authenticator = (PluggableAuthenticator) authenticatorClass.newInstance();
  791.             if (authenticator != null) {
  792.                 HashMap<String, Object> values = new HashMap<String, Object>();
  793.                 values.put("userService", this);
  794.                 values.put("configurationService", configurationService);
  795.                 authenticator.initialize(values);
  796.                 return authenticator.allowPermissionUpdates(user, authentication, authType,
  797.                         (reqSource == 0 ? AuthenticationConstants.REQ_SOURCE_UNKNOWN : reqSource));
  798.             }

  799.             logger.error("Unable to create new authenticator.");
  800.             throw new AuthenticatorException(AuthenticatorException.SYSTEM_ERROR);
  801.         } catch (IllegalAccessException iae) {
  802.             logger.error("Authenticator class " + authenticatorClassName + " can not be instantiated.");
  803.             throw new AuthenticatorException(AuthenticatorException.SYSTEM_ERROR);
  804.         } catch (InstantiationException ie) {
  805.             logger.error("Authenticator class " + authenticatorClassName + " can not be instantiated.");
  806.             throw new AuthenticatorException(AuthenticatorException.SYSTEM_ERROR);
  807.         } catch (ClassCastException cce) {
  808.             logger.error("Authenticator class " + authenticatorClassName
  809.                     + " does not extend the PluggableAuthenticator class.");
  810.             throw new AuthenticatorException(AuthenticatorException.SYSTEM_ERROR);
  811.         }
  812.     }

  813.     public boolean allowPreferenceUpdates(User user, Object authentication, int authType, int reqSource)
  814.             throws AuthenticatorException {
  815.         try {
  816.             PluggableAuthenticator authenticator = (PluggableAuthenticator) authenticatorClass.newInstance();
  817.             if (authenticator != null) {
  818.                 HashMap<String, Object> values = new HashMap<String, Object>();
  819.                 values.put("userService", this);
  820.                 values.put("configurationService", configurationService);
  821.                 authenticator.initialize(values);
  822.                 return authenticator.allowPreferenceUpdates(user, authentication, authType,
  823.                         (reqSource == 0 ? AuthenticationConstants.REQ_SOURCE_UNKNOWN : reqSource));
  824.             }

  825.             logger.error("Unable to create new authenticator.");
  826.             throw new AuthenticatorException(AuthenticatorException.SYSTEM_ERROR);
  827.         } catch (IllegalAccessException iae) {
  828.             logger.error("Authenticator class " + authenticatorClassName + " can not be instantiated.");
  829.             throw new AuthenticatorException(AuthenticatorException.SYSTEM_ERROR);
  830.         } catch (InstantiationException ie) {
  831.             logger.error("Authenticator class " + authenticatorClassName + " can not be instantiated.");
  832.             throw new AuthenticatorException(AuthenticatorException.SYSTEM_ERROR);
  833.         } catch (ClassCastException cce) {
  834.             logger.error("Authenticator class " + authenticatorClassName
  835.                     + " does not extend the PluggableAuthenticator class.");
  836.             throw new AuthenticatorException(AuthenticatorException.SYSTEM_ERROR);
  837.         }
  838.     }


  839. }