コード例 #1
0
  private OpenIDServerDAO getDAO() {
    if (dao == null) {
      ELUtil.getInstance().autowire(this);
    }

    return dao;
  }
コード例 #2
0
  public void main(IWContext iwc) throws Exception {
    ELUtil.getInstance().autowire(this);

    String val = iwc.getParameter("submitBtn");
    if (!StringUtil.isEmpty(val)) {
      dao.createDish(
          iwc.getParameter("dishName"),
          iwc.getParameter("dishDescription"),
          iwc.getParameter("dishPrice"));
    }

    Layer container = new Layer(); // 	<div>
    add(container);

    IWResourceBundle iwrb = getResourceBundle(iwc);

    Form form = new Form();
    container.add(form);

    createField(form, "Dish", "dish_name", new TextInput("dishName"), iwrb);
    createField(form, "Description", "description", new TextArea("dishDescription"), iwrb);
    createField(form, "Price", "price", new TextInput("dishPrice"), iwrb);

    SubmitButton submitBtn =
        new SubmitButton("submitBtn", iwrb.getLocalizedString("submit", "Submit"));
    form.add(submitBtn);
  }
コード例 #3
0
 public void shutdown() {
   ELUtil.getInstance().publishEvent(new IWMainApplicationShutdownEvent(this));
   // poolMgr.release();
   log.info("Stopping IdegaWeb");
   endIdegaWebApplication();
   this.iwma = null;
   // super.destroy();
 }
 protected User getLoggedInUser() {
   try {
     LoginSession loginSession = ELUtil.getInstance().getBean(LoginSession.class);
     return loginSession.isLoggedIn() ? loginSession.getUser() : null;
   } catch (Exception e) {
     LOGGER.log(Level.WARNING, "Error getting logged in user", e);
   }
   return null;
 }
コード例 #5
0
  /**
   * Takes value from given XForms variable.
   *
   * @param expressionContext path to variable to be evaluated, for example: "Expression context [1]
   *     /data[1]/Applicant_name_fbc_66[1]" .
   * @param instance
   * @param paramsExp is variable names given for expression, usually in form
   *     "#{instance('data-instance')/Variable_name_fbc_123}",.. separated by comma.
   * @param returnsSpaceOnFailure if set to <code>true</code>, then returns {@link
   *     CoreConstants#SPACE} on failure, otherwise adds {@link CoreConstants#EMPTY} to places in
   *     string, where failures found.
   * @return Xforms variable values separated by comma. For example: paramsExp -
   *     #{instance(`data-instance`)/Applicant_name_fbc_53},... will return '11', '',... as answer,
   *     where 11 is value of given Xforms variable.
   * @author <a href="mailto:[email protected]">Martynas Stakė</a>
   */
  private static String resolveParams(
      ExpressionContext expressionContext,
      Instance instance,
      String paramsExp,
      boolean returnsSpaceOnFailure) {

    String[] params = paramsExp.split(CoreConstants.COMMA);
    StringBuilder resolvedParamsExp = new StringBuilder();

    Object value = null;

    for (String param : params) {
      if (param.contains(ELUtil.EXPRESSION_BEGIN)) {
        param = ELUtil.cleanupExp(param.trim());

        try {
          if (expressionContext != null) {
            value = getInstanceValueFromExpression(expressionContext, param);
          } else if (instance != null) {
            value = getInstanceValueFromExpression(instance, param);
          } else {
            value = CoreConstants.EMPTY;
          }
        } catch (XFormsException e) {
          LOGGER.log(Level.WARNING, "Unable to get value from parameter: " + param, e);
        }

        if (value == null || value.toString().equals(CoreConstants.EMPTY)) {
          value = CoreConstants.EMPTY;
        }

        if (returnsSpaceOnFailure) {
          if (value == null || value.toString().equals(CoreConstants.EMPTY)) {
            return CoreConstants.SPACE;
          }
        }

      } else {
        value = param;
      }

      resolvedParamsExp
          .append(CoreConstants.QOUTE_SINGLE_MARK)
          .append(value)
          .append(CoreConstants.QOUTE_SINGLE_MARK)
          .append(CoreConstants.JS_STR_PARAM_SEPARATOR);
    }

    return resolvedParamsExp.toString();
  }
コード例 #6
0
  protected User getCurrentUser() {
    User user = null;
    try {
      LoginSession loginSession = ELUtil.getInstance().getBean(LoginSession.class);
      user = loginSession.getUser();
    } catch (Exception e) {
      LOGGER.log(Level.WARNING, "Error getting current user");
    }

    if (user == null) {
      IWContext iwc = CoreUtil.getIWContext();
      user = iwc == null ? null : iwc.isLoggedOn() ? iwc.getCurrentUser() : null;
    }

    return user;
  }
コード例 #7
0
  private boolean isAuthenticatedAndApproved(IWContext iwc, User user, AuthRequest authReq) {

    OpenIDServerBean serverBean = ELUtil.getInstance().getBean("openIDServerBean");
    List<AuthorizedAttribute> required = serverBean.getRequiredAttributes();
    List<AuthorizedAttribute> allAttributes = serverBean.getRequestedAttributes();

    // allowedRealm value set in presentation layer
    boolean allowAction = isAllowAction(iwc);

    // Deny by default if no attributes are exchanged
    boolean allowed = allAttributes != null && !allAttributes.isEmpty();

    // Check each allowed attribute
    // If it has been stored, it is always allow, otherwise it is not
    if (allowAction) {
      allowed = true; // allow by default if allow action
      if (allAttributes != null) {
        for (AuthorizedAttribute attr : allAttributes) {
          if (!attr.getIsAllowed() && required.contains(attr)) {
            // If not allowed but required
            return false;
          }
        }
      }
    } else {
      // denied by default if no attributes are requested, i.e. no always allow option
      // if there are no attributes requested
      if (allAttributes != null) {
        for (AuthorizedAttribute attr : allAttributes) {
          // Check if not always allowed
          if (attr.isNotYetStored()) {
            // Not always-allow and not an allow-action, hence not allowed
            return false;
          }
          if (!attr.getIsAllowed() && required.contains(attr)) {
            // If not allowed but required
            return false;
          } else {
            allowed = true;
          }
        }
      }
    }

    return allowed;
  }
コード例 #8
0
  protected HttpSession getSession() {
    RequestResponseProvider provider = null;
    try {
      provider = ELUtil.getInstance().getBean(RequestResponseProvider.class);
    } catch (Exception e) {
    }

    HttpSession session = null;
    if (provider != null && provider.getRequest() != null)
      session = provider.getRequest().getSession(Boolean.TRUE);

    if (session == null) {
      IWContext iwc = CoreUtil.getIWContext();
      if (iwc != null) session = iwc.getSession();
    }

    return session;
  }
コード例 #9
0
  void addSession(HttpSession session) {
    if (!isManagementOfSessionsTurnedOn()) {
      return;
    }

    String id = session.getId();
    sessions.put(id, session);

    if (getApplication().getSettings().getBoolean("log_session_creation", Boolean.FALSE)) {
      String uri = "unknown";
      try {
        RequestResponseProvider requestProvider =
            ELUtil.getInstance().getBean(RequestResponseProvider.class);
        uri = requestProvider.getRequest().getRequestURI();
      } catch (Exception e) {
      }
      getLogger()
          .info(
              "********************************* HttpSession '"
                  + id
                  + "' created for request: "
                  + uri);
    }
  }
コード例 #10
0
 protected void fireAppStartedEvent() {
   ELUtil.getInstance().publishEvent(new IWMainApplicationStartedEvent(this));
 }
コード例 #11
0
  @SuppressWarnings("unchecked")
  protected void processRequest(HttpServletRequest req, HttpServletResponse resp, boolean isPost)
      throws ServletException, IOException {
    ServerManager manager = getServerManager();
    IWMainApplication iwma = IWMainApplication.getIWMainApplication(req);

    // extract the parameters from the request
    ParameterList requestParameters = new ParameterList(req.getParameterMap());

    OpenIDServerBean serverBean = ELUtil.getInstance().getBean("openIDServerBean");
    ParameterList sessionStoredParameterList = serverBean.getParameterList();
    if (sessionStoredParameterList != null) {
      if (!requestParameters.hasParameter(OpenIDConstants.PARAMETER_OPENID_MODE)) {
        sessionStoredParameterList.addParams(requestParameters);
        requestParameters = sessionStoredParameterList;
      }
    }

    String mode =
        requestParameters.hasParameter(OpenIDConstants.PARAMETER_OPENID_MODE)
            ? requestParameters.getParameterValue(OpenIDConstants.PARAMETER_OPENID_MODE)
            : null;
    String realm =
        requestParameters.hasParameter(OpenIDConstants.PARAMETER_REALM)
            ? requestParameters.getParameterValue(OpenIDConstants.PARAMETER_REALM)
            : null;
    if (realm != null) {
      serverBean.setReturnUrl(realm);
      realm = getRealmName(realm);
      serverBean.setRealm(realm);
    }

    Message response;
    String responseText = null;

    try {
      if (OpenIDConstants.PARAMETER_ASSOCIATE.equals(mode)) {
        // --- process an association request ---
        response = manager.associationResponse(requestParameters);
        responseText = response.keyValueFormEncoding();
      } else if (OpenIDConstants.PARAMETER_CHECKID_SETUP.equals(mode)
          || OpenIDConstants.PARAMETER_CHECKID_IMMEDIATE.equals(mode)) {
        IWContext iwc = new IWContext(req, resp, getServletContext());

        boolean goToLogin = doRedirectToLoginPage(manager, requestParameters, iwc, realm);

        if (!goToLogin) {
          serverBean.setParameterList(null);
          serverBean.setServerUrl(null);
          serverBean.setDoRedirect(null);
          serverBean.setUsername(null);

          // interact with the user and obtain data needed to continue
          User user = iwc.getCurrentUser();
          String userSelectedClaimedId = getUserSelectedClaimedId(iwc, user);

          // --- process an authentication request ---
          AuthRequest authReq =
              AuthRequest.createAuthRequest(requestParameters, manager.getRealmVerifier());

          storeRequestedAttributesToSession(iwc, authReq);

          Boolean authenticatedAndApproved = isAuthenticatedAndApproved(iwc, user, authReq);

          String opLocalId = null;
          // if the user chose a different claimed_id than the one in request
          if (userSelectedClaimedId != null
              && !userSelectedClaimedId.equals(authReq.getClaimed())) {
            opLocalId = userSelectedClaimedId;
          }

          response =
              manager.authResponse(
                  requestParameters,
                  opLocalId,
                  userSelectedClaimedId,
                  authenticatedAndApproved.booleanValue(),
                  false); // Sign after we added extensions.

          if (response instanceof DirectError) {
            directResponse(resp, response.keyValueFormEncoding());
            return;
          } else if (response instanceof AuthFailure) {
            redirectToAuthorisationPage(req, resp, requestParameters, serverBean);
            return;
          } else {
            String[] extensionsToSign = prepareResponse(serverBean, response, iwc, user, authReq);
            boolean signExtensions =
                iwma.getSettings().getBoolean(OpenIDConstants.PROPERTY_SIGN_EXTENSIONS, false);

            AuthSuccess success = (AuthSuccess) response;
            if (signExtensions) {
              success.setSignExtensions(extensionsToSign);
            }

            // Sign the auth success message.
            // This is required as AuthSuccess.buildSignedList has a `todo' tag now.
            manager.sign(success);

            // caller will need to decide which of the following to use:

            // option1: GET HTTP-redirect to the return_to URL
            //		                cleanUpBeforeReturning(iwc, loginExpireHandle);
            // Clean up before returning
            serverBean.invalidate();

            getDAO().createLogEntry(user.getUniqueId(), realm, "");

            resp.sendRedirect(response.getDestinationUrl(true));
            return;

            // option2: HTML FORM Redirection
            // RequestDispatcher dispatcher =
            // getServletContext().getRequestDispatcher("formredirection.jsp");
            // httpReq.setAttribute("parameterMap", response.getParameterMap());
            // httpReq.setAttribute("destinationUrl", response.getDestinationUrl(false));
            // dispatcher.forward(request, response);
            // return null;
          }
        } else {
          redirectToLoginPage(req, resp, requestParameters, serverBean, manager);
          return;
        }
      } else if (OpenIDConstants.PARAMETER_CHECK_AUTHENTICATION.equals(mode)) {
        // --- processing a verification request ---
        response = manager.verify(requestParameters);
        responseText = response.keyValueFormEncoding();
      } else {
        // --- error response ---
        response = DirectError.createDirectError("Unknown request");
        responseText = response.keyValueFormEncoding();
        serverBean.invalidate();
      }
    } catch (MessageException me) {
      me.printStackTrace();
      responseText = me.getMessage();
      serverBean.invalidate();
    } catch (AssociationException ae) {
      ae.printStackTrace();
      responseText = ae.getMessage();
      serverBean.invalidate();
    } catch (ServerException se) {
      se.printStackTrace();
      responseText = se.getMessage();
      serverBean.invalidate();
    }

    // return the result to the user
    directResponse(resp, responseText);
  }
コード例 #12
0
  @SuppressWarnings("unchecked")
  private void storeRequestedAttributesToSession(IWContext iwc, AuthRequest authReq) {
    if (authReq.hasExtension(AxMessage.OPENID_NS_AX)) {
      MessageExtension ext;
      try {
        ext = authReq.getExtension(AxMessage.OPENID_NS_AX);
        if (ext instanceof FetchRequest) {
          FetchRequest fetchReq = (FetchRequest) ext;
          OpenIDServerBean serverBean = ELUtil.getInstance().getBean("openIDServerBean");
          Map<String, String> allAttributes = (Map<String, String>) fetchReq.getAttributes();
          Map<String, String> required = (Map<String, String>) fetchReq.getAttributes(true);

          List<AuthorizedAttribute> allAttributesList = new ArrayList<AuthorizedAttribute>();
          List<AuthorizedAttribute> requiredAttributesList = new ArrayList<AuthorizedAttribute>();
          List<AuthorizedAttribute> optionalAttributesList = new ArrayList<AuthorizedAttribute>();

          String realm = serverBean.getRealm();

          for (String alias : allAttributes.keySet()) {
            ExchangeAttribute attribute =
                getDAO().getExchangeAttribute(alias, allAttributes.get(alias));
            if (attribute != null) {
              User user = iwc.getCurrentUser();
              AuthorizedAttribute aattr =
                  getDAO().getAuthorizedAttributes(user.getUniqueId(), realm, attribute);
              if (aattr == null) {
                aattr = new AuthorizedAttribute();
                aattr.setExchangeAttribute(attribute);
                aattr.setRealm(realm);
                aattr.setUserUUID(user.getUniqueId());
                aattr.setIsAllowed(true);
              }
              allAttributesList.add(aattr);
              if (required.containsKey(alias) && attribute.getType().equals(required.get(alias))) {
                requiredAttributesList.add(aattr);
              } else {
                optionalAttributesList.add(aattr);
              }
            } else {
              LOGGER.warning(
                  "Requesting unknown exchange attribute: "
                      + alias
                      + " : "
                      + allAttributes.get(alias));
              // throw new UnsupportedOperationException("Requesting unknown exchange attribute.");
            }
          }

          serverBean.setRequestedAttributes(allAttributesList);
          serverBean.setRequiredAttributes(requiredAttributesList);
          serverBean.setOptionalAttributes(optionalAttributesList);
          return;
        } else /*if (ext instanceof StoreRequest)*/ {
          // TODO implement?
          throw new UnsupportedOperationException("TODO");
        }
      } catch (MessageException e) {
        e.printStackTrace();
      }
    }
    if (authReq.hasExtension(SRegMessage.OPENID_NS_SREG11)) {
      try {
        MessageExtension ext = authReq.getExtension(SRegMessage.OPENID_NS_SREG11);

        if (ext instanceof SRegRequest) {
          SRegRequest sregReq = (SRegRequest) ext;
          List<String> all = sregReq.getAttributes();
          List<String> required = sregReq.getAttributes(true);
          List<String> optional = sregReq.getAttributes(false);

          List<AuthorizedAttribute> allAttributesList = new ArrayList<AuthorizedAttribute>();
          List<AuthorizedAttribute> requiredAttributesList = new ArrayList<AuthorizedAttribute>();
          List<AuthorizedAttribute> optionalAttributesList = new ArrayList<AuthorizedAttribute>();

          OpenIDServerBean serverBean = ELUtil.getInstance().getBean("openIDServerBean");
          String realm = serverBean.getRealm();
          User user = iwc.getCurrentUser();

          for (String alias : all) {
            ExchangeAttribute attribute = getDAO().getExchangeAttribute(alias);
            if (attribute != null) {
              AuthorizedAttribute aattr =
                  getDAO().getAuthorizedAttributes(user.getUniqueId(), realm, attribute);
              if (aattr == null) {
                aattr = new AuthorizedAttribute();
                aattr.setExchangeAttribute(attribute);
                aattr.setRealm(realm);
                aattr.setUserUUID(user.getUniqueId());
                aattr.setIsAllowed(true);
              }
              allAttributesList.add(aattr);
              if (required.contains(alias)) {
                requiredAttributesList.add(aattr);
              }
              if (optional.contains(alias)) {
                optionalAttributesList.add(aattr);
              }
            }
          }

          serverBean.setRequestedAttributes(allAttributesList);
          serverBean.setRequiredAttributes(requiredAttributesList);
          serverBean.setOptionalAttributes(optionalAttributesList);
          return;
        }
      } catch (MessageException e) {
        e.printStackTrace();
      }
    }
  }
コード例 #13
0
  @SuppressWarnings("unchecked")
  @Override
  protected void initializeComponent(FacesContext context) {
    ELUtil.getInstance().autowire(this);
    iwc = IWContext.getIWContext(context);
    if (!iwc.isLoggedOn()) {
      return;
    }
    if (userId == null) {
      userId = iwc.getCurrentUserId();
    }

    //        HtmlTag div = new
    // HtmlTag();//(HtmlTag)context.getApplication().createComponent(HtmlTag.COMPONENT_TYPE);
    //        getChildren().add(div);
    //        div.setValue(divTag);
    Layer main = new Layer();
    this.add(main);

    IWBundle bundle = getBundle(context, IWBundleStarter.IW_BUNDLE_IDENTIFIER);
    iwrb = bundle.getResourceBundle(iwc);

    if (groupId == null) {
      Label label = new Label();
      main.add(label);
      label.addText(iwrb.getLocalizedString("no_group_set", "No group set"));
      return;
    }

    Group group = null;
    Collection<Group> groups = null;
    try {
      group = this.getUserBusiness().getGroupBusiness().getGroupByGroupID(Integer.valueOf(groupId));
      groups = this.getUserBusiness().getUserGroups(userId);
    } catch (Exception e) {
      Logger.getLogger(this.getClass().getName())
          .log(Level.WARNING, "failed getting groups by ids", e);
    }

    GenericButton joinButton = new GenericButton();
    main.add(joinButton);
    GenericButton leaveButton = new GenericButton();
    main.add(leaveButton);

    StringBuilder parameters =
        new StringBuilder()
            .append(this.userId)
            .append(CoreConstants.JS_STR_PARAM_SEPARATOR)
            .append(this.groupId)
            .append("','#")
            .append(joinButton.getId())
            .append("','#")
            .append(leaveButton.getId())
            .append(CoreConstants.JS_STR_PARAM_END);

    joinButton.setValue(iwrb.getLocalizedString("join", "Join"));
    String action =
        new StringBuilder("GroupJoinerHelper.joinGroup('").append(parameters).toString();
    joinButton.setOnClick(action);
    leaveButton.setValue(iwrb.getLocalizedString("leave", "Leave"));
    action = new StringBuilder("GroupJoinerHelper.leaveGroup('").append(parameters).toString();
    leaveButton.setOnClick(action);

    if (groups.contains(group)) {
      joinButton.setStyleAttribute("display : none;");
    } else {
      leaveButton.setStyleAttribute("display : none;");
    }

    addActions(main);
  }
コード例 #14
0
 JackrabbitSecurityHelper getSecurityHelper() {
   if (securityHelper == null) {
     ELUtil.getInstance().autowire(this);
   }
   return securityHelper;
 }