Search in sources :

Example 46 with Security

use of org.apache.ofbiz.security.Security in project ofbiz-framework by apache.

the class LoginWorker method setWebContextObjects.

protected static void setWebContextObjects(HttpServletRequest request, HttpServletResponse response, Delegator delegator, LocalDispatcher dispatcher) {
    HttpSession session = request.getSession();
    // NOTE: we do NOT want to set this in the servletContext, only in the request and session
    // We also need to setup the security objects since they are dependent on the delegator
    Security security = null;
    try {
        security = SecurityFactory.getInstance(delegator);
    } catch (SecurityConfigurationException e) {
        Debug.logError(e, module);
    }
    request.setAttribute("delegator", delegator);
    request.setAttribute("dispatcher", dispatcher);
    request.setAttribute("security", security);
    session.setAttribute("delegatorName", delegator.getDelegatorName());
    session.setAttribute("delegator", delegator);
    session.setAttribute("dispatcher", dispatcher);
    session.setAttribute("security", security);
    // get rid of the visit info since it was pointing to the previous database, and get a new one
    session.removeAttribute("visitor");
    session.removeAttribute("visit");
    VisitHandler.getVisitor(request, response);
    VisitHandler.getVisit(session);
}
Also used : SecurityConfigurationException(org.apache.ofbiz.security.SecurityConfigurationException) HttpSession(javax.servlet.http.HttpSession) Security(org.apache.ofbiz.security.Security)

Example 47 with Security

use of org.apache.ofbiz.security.Security in project ofbiz-framework by apache.

the class LoginWorker method hasBasePermission.

public static boolean hasBasePermission(GenericValue userLogin, HttpServletRequest request) {
    Security security = (Security) request.getAttribute("security");
    if (security != null) {
        ServletContext context = request.getServletContext();
        String serverId = (String) context.getAttribute("_serverId");
        // get a context path from the request, if it is empty then assume it is the root mount point
        String contextPath = request.getContextPath();
        if (UtilValidate.isEmpty(contextPath)) {
            contextPath = "/";
        }
        ComponentConfig.WebappInfo info = ComponentConfig.getWebAppInfo(serverId, contextPath);
        if (info != null) {
            return hasApplicationPermission(info, security, userLogin);
        } else {
            if (Debug.infoOn()) {
                Debug.logInfo("No webapp configuration found for : " + serverId + " / " + contextPath, module);
            }
        }
    } else {
        if (Debug.warningOn()) {
            Debug.logWarning("Received a null Security object from HttpServletRequest", module);
        }
    }
    return true;
}
Also used : WebappInfo(org.apache.ofbiz.base.component.ComponentConfig.WebappInfo) ComponentConfig(org.apache.ofbiz.base.component.ComponentConfig) ServletContext(javax.servlet.ServletContext) Security(org.apache.ofbiz.security.Security)

Example 48 with Security

use of org.apache.ofbiz.security.Security in project ofbiz-framework by apache.

the class ContextFilter method doFilter.

/**
 * @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest, javax.servlet.ServletResponse, javax.servlet.FilterChain)
 */
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
    HttpServletRequest httpRequest = (HttpServletRequest) request;
    HttpServletResponse httpResponse = (HttpServletResponse) response;
    // ----- Servlet Object Setup -----
    // set the ServletContext in the request for future use
    httpRequest.setAttribute("servletContext", config.getServletContext());
    // set the webSiteId in the session
    if (UtilValidate.isEmpty(httpRequest.getSession().getAttribute("webSiteId"))) {
        httpRequest.getSession().setAttribute("webSiteId", WebSiteWorker.getWebSiteId(httpRequest));
    }
    // set the filesystem path of context root.
    httpRequest.setAttribute("_CONTEXT_ROOT_", config.getServletContext().getRealPath("/"));
    // set the server root url
    httpRequest.setAttribute("_SERVER_ROOT_URL_", UtilHttp.getServerRootUrl(httpRequest));
    if (request.getCharacterEncoding() == null) {
        request.setCharacterEncoding(defaultCharacterEncoding);
    }
    WebAppUtil.setAttributesFromRequestBody(request);
    request.setAttribute("delegator", config.getServletContext().getAttribute("delegator"));
    request.setAttribute("dispatcher", config.getServletContext().getAttribute("dispatcher"));
    request.setAttribute("security", config.getServletContext().getAttribute("security"));
    if (isMultitenant) {
        // get tenant delegator by domain name
        String serverName = httpRequest.getServerName();
        try {
            // if tenant was specified, replace delegator with the new per-tenant delegator and set tenantId to session attribute
            Delegator delegator = WebAppUtil.getDelegator(config.getServletContext());
            // Use base delegator for fetching data from entity of entityGroup org.apache.ofbiz.tenant
            Delegator baseDelegator = DelegatorFactory.getDelegator(delegator.getDelegatorBaseName());
            GenericValue tenantDomainName = EntityQuery.use(baseDelegator).from("TenantDomainName").where("domainName", serverName).queryOne();
            String tenantId = null;
            if (UtilValidate.isNotEmpty(tenantDomainName)) {
                tenantId = tenantDomainName.getString("tenantId");
            }
            if (UtilValidate.isEmpty(tenantId)) {
                tenantId = (String) httpRequest.getAttribute("userTenantId");
            }
            if (UtilValidate.isEmpty(tenantId)) {
                tenantId = httpRequest.getParameter("userTenantId");
            }
            if (UtilValidate.isNotEmpty(tenantId)) {
                // if the request path is a root mount then redirect to the initial path
                if ("".equals(httpRequest.getContextPath()) && "".equals(httpRequest.getServletPath())) {
                    GenericValue tenant = EntityQuery.use(baseDelegator).from("Tenant").where("tenantId", tenantId).queryOne();
                    String initialPath = tenant.getString("initialPath");
                    if (UtilValidate.isNotEmpty(initialPath) && !"/".equals(initialPath)) {
                        ((HttpServletResponse) response).sendRedirect(initialPath);
                        return;
                    }
                }
                // make that tenant active, setup a new delegator and a new dispatcher
                String tenantDelegatorName = delegator.getDelegatorBaseName() + "#" + tenantId;
                httpRequest.getSession().setAttribute("delegatorName", tenantDelegatorName);
                // after this line the delegator is replaced with the new per-tenant delegator
                delegator = DelegatorFactory.getDelegator(tenantDelegatorName);
                config.getServletContext().setAttribute("delegator", delegator);
                // clear web context objects
                config.getServletContext().setAttribute("security", null);
                config.getServletContext().setAttribute("dispatcher", null);
                // initialize security
                Security security = WebAppUtil.getSecurity(config.getServletContext());
                // initialize the services dispatcher
                LocalDispatcher dispatcher = WebAppUtil.getDispatcher(config.getServletContext());
                // set web context objects
                request.setAttribute("delegator", delegator);
                request.setAttribute("dispatcher", dispatcher);
                request.setAttribute("security", security);
                request.setAttribute("userTenantId", tenantId);
            }
        // NOTE DEJ20101130: do NOT always put the delegator name in the user's session because the user may
        // have logged in and specified a tenant, and even if no Tenant record with a matching domainName field
        // is found this will change the user's delegator back to the base one instead of the one for the
        // tenant specified on login
        // httpRequest.getSession().setAttribute("delegatorName", delegator.getDelegatorName());
        } catch (GenericEntityException e) {
            Debug.logWarning(e, "Unable to get Tenant", module);
        }
    }
    // we're done checking; continue on
    chain.doFilter(request, httpResponse);
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) GenericValue(org.apache.ofbiz.entity.GenericValue) LocalDispatcher(org.apache.ofbiz.service.LocalDispatcher) Delegator(org.apache.ofbiz.entity.Delegator) GenericEntityException(org.apache.ofbiz.entity.GenericEntityException) HttpServletResponse(javax.servlet.http.HttpServletResponse) Security(org.apache.ofbiz.security.Security)

Example 49 with Security

use of org.apache.ofbiz.security.Security in project ofbiz-framework by apache.

the class WebAppUtil method getSecurity.

public static Security getSecurity(ServletContext servletContext) {
    Security security = (Security) servletContext.getAttribute("security");
    if (security == null) {
        Delegator delegator = (Delegator) servletContext.getAttribute("delegator");
        if (delegator != null) {
            try {
                security = SecurityFactory.getInstance(delegator);
            } catch (SecurityConfigurationException e) {
                Debug.logError(e, "Unable to obtain an instance of the security object.", module);
            }
        }
        servletContext.setAttribute("security", security);
        if (security == null) {
            Debug.logError("An invalid (null) Security object has been set in the servlet context.", module);
        }
    }
    return security;
}
Also used : Delegator(org.apache.ofbiz.entity.Delegator) SecurityConfigurationException(org.apache.ofbiz.security.SecurityConfigurationException) Security(org.apache.ofbiz.security.Security)

Example 50 with Security

use of org.apache.ofbiz.security.Security in project ofbiz-framework by apache.

the class ProductEvents method updateProductAssoc.

/**
 * Updates ProductAssoc information according to UPDATE_MODE parameter
 *
 * @param request The HTTPRequest object for the current request
 * @param response The HTTPResponse object for the current request
 * @return String specifying the exit status of this event
 */
public static String updateProductAssoc(HttpServletRequest request, HttpServletResponse response) {
    String errMsg = "";
    List<Object> errMsgList = new LinkedList<>();
    Delegator delegator = (Delegator) request.getAttribute("delegator");
    Security security = (Security) request.getAttribute("security");
    String updateMode = request.getParameter("UPDATE_MODE");
    if (UtilValidate.isEmpty(updateMode)) {
        errMsg = UtilProperties.getMessage(resource, "productevents.updatemode_not_specified", UtilHttp.getLocale(request));
        request.setAttribute("_ERROR_MESSAGE_", errMsg);
        Debug.logWarning("[ProductEvents.updateProductAssoc] Update Mode was not specified, but is required", module);
        return "error";
    }
    // check permissions before moving on...
    if (!security.hasEntityPermission("CATALOG", "_" + updateMode, request.getSession())) {
        Map<String, String> messageMap = UtilMisc.toMap("updateMode", updateMode);
        errMsg = UtilProperties.getMessage(resource, "productevents.not_sufficient_permissions", messageMap, UtilHttp.getLocale(request));
        request.setAttribute("_ERROR_MESSAGE_", errMsg);
        return "error";
    }
    String productId = request.getParameter("PRODUCT_ID");
    String productIdTo = request.getParameter("PRODUCT_ID_TO");
    String productAssocTypeId = request.getParameter("PRODUCT_ASSOC_TYPE_ID");
    String fromDateStr = request.getParameter("FROM_DATE");
    Timestamp fromDate = null;
    try {
        if (EntityQuery.use(delegator).from("Product").where("productId", productId).queryOne() == null) {
            Map<String, String> messageMap = UtilMisc.toMap("productId", productId);
            errMsgList.add(UtilProperties.getMessage(resource, "productevents.product_with_id_not_found", messageMap, UtilHttp.getLocale(request)));
        }
        if (EntityQuery.use(delegator).from("Product").where("productId", productIdTo).queryOne() == null) {
            Map<String, String> messageMap = UtilMisc.toMap("productIdTo", productIdTo);
            errMsgList.add(UtilProperties.getMessage(resource, "productevents.product_To_with_id_not_found", messageMap, UtilHttp.getLocale(request)));
        }
    } catch (GenericEntityException e) {
        // if there is an exception for either, the other probably wont work
        Debug.logWarning(e, module);
    }
    if (UtilValidate.isNotEmpty(fromDateStr)) {
        try {
            fromDate = (Timestamp) ObjectType.simpleTypeConvert(fromDateStr, "Timestamp", null, UtilHttp.getTimeZone(request), UtilHttp.getLocale(request), false);
        } catch (Exception e) {
            errMsgList.add("From Date not formatted correctly.");
        }
    }
    if (UtilValidate.isEmpty(productId)) {
        errMsgList.add(UtilProperties.getMessage(resource, "productevents.product_ID_missing", UtilHttp.getLocale(request)));
    }
    if (UtilValidate.isEmpty(productIdTo)) {
        errMsgList.add(UtilProperties.getMessage(resource, "productevents.product_ID_To_missing", UtilHttp.getLocale(request)));
    }
    if (UtilValidate.isEmpty(productAssocTypeId)) {
        errMsgList.add(UtilProperties.getMessage(resource, "productevents.association_type_ID_missing", UtilHttp.getLocale(request)));
    }
    // from date is only required if update mode is not CREATE
    if (!"CREATE".equals(updateMode) && UtilValidate.isEmpty(fromDateStr)) {
        errMsgList.add(UtilProperties.getMessage(resource, "productevents.from_date_missing", UtilHttp.getLocale(request)));
    }
    if (errMsgList.size() > 0) {
        request.setAttribute("_ERROR_MESSAGE_LIST_", errMsgList);
        return "error";
    }
    // clear some cache entries
    delegator.clearCacheLine("ProductAssoc", UtilMisc.toMap("productId", productId));
    delegator.clearCacheLine("ProductAssoc", UtilMisc.toMap("productId", productId, "productAssocTypeId", productAssocTypeId));
    delegator.clearCacheLine("ProductAssoc", UtilMisc.toMap("productIdTo", productIdTo));
    delegator.clearCacheLine("ProductAssoc", UtilMisc.toMap("productIdTo", productIdTo, "productAssocTypeId", productAssocTypeId));
    delegator.clearCacheLine("ProductAssoc", UtilMisc.toMap("productAssocTypeId", productAssocTypeId));
    delegator.clearCacheLine("ProductAssoc", UtilMisc.toMap("productId", productId, "productIdTo", productIdTo, "productAssocTypeId", productAssocTypeId, "fromDate", fromDate));
    GenericValue tempProductAssoc = delegator.makeValue("ProductAssoc", UtilMisc.toMap("productId", productId, "productIdTo", productIdTo, "productAssocTypeId", productAssocTypeId, "fromDate", fromDate));
    if ("DELETE".equals(updateMode)) {
        GenericValue productAssoc = null;
        try {
            productAssoc = EntityQuery.use(delegator).from(tempProductAssoc.getEntityName()).where(tempProductAssoc.getPrimaryKey()).queryOne();
        } catch (GenericEntityException e) {
            Debug.logWarning(e.getMessage(), module);
            productAssoc = null;
        }
        if (productAssoc == null) {
            errMsg = UtilProperties.getMessage(resource, "productevents.could_not_remove_product_association_exist", UtilHttp.getLocale(request));
            request.setAttribute("_ERROR_MESSAGE_", errMsg);
            return "error";
        }
        try {
            productAssoc.remove();
        } catch (GenericEntityException e) {
            errMsg = UtilProperties.getMessage(resource, "productevents.could_not_remove_product_association_write", UtilHttp.getLocale(request));
            request.setAttribute("_ERROR_MESSAGE_", errMsg);
            Debug.logWarning("[ProductEvents.updateProductAssoc] Could not remove product association (write error); message: " + e.getMessage(), module);
            return "error";
        }
        return "success";
    }
    String thruDateStr = request.getParameter("THRU_DATE");
    String reason = request.getParameter("REASON");
    String instruction = request.getParameter("INSTRUCTION");
    String quantityStr = request.getParameter("QUANTITY");
    String sequenceNumStr = request.getParameter("SEQUENCE_NUM");
    Timestamp thruDate = null;
    BigDecimal quantity = null;
    Long sequenceNum = null;
    if (UtilValidate.isNotEmpty(thruDateStr)) {
        try {
            thruDate = (Timestamp) ObjectType.simpleTypeConvert(thruDateStr, "Timestamp", null, UtilHttp.getTimeZone(request), UtilHttp.getLocale(request), false);
        } catch (Exception e) {
            errMsgList.add(UtilProperties.getMessage(resource, "productevents.thru_date_not_formatted_correctly", UtilHttp.getLocale(request)));
        }
    }
    if (UtilValidate.isNotEmpty(quantityStr)) {
        try {
            quantity = new BigDecimal(quantityStr);
        } catch (NumberFormatException e) {
            errMsgList.add(UtilProperties.getMessage(resource, "productevents.quantity_not_formatted_correctly", UtilHttp.getLocale(request)));
        }
    }
    if (UtilValidate.isNotEmpty(sequenceNumStr)) {
        try {
            sequenceNum = Long.valueOf(sequenceNumStr);
        } catch (Exception e) {
            errMsgList.add(UtilProperties.getMessage(resource, "productevents.sequenceNum_not_formatted_correctly", UtilHttp.getLocale(request)));
        }
    }
    if (errMsgList.size() > 0) {
        request.setAttribute("_ERROR_MESSAGE_LIST_", errMsgList);
        return "error";
    }
    tempProductAssoc.set("thruDate", thruDate);
    tempProductAssoc.set("reason", reason);
    tempProductAssoc.set("instruction", instruction);
    tempProductAssoc.set("quantity", quantity);
    tempProductAssoc.set("sequenceNum", sequenceNum);
    if ("CREATE".equals(updateMode)) {
        // if no from date specified, set to now
        if (fromDate == null) {
            fromDate = new Timestamp(new java.util.Date().getTime());
            tempProductAssoc.set("fromDate", fromDate);
            request.setAttribute("ProductAssocCreateFromDate", fromDate);
        }
        GenericValue productAssoc = null;
        try {
            productAssoc = EntityQuery.use(delegator).from(tempProductAssoc.getEntityName()).where(tempProductAssoc.getPrimaryKey()).queryOne();
        } catch (GenericEntityException e) {
            Debug.logWarning(e.getMessage(), module);
            productAssoc = null;
        }
        if (productAssoc != null) {
            errMsg = UtilProperties.getMessage(resource, "productevents.could_not_create_product_association_exists", UtilHttp.getLocale(request));
            request.setAttribute("_ERROR_MESSAGE_", errMsg);
            return "error";
        }
        try {
            productAssoc = tempProductAssoc.create();
        } catch (GenericEntityException e) {
            errMsg = UtilProperties.getMessage(resource, "productevents.could_not_create_product_association_write", UtilHttp.getLocale(request));
            request.setAttribute("_ERROR_MESSAGE_", errMsg);
            Debug.logWarning("[ProductEvents.updateProductAssoc] Could not create product association (write error); message: " + e.getMessage(), module);
            return "error";
        }
    } else if ("UPDATE".equals(updateMode)) {
        try {
            tempProductAssoc.store();
        } catch (GenericEntityException e) {
            errMsg = UtilProperties.getMessage(resource, "productevents.could_not_update_product_association_write", UtilHttp.getLocale(request));
            request.setAttribute("_ERROR_MESSAGE_", errMsg);
            Debug.logWarning("[ProductEvents.updateProductAssoc] Could not update product association (write error); message: " + e.getMessage(), module);
            return "error";
        }
    } else {
        Map<String, String> messageMap = UtilMisc.toMap("updateMode", updateMode);
        errMsg = UtilProperties.getMessage(resource, "productevents.specified_update_mode_not_supported", messageMap, UtilHttp.getLocale(request));
        request.setAttribute("_ERROR_MESSAGE_", errMsg);
        return "error";
    }
    return "success";
}
Also used : GenericValue(org.apache.ofbiz.entity.GenericValue) Security(org.apache.ofbiz.security.Security) Timestamp(java.sql.Timestamp) LinkedList(java.util.LinkedList) GenericServiceException(org.apache.ofbiz.service.GenericServiceException) GenericTransactionException(org.apache.ofbiz.entity.transaction.GenericTransactionException) GenericEntityException(org.apache.ofbiz.entity.GenericEntityException) BigDecimal(java.math.BigDecimal) Delegator(org.apache.ofbiz.entity.Delegator) GenericEntityException(org.apache.ofbiz.entity.GenericEntityException) HashMap(java.util.HashMap) Map(java.util.Map)

Aggregations

Security (org.apache.ofbiz.security.Security)79 GenericValue (org.apache.ofbiz.entity.GenericValue)69 Delegator (org.apache.ofbiz.entity.Delegator)60 Locale (java.util.Locale)56 GenericEntityException (org.apache.ofbiz.entity.GenericEntityException)54 HashMap (java.util.HashMap)36 Timestamp (java.sql.Timestamp)27 LinkedList (java.util.LinkedList)27 LocalDispatcher (org.apache.ofbiz.service.LocalDispatcher)20 GenericServiceException (org.apache.ofbiz.service.GenericServiceException)18 Map (java.util.Map)12 HttpSession (javax.servlet.http.HttpSession)7 GeneralException (org.apache.ofbiz.base.util.GeneralException)7 BigDecimal (java.math.BigDecimal)6 List (java.util.List)5 IOException (java.io.IOException)4 ArrayList (java.util.ArrayList)4 Date (java.util.Date)4 GenericTransactionException (org.apache.ofbiz.entity.transaction.GenericTransactionException)4 File (java.io.File)3