public boolean accept(String from, String recipient, Message message) {
    try {
      String messageId = getMessageId(recipient, message);

      if ((messageId == null)
          || (!messageId.startsWith(MBUtil.MESSAGE_POP_PORTLET_PREFIX, getOffset()))) {

        return false;
      }

      Company company = getCompany(messageId);
      long categoryId = getCategoryId(messageId);

      MBCategory category = MBCategoryLocalServiceUtil.getCategory(categoryId);

      if (category.getCompanyId() != company.getCompanyId()) {
        return false;
      }

      if (_log.isDebugEnabled()) {
        _log.debug("Check to see if user " + from + " exists");
      }

      UserLocalServiceUtil.getUserByEmailAddress(company.getCompanyId(), from);

      return true;
    } catch (Exception e) {
      if (_log.isErrorEnabled()) {
        _log.error("Unable to process message: " + message, e);
      }

      return false;
    }
  }
  protected int authenticateOmniadmin(
      long companyId, String emailAddress, String screenName, long userId) throws Exception {

    // Only allow omniadmin if Liferay password checking is enabled

    if (PropsValues.AUTH_PIPELINE_ENABLE_LIFERAY_CHECK) {
      if (userId > 0) {
        if (OmniadminUtil.isOmniadmin(userId)) {
          return SUCCESS;
        }
      } else if (Validator.isNotNull(emailAddress)) {
        try {
          User user = UserLocalServiceUtil.getUserByEmailAddress(companyId, emailAddress);

          if (OmniadminUtil.isOmniadmin(user.getUserId())) {
            return SUCCESS;
          }
        } catch (NoSuchUserException nsue) {
        }
      } else if (Validator.isNotNull(screenName)) {
        try {
          User user = UserLocalServiceUtil.getUserByScreenName(companyId, screenName);

          if (OmniadminUtil.isOmniadmin(user.getUserId())) {
            return SUCCESS;
          }
        } catch (NoSuchUserException nsue) {
        }
      }
    }

    return FAILURE;
  }
 @Override
 public void run(String[] arg0) throws ActionException {
   Properties props = new Properties();
   try {
     props.load(
         this.getClass().getClassLoader().getResourceAsStream("password.changer.properties"));
     String type = props.getProperty("type");
     String virtualHost = props.getProperty("virtualhost");
     Company c = CompanyUtil.fetchByVirtualHost(virtualHost);
     User u = null;
     String name = null;
     if ("screenname".equals(type)) {
       String screenName = props.getProperty("screenname");
       u = UserLocalServiceUtil.getUserByScreenName(c.getCompanyId(), screenName);
       name = screenName;
     } else if ("e-mail".equals(type)) {
       String emailAddress = props.getProperty("emailaddress");
       u = UserLocalServiceUtil.getUserByEmailAddress(c.getCompanyId(), emailAddress);
       name = emailAddress;
     } else {
       _log.error(
           "You should set type to screenname or e-mail if you want to use the password updater.");
     }
     String password = props.getProperty("password");
     UserLocalServiceUtil.updatePasswordManually(u.getUserId(), password, false, true, new Date());
     _log.info("Password for " + name + " was updated.");
   } catch (Exception e) {
     _log.error(e);
   }
 }
  @Override
  public String[] login(HttpServletRequest request, HttpServletResponse response)
      throws AutoLoginException {
    String emailId = request.getHeader(AUTH_EMAIL_VALUE);
    String extid = request.getHeader(AUTH_EXTID_VALUE);

    log.info("Attempting auto login for email: '" + emailId + "' and external id: '" + extid + "'");

    Enumeration headerNames = request.getHeaderNames();
    while (headerNames.hasMoreElements()) {
      String key = (String) headerNames.nextElement();
      String value = request.getHeader(key);
      log.debug(key + ":" + value);
    }

    if (emailId == null || emailId.isEmpty() || extid == null || extid.isEmpty()) {
      log.error("Empty credentials, auto login impossible.");
      return new String[] {};
    }
    long companyId = PortalUtil.getCompanyId(request);

    User user = null;
    try {
      user = UserLocalServiceUtil.getUserByEmailAddress(companyId, emailId);
    } catch (SystemException | PortalException e) {
      log.error(
          "Exception during get user by email: '"
              + emailId
              + "' and company id: '"
              + companyId
              + "'",
          e);
    }

    // If user was found by liferay
    if (user != null) {
      // Create a return credentials object
      return new String[] {
        String.valueOf(user.getUserId()),
        user.getPassword(), // Encrypted Liferay password
        Boolean.TRUE.toString() // True: password is encrypted
      };
    } else {
      log.error("Could not get user with email: '" + emailId + "'.");
      return new String[] {};
    }
  }
  protected User getUser(long companyId, LDAPUser ldapUser) throws Exception {
    User user = null;

    try {
      String authType =
          PrefsPropsUtil.getString(
              companyId,
              PropsKeys.COMPANY_SECURITY_AUTH_TYPE,
              PropsValues.COMPANY_SECURITY_AUTH_TYPE);

      if (authType.equals(CompanyConstants.AUTH_TYPE_SN) && !ldapUser.isAutoScreenName()) {

        user = UserLocalServiceUtil.getUserByScreenName(companyId, ldapUser.getScreenName());
      } else {
        user = UserLocalServiceUtil.getUserByEmailAddress(companyId, ldapUser.getEmailAddress());
      }
    } catch (NoSuchUserException nsue) {
    }

    return user;
  }
  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());
  }
 private static com.liferay.portal.model.User getLiferayUser(PortletRequest request, User user)
     throws PortalException, SystemException {
   ThemeDisplay themeDisplay = (ThemeDisplay) request.getAttribute(WebKeys.THEME_DISPLAY);
   long companyId = themeDisplay.getCompanyId();
   return UserLocalServiceUtil.getUserByEmailAddress(companyId, user.email);
 }
  public void deliver(String from, String recipient, Message message)
      throws MessageListenerException {

    try {
      StopWatch stopWatch = null;

      if (_log.isDebugEnabled()) {
        stopWatch = new StopWatch();

        stopWatch.start();

        _log.debug("Deliver message from " + from + " to " + recipient);
      }

      String messageId = getMessageId(recipient, message);

      Company company = getCompany(messageId);

      if (_log.isDebugEnabled()) {
        _log.debug("Message id " + messageId);
      }

      long groupId = 0;
      long categoryId = getCategoryId(messageId);

      try {
        MBCategory category = MBCategoryLocalServiceUtil.getCategory(categoryId);

        groupId = category.getGroupId();
      } catch (NoSuchCategoryException nsce) {
        groupId = categoryId;
        categoryId = MBCategoryConstants.DEFAULT_PARENT_CATEGORY_ID;
      }

      if (_log.isDebugEnabled()) {
        _log.debug("Group id " + groupId);
        _log.debug("Category id " + categoryId);
      }

      User user = UserLocalServiceUtil.getUserByEmailAddress(company.getCompanyId(), from);

      long parentMessageId = getParentMessageId(recipient, message);

      if (_log.isDebugEnabled()) {
        _log.debug("Parent message id " + parentMessageId);
      }

      MBMessage parentMessage = null;

      try {
        if (parentMessageId > 0) {
          parentMessage = MBMessageLocalServiceUtil.getMessage(parentMessageId);
        }
      } catch (NoSuchMessageException nsme) {

        // If the parent message does not exist we ignore it and post
        // the message as a new thread.

      }

      if (_log.isDebugEnabled()) {
        _log.debug("Parent message " + parentMessage);
      }

      String subject = MBUtil.getSubjectWithoutMessageId(message);

      MBMailMessage collector = new MBMailMessage();

      MBUtil.collectPartContent(message, collector);

      PermissionCheckerUtil.setThreadValues(user);

      ServiceContext serviceContext = new ServiceContext();

      serviceContext.setAddGroupPermissions(true);
      serviceContext.setAddGuestPermissions(true);
      serviceContext.setLayoutFullURL(
          PortalUtil.getLayoutFullURL(groupId, PortletKeys.MESSAGE_BOARDS));
      serviceContext.setScopeGroupId(groupId);

      if (parentMessage == null) {
        MBMessageServiceUtil.addMessage(
            groupId,
            categoryId,
            subject,
            collector.getBody(),
            MBMessageConstants.DEFAULT_FORMAT,
            collector.getFiles(),
            false,
            0.0,
            true,
            serviceContext);
      } else {
        MBMessageServiceUtil.addMessage(
            groupId,
            categoryId,
            parentMessage.getThreadId(),
            parentMessage.getMessageId(),
            subject,
            collector.getBody(),
            MBMessageConstants.DEFAULT_FORMAT,
            collector.getFiles(),
            false,
            0.0,
            true,
            serviceContext);
      }

      if (_log.isDebugEnabled()) {
        _log.debug("Delivering message takes " + stopWatch.getTime() + " ms");
      }
    } catch (PrincipalException pe) {
      if (_log.isDebugEnabled()) {
        _log.debug("Prevented unauthorized post from " + from);
      }

      throw new MessageListenerException(pe);
    } catch (Exception e) {
      _log.error(e, e);

      throw new MessageListenerException(e);
    } finally {
      PermissionCheckerUtil.setThreadValues(null);
    }
  }
  protected void login(
      ThemeDisplay themeDisplay,
      ActionRequest actionRequest,
      ActionResponse actionResponse,
      PortletPreferences preferences)
      throws Exception {

    HttpServletRequest request = PortalUtil.getHttpServletRequest(actionRequest);
    HttpServletResponse response = PortalUtil.getHttpServletResponse(actionResponse);

    String login = ParamUtil.getString(actionRequest, "login");
    String password = actionRequest.getParameter("password");
    boolean rememberMe = ParamUtil.getBoolean(actionRequest, "rememberMe");

    String authType = preferences.getValue("authType", null);

    // cusotm code =============
    try {
      User tmp = null;
      UserEntry userEntryTmp = null;
      if (Validator.isEmailAddress(login)) {
        tmp = UserLocalServiceUtil.getUserByEmailAddress(PortalUtil.getCompanyId(request), login);
        login = String.valueOf(tmp.getUserId());
        System.out.println("email:" + login);
      } else if (Validator.isNumber(login)) {
        // is mobile number
        //				UserEntryLocalServiceUtil.get
        userEntryTmp = UserEntryLocalServiceUtil.findByMobilePhone(login);
        login = String.valueOf(userEntryTmp.getUserId());
        System.out.println("mobile number:" + login);
      } else {
        // userEntryTmp = UserEntryLocalServiceUtil.findByUserName(login);
        tmp = UserLocalServiceUtil.getUserByScreenName(PortalUtil.getCompanyId(request), login);
        login = String.valueOf(tmp.getUserId());
        System.out.println("userName:"******"/portal/protected");
    } else {
      String redirect = ParamUtil.getString(actionRequest, "redirect");

      if (Validator.isNotNull(redirect)) {
        redirect = PortalUtil.escapeRedirect(redirect);

        if (!redirect.startsWith(Http.HTTP)) {
          redirect = getCompleteRedirectURL(request, redirect);
        }

        actionResponse.sendRedirect(redirect);
      } else {
        boolean doActionAfterLogin = ParamUtil.getBoolean(actionRequest, "doActionAfterLogin");

        if (doActionAfterLogin) {
          return;
        } else {
          actionResponse.sendRedirect(themeDisplay.getPathMain());
        }
      }
    }
  }
  @Override
  public void processAction(
      ActionMapping mapping,
      ActionForm form,
      PortletConfig portletConfig,
      ActionRequest actionRequest,
      ActionResponse actionResponse)
      throws Exception {

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

    String portletName = portletConfig.getPortletName();

    if (!portletName.equals(PortletKeys.FAST_LOGIN)) {
      throw new PrincipalException();
    }

    if (actionRequest.getRemoteUser() != null) {
      actionResponse.sendRedirect(themeDisplay.getPathMain());

      return;
    }

    String cmd = ParamUtil.getString(actionRequest, Constants.CMD);

    String emailAddress = ParamUtil.getString(actionRequest, "emailAddress");

    PortletURL portletURL =
        PortletURLFactoryUtil.create(
            actionRequest,
            PortletKeys.FAST_LOGIN,
            themeDisplay.getPlid(),
            PortletRequest.RENDER_PHASE);

    portletURL.setParameter("struts_action", "/login/login_redirect");
    portletURL.setParameter("emailAddress", emailAddress);
    portletURL.setParameter("anonymousUser", Boolean.TRUE.toString());
    portletURL.setWindowState(LiferayWindowState.POP_UP);

    JSONObject jsonObject = JSONFactoryUtil.createJSONObject();

    try {
      if (cmd.equals(Constants.ADD)) {
        addAnonymousUser(actionRequest, actionResponse);

        sendRedirect(actionRequest, actionResponse, portletURL.toString());
      } else if (cmd.equals(Constants.UPDATE)) {
        jsonObject = updateIncompleteUser(actionRequest, actionResponse);

        writeJSON(actionRequest, actionResponse, jsonObject);
      }
    } catch (Exception e) {
      if (cmd.equals(Constants.UPDATE)) {
        jsonObject.putException(e);

        writeJSON(actionRequest, actionResponse, jsonObject);
      } else if (e instanceof DuplicateUserEmailAddressException) {
        User user =
            UserLocalServiceUtil.getUserByEmailAddress(themeDisplay.getCompanyId(), emailAddress);

        if (user.getStatus() != WorkflowConstants.STATUS_INCOMPLETE) {
          SessionErrors.add(actionRequest, e.getClass());
        } else {
          sendRedirect(actionRequest, actionResponse, portletURL.toString());
        }
      } else if (e instanceof CaptchaTextException
          || e instanceof CompanyMaxUsersException
          || e instanceof ContactFirstNameException
          || e instanceof ContactFullNameException
          || e instanceof ContactLastNameException
          || e instanceof EmailAddressException
          || e instanceof GroupFriendlyURLException
          || e instanceof ReservedUserEmailAddressException
          || e instanceof UserEmailAddressException) {

        SessionErrors.add(actionRequest, e.getClass(), e);
      } else {
        _log.error("Unable to create anonymous account", e);

        PortalUtil.sendError(e, actionRequest, actionResponse);
      }
    }
  }