protected int authenticate(
      long companyId,
      long ldapServerId,
      String emailAddress,
      String screenName,
      long userId,
      String password)
      throws Exception {

    String postfix = LDAPSettingsUtil.getPropertyPostfix(ldapServerId);

    LdapContext ldapContext = PortalLDAPUtil.getContext(ldapServerId, companyId);

    if (ldapContext == null) {
      return FAILURE;
    }

    try {
      String baseDN = PrefsPropsUtil.getString(companyId, PropsKeys.LDAP_BASE_DN + postfix);

      //  Process LDAP auth search filter

      String filter =
          LDAPSettingsUtil.getAuthSearchFilter(
              ldapServerId, companyId, emailAddress, screenName, String.valueOf(userId));

      Properties userMappings = LDAPSettingsUtil.getUserMappings(ldapServerId, companyId);

      String userMappingsScreenName =
          GetterUtil.getString(userMappings.getProperty("screenName")).toLowerCase();

      SearchControls searchControls =
          new SearchControls(
              SearchControls.SUBTREE_SCOPE,
              1,
              0,
              new String[] {userMappingsScreenName},
              false,
              false);

      NamingEnumeration<SearchResult> enu = ldapContext.search(baseDN, filter, searchControls);

      if (enu.hasMoreElements()) {
        if (_log.isDebugEnabled()) {
          _log.debug("Search filter returned at least one result");
        }

        SearchResult result = enu.nextElement();

        String fullUserDN = PortalLDAPUtil.getNameInNamespace(ldapServerId, companyId, result);

        Attributes attributes =
            PortalLDAPUtil.getUserAttributes(ldapServerId, companyId, ldapContext, fullUserDN);

        LDAPAuthResult ldapAuthResult = null;

        if (PropsValues.LDAP_IMPORT_USER_PASSWORD_ENABLED) {
          ldapAuthResult = authenticate(ldapContext, companyId, attributes, fullUserDN, password);

          // Process LDAP failure codes

          String errorMessage = ldapAuthResult.getErrorMessage();

          if (errorMessage != null) {
            if (errorMessage.indexOf(
                    PrefsPropsUtil.getString(companyId, PropsKeys.LDAP_ERROR_USER_LOCKOUT))
                != -1) {

              throw new UserLockoutException();
            } else if (errorMessage.indexOf(
                    PrefsPropsUtil.getString(companyId, PropsKeys.LDAP_ERROR_PASSWORD_EXPIRED))
                != -1) {

              throw new PasswordExpiredException();
            }
          }

          if (!ldapAuthResult.isAuthenticated() && PropsValues.LDAP_IMPORT_USER_PASSWORD_ENABLED) {

            return FAILURE;
          }
        }

        // Get user or create from LDAP

        User user =
            PortalLDAPImporterUtil.importLDAPUser(
                ldapServerId, companyId, ldapContext, attributes, password);

        // Process LDAP success codes

        if (ldapAuthResult != null) {
          String resultCode = ldapAuthResult.getResponseControl();

          if (resultCode.equals(LDAPAuth.RESULT_PASSWORD_RESET)) {
            UserLocalServiceUtil.updatePasswordReset(user.getUserId(), true);
          }
        }
      } else {
        if (_log.isDebugEnabled()) {
          _log.debug("Search filter did not return any results");
        }

        return DNE;
      }

      enu.close();
    } catch (Exception e) {
      if (e instanceof PasswordExpiredException || e instanceof UserLockoutException) {

        throw e;
      }

      _log.error("Problem accessing LDAP server", e);

      return FAILURE;
    } finally {
      if (ldapContext != null) {
        ldapContext.close();
      }
    }

    return SUCCESS;
  }
예제 #2
0
  private static void _updateAdminUser(
      HttpServletRequest request, UnicodeProperties unicodeProperties) throws Exception {

    ThemeDisplay themeDisplay = (ThemeDisplay) request.getAttribute(WebKeys.THEME_DISPLAY);

    Company company = CompanyLocalServiceUtil.getCompanyById(themeDisplay.getCompanyId());

    String emailAddress =
        ParamUtil.getString(
            request,
            "adminEmailAddress",
            PropsValues.DEFAULT_ADMIN_EMAIL_ADDRESS_PREFIX + StringPool.AT + company.getMx());

    PropsValues.ADMIN_EMAIL_FROM_ADDRESS = emailAddress;

    unicodeProperties.put(PropsKeys.ADMIN_EMAIL_FROM_ADDRESS, emailAddress);

    ScreenNameGenerator screenNameGenerator = ScreenNameGeneratorFactory.getInstance();

    String screenName =
        GetterUtil.getString(PropsValues.DEFAULT_ADMIN_EMAIL_ADDRESS_PREFIX, "test");

    try {
      screenName = screenNameGenerator.generate(0, 0, emailAddress);
    } catch (Exception e) {
    }

    String firstName =
        ParamUtil.getString(request, "adminFirstName", PropsValues.DEFAULT_ADMIN_FIRST_NAME);
    String lastName =
        ParamUtil.getString(request, "adminLastName", PropsValues.DEFAULT_ADMIN_LAST_NAME);

    FullNameGenerator fullNameGenerator = FullNameGeneratorFactory.getInstance();

    String fullName = fullNameGenerator.getFullName(firstName, null, lastName);

    PropsValues.ADMIN_EMAIL_FROM_NAME = fullName;

    unicodeProperties.put(PropsKeys.ADMIN_EMAIL_FROM_NAME, fullName);

    User user = null;

    try {
      user = UserLocalServiceUtil.getUserByEmailAddress(themeDisplay.getCompanyId(), emailAddress);

      String greeting =
          LanguageUtil.format(
              themeDisplay.getLocale(), "welcome-x", StringPool.SPACE + fullName, false);

      Contact contact = user.getContact();

      Calendar birthdayCal = CalendarFactoryUtil.getCalendar();

      birthdayCal.setTime(contact.getBirthday());

      int birthdayMonth = birthdayCal.get(Calendar.MONTH);
      int birthdayDay = birthdayCal.get(Calendar.DAY_OF_MONTH);
      int birthdayYear = birthdayCal.get(Calendar.YEAR);

      user =
          UserLocalServiceUtil.updateUser(
              user.getUserId(),
              StringPool.BLANK,
              StringPool.BLANK,
              StringPool.BLANK,
              false,
              user.getReminderQueryQuestion(),
              user.getReminderQueryAnswer(),
              screenName,
              emailAddress,
              user.getFacebookId(),
              user.getOpenId(),
              themeDisplay.getLanguageId(),
              user.getTimeZoneId(),
              greeting,
              user.getComments(),
              firstName,
              user.getMiddleName(),
              lastName,
              contact.getPrefixId(),
              contact.getSuffixId(),
              contact.isMale(),
              birthdayMonth,
              birthdayDay,
              birthdayYear,
              contact.getSmsSn(),
              contact.getAimSn(),
              contact.getFacebookSn(),
              contact.getIcqSn(),
              contact.getJabberSn(),
              contact.getMsnSn(),
              contact.getMySpaceSn(),
              contact.getSkypeSn(),
              contact.getTwitterSn(),
              contact.getYmSn(),
              contact.getJobTitle(),
              null,
              null,
              null,
              null,
              null,
              new ServiceContext());
    } catch (NoSuchUserException nsue) {
      UserLocalServiceUtil.addDefaultAdminUser(
          themeDisplay.getCompanyId(),
          screenName,
          emailAddress,
          themeDisplay.getLocale(),
          firstName,
          StringPool.BLANK,
          lastName);

      user = UserLocalServiceUtil.getUserByEmailAddress(themeDisplay.getCompanyId(), emailAddress);

      String defaultAdminEmailAddress =
          PropsValues.DEFAULT_ADMIN_EMAIL_ADDRESS_PREFIX + "@" + PropsValues.COMPANY_DEFAULT_WEB_ID;

      if (!emailAddress.equals(defaultAdminEmailAddress)) {
        User testUser =
            UserLocalServiceUtil.fetchUserByEmailAddress(
                themeDisplay.getCompanyId(), defaultAdminEmailAddress);

        if (testUser != null) {
          UserLocalServiceUtil.updateStatus(
              testUser.getUserId(), WorkflowConstants.STATUS_INACTIVE);
        }
      }
    }

    user = UserLocalServiceUtil.updatePasswordReset(user.getUserId(), true);

    HttpSession session = request.getSession();

    session.setAttribute(WebKeys.EMAIL_ADDRESS, emailAddress);
    session.setAttribute(WebKeys.SETUP_WIZARD_PASSWORD_UPDATED, true);
    session.setAttribute(WebKeys.USER_ID, user.getUserId());
  }
  protected User addUser(HttpSession session, long companyId, Userinfo userinfo) throws Exception {

    long creatorUserId = 0;
    boolean autoPassword = true;
    String password1 = StringPool.BLANK;
    String password2 = StringPool.BLANK;
    boolean autoScreenName = true;
    String screenName = StringPool.BLANK;
    String emailAddress = userinfo.getEmail();
    String openId = StringPool.BLANK;
    Locale locale = LocaleUtil.getDefault();
    String firstName = userinfo.getGivenName();
    String middleName = StringPool.BLANK;
    String lastName = userinfo.getFamilyName();
    int prefixId = 0;
    int suffixId = 0;
    boolean male = Validator.equals(userinfo.getGender(), "male");
    int birthdayMonth = Calendar.JANUARY;
    int birthdayDay = 1;
    int birthdayYear = 1970;
    String jobTitle = StringPool.BLANK;
    long[] groupIds = null;
    long[] organizationIds = null;
    long[] roleIds = null;
    long[] userGroupIds = null;
    boolean sendEmail = true;

    ServiceContext serviceContext = new ServiceContext();

    User user =
        UserLocalServiceUtil.addUser(
            creatorUserId,
            companyId,
            autoPassword,
            password1,
            password2,
            autoScreenName,
            screenName,
            emailAddress,
            0,
            openId,
            locale,
            firstName,
            middleName,
            lastName,
            prefixId,
            suffixId,
            male,
            birthdayMonth,
            birthdayDay,
            birthdayYear,
            jobTitle,
            groupIds,
            organizationIds,
            roleIds,
            userGroupIds,
            sendEmail,
            serviceContext);

    user = UserLocalServiceUtil.updateLastLogin(user.getUserId(), user.getLoginIP());

    user = UserLocalServiceUtil.updatePasswordReset(user.getUserId(), false);

    user = UserLocalServiceUtil.updateEmailAddressVerified(user.getUserId(), true);

    session.setAttribute("GOOGLE_USER_EMAIL_ADDRESS", emailAddress);

    return user;
  }