Search in sources :

Example 56 with GeneralException

use of org.apache.ofbiz.base.util.GeneralException in project ofbiz-framework by apache.

the class LoginWorker method login.

/**
 * An HTTP WebEvent handler that logs in a userLogin. This should run before the security check.
 *
 * @param request The HTTP request object for the current JSP or Servlet request.
 * @param response The HTTP response object for the current JSP or Servlet request.
 * @return Return a boolean which specifies whether or not the calling Servlet or
 *         JSP should generate its own content. This allows an event to override the default content.
 */
public static String login(HttpServletRequest request, HttpServletResponse response) {
    HttpSession session = request.getSession();
    Delegator delegator = (Delegator) request.getAttribute("delegator");
    String username = request.getParameter("USERNAME");
    String password = request.getParameter("PASSWORD");
    String forgotPwdFlag = request.getParameter("forgotPwdFlag");
    // password decryption
    EntityCrypto entityDeCrypto = null;
    try {
        entityDeCrypto = new EntityCrypto(delegator, null);
    } catch (EntityCryptoException e1) {
        Debug.logError(e1.getMessage(), module);
    }
    if (entityDeCrypto != null && "true".equals(forgotPwdFlag)) {
        try {
            Object decryptedPwd = entityDeCrypto.decrypt(keyValue, ModelField.EncryptMethod.TRUE, password);
            password = decryptedPwd.toString();
        } catch (GeneralException e) {
            Debug.logError(e, "Current Password Decryption failed", module);
        }
    }
    if (username == null)
        username = (String) session.getAttribute("USERNAME");
    if (password == null)
        password = (String) session.getAttribute("PASSWORD");
    // allow a username and/or password in a request attribute to override the request parameter or the session attribute; this way a preprocessor can play with these a bit...
    if (UtilValidate.isNotEmpty(request.getAttribute("USERNAME"))) {
        username = (String) request.getAttribute("USERNAME");
    }
    if (UtilValidate.isNotEmpty(request.getAttribute("PASSWORD"))) {
        password = (String) request.getAttribute("PASSWORD");
    }
    List<String> unpwErrMsgList = new LinkedList<String>();
    if (UtilValidate.isEmpty(username)) {
        unpwErrMsgList.add(UtilProperties.getMessage(resourceWebapp, "loginevents.username_was_empty_reenter", UtilHttp.getLocale(request)));
    }
    if (UtilValidate.isEmpty(password)) {
        unpwErrMsgList.add(UtilProperties.getMessage(resourceWebapp, "loginevents.password_was_empty_reenter", UtilHttp.getLocale(request)));
    }
    boolean requirePasswordChange = "Y".equals(request.getParameter("requirePasswordChange"));
    if (!unpwErrMsgList.isEmpty()) {
        request.setAttribute("_ERROR_MESSAGE_LIST_", unpwErrMsgList);
        return requirePasswordChange ? "requirePasswordChange" : "error";
    }
    boolean setupNewDelegatorEtc = false;
    LocalDispatcher dispatcher = (LocalDispatcher) request.getAttribute("dispatcher");
    ServletContext servletContext = session.getServletContext();
    // if a tenantId was passed in, see if the userLoginId is associated with that tenantId (can use any delegator for this, entity is not tenant-specific)
    String tenantId = request.getParameter("userTenantId");
    if (UtilValidate.isEmpty(tenantId)) {
        tenantId = (String) request.getAttribute("userTenantId");
    }
    if (UtilValidate.isNotEmpty(tenantId)) {
        // see if we need to activate a tenant delegator, only do if the current delegatorName has a hash symbol in it, and if the passed in tenantId doesn't match the one in the delegatorName
        String oldDelegatorName = delegator.getDelegatorName();
        int delegatorNameHashIndex = oldDelegatorName.indexOf('#');
        String currentDelegatorTenantId = null;
        if (delegatorNameHashIndex > 0) {
            currentDelegatorTenantId = oldDelegatorName.substring(delegatorNameHashIndex + 1);
            if (currentDelegatorTenantId != null)
                currentDelegatorTenantId = currentDelegatorTenantId.trim();
        }
        if (delegatorNameHashIndex == -1 || (currentDelegatorTenantId != null && !tenantId.equals(currentDelegatorTenantId))) {
            // make that tenant active, setup a new delegator and a new dispatcher
            String delegatorName = delegator.getDelegatorBaseName() + "#" + tenantId;
            try {
                // after this line the delegator is replaced with the new per-tenant delegator
                delegator = DelegatorFactory.getDelegator(delegatorName);
                dispatcher = WebAppUtil.makeWebappDispatcher(servletContext, delegator);
            } catch (NullPointerException e) {
                Debug.logError(e, "Error getting tenant delegator", module);
                Map<String, String> messageMap = UtilMisc.toMap("errorMessage", "Tenant [" + tenantId + "]  not found...");
                String errMsg = UtilProperties.getMessage(resourceWebapp, "loginevents.following_error_occurred_during_login", messageMap, UtilHttp.getLocale(request));
                request.setAttribute("_ERROR_MESSAGE_", errMsg);
                return "error";
            }
            // NOTE: these will be local for now and set in the request and session later, after we've verified that the user
            setupNewDelegatorEtc = true;
        }
    } else {
        // Set default delegator
        if (Debug.infoOn()) {
            Debug.logInfo("Setting default delegator", module);
        }
        String delegatorName = delegator.getDelegatorBaseName();
        try {
            // after this line the delegator is replaced with default delegator
            delegator = DelegatorFactory.getDelegator(delegatorName);
            dispatcher = WebAppUtil.makeWebappDispatcher(servletContext, delegator);
        } catch (NullPointerException e) {
            Debug.logError(e, "Error getting default delegator", module);
            Map<String, String> messageMap = UtilMisc.toMap("errorMessage", "Error getting default delegator");
            String errMsg = UtilProperties.getMessage(resourceWebapp, "loginevents.following_error_occurred_during_login", messageMap, UtilHttp.getLocale(request));
            request.setAttribute("_ERROR_MESSAGE_", errMsg);
            return "error";
        }
        setupNewDelegatorEtc = true;
    }
    Map<String, Object> result = null;
    try {
        // get the visit id to pass to the userLogin for history
        String visitId = VisitHandler.getVisitId(session);
        result = dispatcher.runSync("userLogin", UtilMisc.toMap("login.username", username, "login.password", password, "visitId", visitId, "locale", UtilHttp.getLocale(request), "request", request));
    } catch (GenericServiceException e) {
        Debug.logError(e, "Error calling userLogin service", module);
        Map<String, String> messageMap = UtilMisc.toMap("errorMessage", e.getMessage());
        String errMsg = UtilProperties.getMessage(resourceWebapp, "loginevents.following_error_occurred_during_login", messageMap, UtilHttp.getLocale(request));
        request.setAttribute("_ERROR_MESSAGE_", errMsg);
        return "error";
    }
    if (ModelService.RESPOND_SUCCESS.equals(result.get(ModelService.RESPONSE_MESSAGE))) {
        GenericValue userLogin = (GenericValue) result.get("userLogin");
        if (requirePasswordChange) {
            Map<String, Object> inMap = UtilMisc.<String, Object>toMap("login.username", username, "login.password", password, "locale", UtilHttp.getLocale(request));
            inMap.put("userLoginId", username);
            inMap.put("currentPassword", password);
            inMap.put("newPassword", request.getParameter("newPassword"));
            inMap.put("newPasswordVerify", request.getParameter("newPasswordVerify"));
            Map<String, Object> resultPasswordChange = null;
            try {
                resultPasswordChange = dispatcher.runSync("updatePassword", inMap);
            } catch (GenericServiceException e) {
                Debug.logError(e, "Error calling updatePassword service", module);
                Map<String, String> messageMap = UtilMisc.toMap("errorMessage", e.getMessage());
                String errMsg = UtilProperties.getMessage(resourceWebapp, "loginevents.following_error_occurred_during_login", messageMap, UtilHttp.getLocale(request));
                request.setAttribute("_ERROR_MESSAGE_", errMsg);
                return "requirePasswordChange";
            }
            if (ServiceUtil.isError(resultPasswordChange)) {
                String errorMessage = (String) resultPasswordChange.get(ModelService.ERROR_MESSAGE);
                if (UtilValidate.isNotEmpty(errorMessage)) {
                    Map<String, String> messageMap = UtilMisc.toMap("errorMessage", errorMessage);
                    String errMsg = UtilProperties.getMessage(resourceWebapp, "loginevents.following_error_occurred_during_login", messageMap, UtilHttp.getLocale(request));
                    request.setAttribute("_ERROR_MESSAGE_", errMsg);
                }
                request.setAttribute("_ERROR_MESSAGE_LIST_", resultPasswordChange.get(ModelService.ERROR_MESSAGE_LIST));
                return "requirePasswordChange";
            } else {
                try {
                    userLogin.refresh();
                } catch (GenericEntityException e) {
                    Debug.logError(e, "Error refreshing userLogin value", module);
                    Map<String, String> messageMap = UtilMisc.toMap("errorMessage", e.getMessage());
                    String errMsg = UtilProperties.getMessage(resourceWebapp, "loginevents.following_error_occurred_during_login", messageMap, UtilHttp.getLocale(request));
                    request.setAttribute("_ERROR_MESSAGE_", errMsg);
                    return "requirePasswordChange";
                }
            }
        }
        if (setupNewDelegatorEtc) {
            // now set the delegator and dispatcher in a bunch of places just in case they were changed
            setWebContextObjects(request, response, delegator, dispatcher);
        }
        // check to see if a password change is required for the user
        Map<String, Object> userLoginSession = checkMap(result.get("userLoginSession"), String.class, Object.class);
        if (userLogin != null && "Y".equals(userLogin.getString("requirePasswordChange"))) {
            return "requirePasswordChange";
        }
        String autoChangePassword = EntityUtilProperties.getPropertyValue("security", "user.auto.change.password.enable", "false", delegator);
        if ("true".equalsIgnoreCase(autoChangePassword)) {
            if ("requirePasswordChange".equals(autoChangePassword(request, response))) {
                return "requirePasswordChange";
            }
        }
        // check on JavaScriptEnabled
        String javaScriptEnabled = "N";
        if ("Y".equals(request.getParameter("JavaScriptEnabled"))) {
            javaScriptEnabled = "Y";
        }
        try {
            result = dispatcher.runSync("setUserPreference", UtilMisc.toMap("userPrefTypeId", "javaScriptEnabled", "userPrefGroupTypeId", "GLOBAL_PREFERENCES", "userPrefValue", javaScriptEnabled, "userLogin", userLogin));
        } catch (GenericServiceException e) {
            Debug.logError(e, "Error setting user preference", module);
        }
        // start with a clean state, in case the user has quit the session w/o login out
        autoLogoutCleanCookies(userLogin, request, response);
        // finally do the main login routine to set everything else up in the session, etc
        return doMainLogin(request, response, userLogin, userLoginSession);
    } else {
        Map<String, String> messageMap = UtilMisc.toMap("errorMessage", (String) result.get(ModelService.ERROR_MESSAGE));
        String errMsg = UtilProperties.getMessage(resourceWebapp, "loginevents.following_error_occurred_during_login", messageMap, UtilHttp.getLocale(request));
        request.setAttribute("_ERROR_MESSAGE_", errMsg);
        return requirePasswordChange ? "requirePasswordChange" : "error";
    }
}
Also used : EntityCryptoException(org.apache.ofbiz.entity.EntityCryptoException) GenericValue(org.apache.ofbiz.entity.GenericValue) LocalDispatcher(org.apache.ofbiz.service.LocalDispatcher) GeneralException(org.apache.ofbiz.base.util.GeneralException) HttpSession(javax.servlet.http.HttpSession) EntityCrypto(org.apache.ofbiz.entity.util.EntityCrypto) LinkedList(java.util.LinkedList) Delegator(org.apache.ofbiz.entity.Delegator) GenericEntityException(org.apache.ofbiz.entity.GenericEntityException) ServletContext(javax.servlet.ServletContext) GenericServiceException(org.apache.ofbiz.service.GenericServiceException) UtilGenerics.checkMap(org.apache.ofbiz.base.util.UtilGenerics.checkMap) Map(java.util.Map)

Example 57 with GeneralException

use of org.apache.ofbiz.base.util.GeneralException in project ofbiz-framework by apache.

the class LoginWorker method loginUserWithUserLoginId.

/**
 * This method will log in a user with only their username (userLoginId).
 * @param request
 * @param response
 * @param userLoginId
 * @return Returns "success" if user could be logged in or "error" if there was a problem.
 */
public static String loginUserWithUserLoginId(HttpServletRequest request, HttpServletResponse response, String userLoginId) {
    Delegator delegator = (Delegator) request.getAttribute("delegator");
    try {
        GenericValue userLogin = EntityQuery.use(delegator).from("UserLogin").where("userLoginId", userLoginId).queryOne();
        if (userLogin != null) {
            String enabled = userLogin.getString("enabled");
            if (enabled == null || "Y".equals(enabled)) {
                userLogin.set("hasLoggedOut", "N");
                userLogin.store();
                // login the user
                Map<String, Object> ulSessionMap = LoginWorker.getUserLoginSession(userLogin);
                // doing the main login
                return doMainLogin(request, response, userLogin, ulSessionMap);
            }
        }
    } catch (GeneralException e) {
        Debug.logError(e, module);
    }
    // Shouldn't be here if all went well
    return "error";
}
Also used : GenericValue(org.apache.ofbiz.entity.GenericValue) GeneralException(org.apache.ofbiz.base.util.GeneralException) Delegator(org.apache.ofbiz.entity.Delegator)

Example 58 with GeneralException

use of org.apache.ofbiz.base.util.GeneralException in project ofbiz-framework by apache.

the class LoginWorker method check509CertLogin.

// preprocessor method to login a user w/ client certificate see security.properties to configure the pattern of CN
public static String check509CertLogin(HttpServletRequest request, HttpServletResponse response) {
    Delegator delegator = (Delegator) request.getAttribute("delegator");
    boolean doCheck = "true".equalsIgnoreCase(EntityUtilProperties.getPropertyValue("security", "security.login.cert.allow", "true", delegator));
    if (doCheck) {
        HttpSession session = request.getSession();
        GenericValue currentUserLogin = (GenericValue) session.getAttribute("userLogin");
        if (currentUserLogin != null) {
            String hasLoggedOut = currentUserLogin.getString("hasLoggedOut");
            if (hasLoggedOut != null && "Y".equals(hasLoggedOut)) {
                currentUserLogin = null;
            }
        }
        String cnPattern = EntityUtilProperties.getPropertyValue("security", "security.login.cert.pattern", "(.*)", delegator);
        Pattern pattern = Pattern.compile(cnPattern);
        if (currentUserLogin == null) {
            // 2.2 spec
            X509Certificate[] clientCerts = (X509Certificate[]) request.getAttribute("javax.servlet.request.X509Certificate");
            if (clientCerts == null) {
                // 2.1 spec
                clientCerts = (X509Certificate[]) request.getAttribute("javax.net.ssl.peer_certificates");
            }
            if (clientCerts != null) {
                String userLoginId = null;
                for (int i = 0; i < clientCerts.length; i++) {
                    // X500Principal x500 = clientCerts[i].getSubjectX500Principal();
                    // Debug.logInfo("Checking client certification for authentication: " + x500.getName(), module);
                    Map<String, String> x500Map = KeyStoreUtil.getCertX500Map(clientCerts[i]);
                    if (i == 0) {
                        String cn = x500Map.get("CN");
                        cn = cn.replaceAll("\\\\", "");
                        Matcher m = pattern.matcher(cn);
                        if (m.matches()) {
                            userLoginId = m.group(1);
                        } else {
                            if (Debug.infoOn()) {
                                Debug.logInfo("Client certificate CN does not match pattern: [" + cnPattern + "]", module);
                            }
                        }
                    }
                    try {
                        // check for a valid issuer (or generated cert data)
                        if (LoginWorker.checkValidIssuer(delegator, x500Map, clientCerts[i].getSerialNumber())) {
                            // Debug.logInfo("Looking up userLogin from CN: " + userLoginId, module);
                            // CN should match the userLoginId
                            GenericValue userLogin = EntityQuery.use(delegator).from("UserLogin").where("userLoginId", userLoginId).queryOne();
                            if (userLogin != null) {
                                String enabled = userLogin.getString("enabled");
                                if (enabled == null || "Y".equals(enabled)) {
                                    userLogin.set("hasLoggedOut", "N");
                                    userLogin.store();
                                    // login the user
                                    Map<String, Object> ulSessionMap = LoginWorker.getUserLoginSession(userLogin);
                                    // doing the main login
                                    return doMainLogin(request, response, userLogin, ulSessionMap);
                                }
                            }
                        }
                    } catch (GeneralException e) {
                        Debug.logError(e, module);
                    }
                }
            }
        }
    }
    return "success";
}
Also used : GenericValue(org.apache.ofbiz.entity.GenericValue) Pattern(java.util.regex.Pattern) GeneralException(org.apache.ofbiz.base.util.GeneralException) Matcher(java.util.regex.Matcher) HttpSession(javax.servlet.http.HttpSession) X509Certificate(java.security.cert.X509Certificate) Delegator(org.apache.ofbiz.entity.Delegator)

Example 59 with GeneralException

use of org.apache.ofbiz.base.util.GeneralException in project ofbiz-framework by apache.

the class JmsQueueListener method load.

public synchronized void load() throws GenericServiceException {
    try {
        InitialContext jndi = JNDIContextFactory.getInitialContext(jndiServer);
        QueueConnectionFactory factory = (QueueConnectionFactory) jndi.lookup(jndiName);
        if (factory != null) {
            con = factory.createQueueConnection(userName, password);
            con.setExceptionListener(this);
            session = con.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);
            queue = (Queue) jndi.lookup(queueName);
            if (queue != null) {
                QueueReceiver receiver = session.createReceiver(queue);
                receiver.setMessageListener(this);
                con.start();
                this.setConnected(true);
                Debug.logInfo("Listening to queue [" + queueName + "]...", module);
            } else {
                throw new GenericServiceException("Queue lookup failed.");
            }
        } else {
            throw new GenericServiceException("Factory (broker) lookup failed.");
        }
    } catch (NamingException ne) {
        throw new GenericServiceException("JNDI lookup problems; listener not running.", ne);
    } catch (JMSException je) {
        throw new GenericServiceException("JMS internal error; listener not running.", je);
    } catch (GeneralException ge) {
        throw new GenericServiceException("Problems with InitialContext; listener not running.", ge);
    }
}
Also used : GeneralException(org.apache.ofbiz.base.util.GeneralException) QueueConnectionFactory(javax.jms.QueueConnectionFactory) QueueReceiver(javax.jms.QueueReceiver) GenericServiceException(org.apache.ofbiz.service.GenericServiceException) NamingException(javax.naming.NamingException) JMSException(javax.jms.JMSException) InitialContext(javax.naming.InitialContext)

Example 60 with GeneralException

use of org.apache.ofbiz.base.util.GeneralException in project ofbiz-framework by apache.

the class EntityAutoEngine method runSync.

/**
 * @see org.apache.ofbiz.service.engine.GenericEngine#runSync(java.lang.String, org.apache.ofbiz.service.ModelService, java.util.Map)
 */
@Override
public Map<String, Object> runSync(String localName, ModelService modelService, Map<String, Object> parameters) throws GenericServiceException {
    // static java service methods should be: public Map<String, Object> methodName(DispatchContext dctx, Map<String, Object> context)
    DispatchContext dctx = dispatcher.getLocalContext(localName);
    Locale locale = (Locale) parameters.get("locale");
    Map<String, Object> result = ServiceUtil.returnSuccess();
    // check the package and method names
    if (modelService.invoke == null || !availableInvokeActionNames.contains(modelService.invoke)) {
        throw new GenericServiceException("In Service [" + modelService.name + "] the invoke value must be create, update, or delete for entity-auto engine");
    }
    if (UtilValidate.isEmpty(modelService.defaultEntityName)) {
        throw new GenericServiceException("In Service [" + modelService.name + "] you must specify a default-entity-name for entity-auto engine");
    }
    ModelEntity modelEntity = dctx.getDelegator().getModelEntity(modelService.defaultEntityName);
    if (modelEntity == null) {
        throw new GenericServiceException("In Service [" + modelService.name + "] the specified default-entity-name [" + modelService.defaultEntityName + "] is not valid");
    }
    try {
        boolean allPksInOnly = true;
        List<String> pkFieldNameOutOnly = null;
        /* Check for each pk if it's :
             * 1. part IN
             * 2. or part IN and OUT, but without value but present on parameters map
             * Help the engine to determinate the operation to realize for a create call or validate that
             * any pk is present for update/delete call.
             */
        for (ModelField pkField : modelEntity.getPkFieldsUnmodifiable()) {
            ModelParam pkParam = modelService.getParam(pkField.getName());
            boolean pkValueInParameters = pkParam.isIn() && UtilValidate.isNotEmpty(parameters.get(pkParam.getFieldName()));
            if (pkParam.isOut() && !pkValueInParameters) {
                if (pkFieldNameOutOnly == null) {
                    pkFieldNameOutOnly = new LinkedList<>();
                    allPksInOnly = false;
                }
                pkFieldNameOutOnly.add(pkField.getName());
            }
        }
        switch(modelService.invoke) {
            case "create":
                result = invokeCreate(dctx, parameters, modelService, modelEntity, allPksInOnly, pkFieldNameOutOnly);
                break;
            case "update":
                result = invokeUpdate(dctx, parameters, modelService, modelEntity, allPksInOnly);
                break;
            case "delete":
                result = invokeDelete(dctx, parameters, modelService, modelEntity, allPksInOnly);
                break;
            case "expire":
                result = invokeExpire(dctx, parameters, modelService, modelEntity, allPksInOnly);
                if (ServiceUtil.isSuccess(result)) {
                    result = invokeUpdate(dctx, parameters, modelService, modelEntity, allPksInOnly);
                }
                break;
            default:
                break;
        }
        GenericValue crudValue = (GenericValue) result.get("crudValue");
        if (crudValue != null) {
            result.remove("crudValue");
            result.putAll(modelService.makeValid(crudValue, ModelService.OUT_PARAM));
        }
    } catch (GeneralException e) {
        Debug.logError(e, "Error doing entity-auto operation for entity [" + modelEntity.getEntityName() + "] in service [" + modelService.name + "]: " + e.toString(), module);
        return ServiceUtil.returnError(UtilProperties.getMessage(resource, "ServiceEntityAutoOperation", UtilMisc.toMap("entityName", modelEntity.getEntityName(), "serviceName", modelService.name, "errorString", e.toString()), locale));
    }
    result.put(ModelService.SUCCESS_MESSAGE, ServiceUtil.makeSuccessMessage(result, "", "", "", ""));
    return result;
}
Also used : Locale(java.util.Locale) GenericValue(org.apache.ofbiz.entity.GenericValue) GeneralException(org.apache.ofbiz.base.util.GeneralException) ModelParam(org.apache.ofbiz.service.ModelParam) DispatchContext(org.apache.ofbiz.service.DispatchContext) ModelField(org.apache.ofbiz.entity.model.ModelField) GenericServiceException(org.apache.ofbiz.service.GenericServiceException) ModelEntity(org.apache.ofbiz.entity.model.ModelEntity)

Aggregations

GeneralException (org.apache.ofbiz.base.util.GeneralException)216 GenericValue (org.apache.ofbiz.entity.GenericValue)133 Delegator (org.apache.ofbiz.entity.Delegator)101 Locale (java.util.Locale)81 HashMap (java.util.HashMap)71 GenericEntityException (org.apache.ofbiz.entity.GenericEntityException)68 LocalDispatcher (org.apache.ofbiz.service.LocalDispatcher)68 IOException (java.io.IOException)65 BigDecimal (java.math.BigDecimal)55 GenericServiceException (org.apache.ofbiz.service.GenericServiceException)54 Writer (java.io.Writer)29 LinkedList (java.util.LinkedList)29 Map (java.util.Map)29 Timestamp (java.sql.Timestamp)26 StringWriter (java.io.StringWriter)19 Environment (freemarker.core.Environment)15 HttpServletRequest (javax.servlet.http.HttpServletRequest)14 ShoppingCart (org.apache.ofbiz.order.shoppingcart.ShoppingCart)14 HttpSession (javax.servlet.http.HttpSession)13 ParserConfigurationException (javax.xml.parsers.ParserConfigurationException)13