protected void setPrincipal(long companyId, long userId, String remoteUser, String password) {

    if ((userId == 0) && (remoteUser == null)) {
      return;
    }

    String name = String.valueOf(userId);

    if (PropsValues.PORTAL_JAAS_ENABLE) {
      long remoteUserId = 0;

      try {
        remoteUserId = JAASHelper.getJaasUserId(companyId, remoteUser);
      } catch (Exception e) {
        if (_log.isWarnEnabled()) {
          _log.warn(e);
        }
      }

      if (remoteUserId > 0) {
        name = String.valueOf(remoteUserId);
      }
    } else if (remoteUser != null) {
      name = remoteUser;
    }

    PrincipalThreadLocal.setName(name);

    PrincipalThreadLocal.setPassword(password);
  }
  protected long loginUser(
      HttpServletRequest request,
      HttpServletResponse response,
      long companyId,
      long userId,
      String remoteUser)
      throws PortalException, SystemException {

    if ((userId > 0) || (remoteUser == null)) {
      return userId;
    }

    if (PropsValues.PORTAL_JAAS_ENABLE) {
      userId = JAASHelper.getJaasUserId(companyId, remoteUser);
    } else {
      userId = GetterUtil.getLong(remoteUser);
    }

    EventsProcessorUtil.process(
        PropsKeys.LOGIN_EVENTS_PRE, PropsValues.LOGIN_EVENTS_PRE, request, response);

    User user = UserLocalServiceUtil.getUserById(userId);

    if (PropsValues.USERS_UPDATE_LAST_LOGIN) {
      UserLocalServiceUtil.updateLastLogin(userId, request.getRemoteAddr());
    }

    HttpSession session = request.getSession();

    session.setAttribute(WebKeys.USER, user);
    session.setAttribute(WebKeys.USER_ID, new Long(userId));
    session.setAttribute(Globals.LOCALE_KEY, user.getLocale());

    EventsProcessorUtil.process(
        PropsKeys.LOGIN_EVENTS_POST, PropsValues.LOGIN_EVENTS_POST, request, response);

    return userId;
  }