Search in sources :

Example 1 with EntityCrypto

use of org.apache.ofbiz.entity.util.EntityCrypto 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 2 with EntityCrypto

use of org.apache.ofbiz.entity.util.EntityCrypto in project ofbiz-framework by apache.

the class LoginEvents method emailPassword.

/**
 *  Email the password for the userLoginId specified in the request object.
 *
 * @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 emailPassword(HttpServletRequest request, HttpServletResponse response) {
    String defaultScreenLocation = "component://securityext/widget/EmailSecurityScreens.xml#PasswordEmail";
    Delegator delegator = (Delegator) request.getAttribute("delegator");
    LocalDispatcher dispatcher = (LocalDispatcher) request.getAttribute("dispatcher");
    String productStoreId = ProductStoreWorker.getProductStoreId(request);
    String errMsg = null;
    boolean useEncryption = "true".equals(EntityUtilProperties.getPropertyValue("security", "password.encrypt", delegator));
    String userLoginId = request.getParameter("USERNAME");
    if ((userLoginId != null) && ("true".equals(EntityUtilProperties.getPropertyValue("security", "username.lowercase", delegator)))) {
        userLoginId = userLoginId.toLowerCase(Locale.getDefault());
    }
    if (UtilValidate.isEmpty(userLoginId)) {
        // the password was incomplete
        errMsg = UtilProperties.getMessage(resource, "loginevents.username_was_empty_reenter", UtilHttp.getLocale(request));
        request.setAttribute("_ERROR_MESSAGE_", errMsg);
        return "error";
    }
    GenericValue supposedUserLogin = null;
    String passwordToSend = null;
    String autoPassword = null;
    try {
        supposedUserLogin = EntityQuery.use(delegator).from("UserLogin").where("userLoginId", userLoginId).queryOne();
        if (supposedUserLogin == null) {
            // the Username was not found
            errMsg = UtilProperties.getMessage(resource, "loginevents.username_not_found_reenter", UtilHttp.getLocale(request));
            request.setAttribute("_ERROR_MESSAGE_", errMsg);
            return "error";
        }
        if (useEncryption) {
            // password encrypted, can't send, generate new password and email to user
            passwordToSend = RandomStringUtils.randomAlphanumeric(EntityUtilProperties.getPropertyAsInteger("security", "password.length.min", 5).intValue());
            if ("true".equals(EntityUtilProperties.getPropertyValue("security", "password.lowercase", delegator))) {
                passwordToSend = passwordToSend.toLowerCase(Locale.getDefault());
            }
            autoPassword = RandomStringUtils.randomAlphanumeric(EntityUtilProperties.getPropertyAsInteger("security", "password.length.min", 5).intValue());
            EntityCrypto entityCrypto = new EntityCrypto(delegator, null);
            try {
                passwordToSend = entityCrypto.encrypt(keyValue, EncryptMethod.TRUE, autoPassword);
            } catch (GeneralException e) {
                Debug.logWarning(e, "Problem in encryption", module);
            }
            supposedUserLogin.set("currentPassword", HashCrypt.cryptUTF8(LoginServices.getHashType(), null, autoPassword));
            supposedUserLogin.set("passwordHint", "Auto-Generated Password");
            if ("true".equals(EntityUtilProperties.getPropertyValue("security", "password.email_password.require_password_change", delegator))) {
                supposedUserLogin.set("requirePasswordChange", "Y");
            }
        } else {
            passwordToSend = supposedUserLogin.getString("currentPassword");
        }
        /* Its a Base64 string, it can contain + and this + will be converted to space after decoding the url.
               For example: passwordToSend "DGb1s2wgUQmwOBK9FK+fvQ==" will be converted to "DGb1s2wgUQmwOBK9FK fvQ=="
               So to fix it, done Url encoding of passwordToSend.
            */
        passwordToSend = URLEncoder.encode(passwordToSend, "UTF-8");
    } catch (GenericEntityException | UnsupportedEncodingException e) {
        Debug.logWarning(e, "", module);
        Map<String, String> messageMap = UtilMisc.toMap("errorMessage", e.toString());
        errMsg = UtilProperties.getMessage(resource, "loginevents.error_accessing_password", messageMap, UtilHttp.getLocale(request));
        request.setAttribute("_ERROR_MESSAGE_", errMsg);
        return "error";
    }
    StringBuilder emails = new StringBuilder();
    GenericValue party = null;
    try {
        party = supposedUserLogin.getRelatedOne("Party", false);
    } catch (GenericEntityException e) {
        Debug.logWarning(e, "", module);
    }
    if (party != null) {
        Iterator<GenericValue> emailIter = UtilMisc.toIterator(ContactHelper.getContactMechByPurpose(party, "PRIMARY_EMAIL", false));
        while (emailIter != null && emailIter.hasNext()) {
            GenericValue email = emailIter.next();
            emails.append(emails.length() > 0 ? "," : "").append(email.getString("infoString"));
        }
    }
    if (UtilValidate.isEmpty(emails.toString())) {
        // the Username was not found
        errMsg = UtilProperties.getMessage(resource, "loginevents.no_primary_email_address_set_contact_customer_service", UtilHttp.getLocale(request));
        request.setAttribute("_ERROR_MESSAGE_", errMsg);
        return "error";
    }
    // get the ProductStore email settings
    GenericValue productStoreEmail = null;
    try {
        productStoreEmail = EntityQuery.use(delegator).from("ProductStoreEmailSetting").where("productStoreId", productStoreId, "emailType", "PRDS_PWD_RETRIEVE").queryOne();
    } catch (GenericEntityException e) {
        Debug.logError(e, "Problem getting ProductStoreEmailSetting", module);
    }
    String bodyScreenLocation = null;
    if (productStoreEmail != null) {
        bodyScreenLocation = productStoreEmail.getString("bodyScreenLocation");
    }
    if (UtilValidate.isEmpty(bodyScreenLocation)) {
        bodyScreenLocation = defaultScreenLocation;
    }
    // set the needed variables in new context
    Map<String, Object> bodyParameters = new HashMap<>();
    bodyParameters.put("useEncryption", Boolean.valueOf(useEncryption));
    bodyParameters.put("password", UtilFormatOut.checkNull(passwordToSend));
    bodyParameters.put("locale", UtilHttp.getLocale(request));
    bodyParameters.put("userLogin", supposedUserLogin);
    bodyParameters.put("productStoreId", productStoreId);
    Map<String, Object> serviceContext = new HashMap<>();
    serviceContext.put("bodyScreenUri", bodyScreenLocation);
    serviceContext.put("bodyParameters", bodyParameters);
    if (productStoreEmail != null) {
        serviceContext.put("subject", productStoreEmail.getString("subject"));
        serviceContext.put("sendFrom", productStoreEmail.get("fromAddress"));
        serviceContext.put("sendCc", productStoreEmail.get("ccAddress"));
        serviceContext.put("sendBcc", productStoreEmail.get("bccAddress"));
        serviceContext.put("contentType", productStoreEmail.get("contentType"));
    } else {
        GenericValue emailTemplateSetting = null;
        try {
            emailTemplateSetting = EntityQuery.use(delegator).from("EmailTemplateSetting").where("emailTemplateSettingId", "EMAIL_PASSWORD").cache().queryOne();
        } catch (GenericEntityException e) {
            Debug.logError(e, module);
        }
        if (emailTemplateSetting != null) {
            String subject = emailTemplateSetting.getString("subject");
            subject = FlexibleStringExpander.expandString(subject, UtilMisc.toMap("userLoginId", userLoginId));
            serviceContext.put("subject", subject);
            serviceContext.put("sendFrom", emailTemplateSetting.get("fromAddress"));
        } else {
            serviceContext.put("subject", UtilProperties.getMessage(resource, "loginservices.password_reminder_subject", UtilMisc.toMap("userLoginId", userLoginId), UtilHttp.getLocale(request)));
            serviceContext.put("sendFrom", EntityUtilProperties.getPropertyValue("general", "defaultFromEmailAddress", delegator));
        }
    }
    serviceContext.put("sendTo", emails.toString());
    serviceContext.put("partyId", party.getString("partyId"));
    try {
        Map<String, Object> result = dispatcher.runSync("sendMailHiddenInLogFromScreen", serviceContext);
        if (ServiceUtil.isError(result)) {
            String errorMessage = ServiceUtil.getErrorMessage(result);
            request.setAttribute("_ERROR_MESSAGE_", errorMessage);
            Debug.logError(errorMessage, module);
            return "error";
        }
        if (ModelService.RESPOND_ERROR.equals(result.get(ModelService.RESPONSE_MESSAGE))) {
            Map<String, Object> messageMap = UtilMisc.toMap("errorMessage", result.get(ModelService.ERROR_MESSAGE));
            errMsg = UtilProperties.getMessage(resource, "loginevents.error_unable_email_password_contact_customer_service_errorwas", messageMap, UtilHttp.getLocale(request));
            request.setAttribute("_ERROR_MESSAGE_", errMsg);
            return "error";
        }
    } catch (GenericServiceException e) {
        Debug.logWarning(e, "", module);
        errMsg = UtilProperties.getMessage(resource, "loginevents.error_unable_email_password_contact_customer_service", UtilHttp.getLocale(request));
        request.setAttribute("_ERROR_MESSAGE_", errMsg);
        return "error";
    }
    // don't save password until after it has been sent
    if (useEncryption) {
        try {
            supposedUserLogin.store();
        } catch (GenericEntityException e) {
            Debug.logWarning(e, "", module);
            Map<String, String> messageMap = UtilMisc.toMap("errorMessage", e.toString());
            errMsg = UtilProperties.getMessage(resource, "loginevents.error_saving_new_password_email_not_correct_password", messageMap, UtilHttp.getLocale(request));
            request.setAttribute("_ERROR_MESSAGE_", errMsg);
            return "error";
        }
    }
    if (useEncryption) {
        errMsg = UtilProperties.getMessage(resource, "loginevents.new_password_createdandsent_check_email", UtilHttp.getLocale(request));
        request.setAttribute("_EVENT_MESSAGE_", errMsg);
    } else {
        errMsg = UtilProperties.getMessage(resource, "loginevents.new_password_sent_check_email", UtilHttp.getLocale(request));
        request.setAttribute("_EVENT_MESSAGE_", errMsg);
    }
    return "success";
}
Also used : GenericValue(org.apache.ofbiz.entity.GenericValue) LocalDispatcher(org.apache.ofbiz.service.LocalDispatcher) GeneralException(org.apache.ofbiz.base.util.GeneralException) HashMap(java.util.HashMap) EntityCrypto(org.apache.ofbiz.entity.util.EntityCrypto) UnsupportedEncodingException(java.io.UnsupportedEncodingException) Delegator(org.apache.ofbiz.entity.Delegator) GenericDelegator(org.apache.ofbiz.entity.GenericDelegator) GenericEntityException(org.apache.ofbiz.entity.GenericEntityException) GenericServiceException(org.apache.ofbiz.service.GenericServiceException) HashMap(java.util.HashMap) Map(java.util.Map)

Aggregations

Map (java.util.Map)2 GeneralException (org.apache.ofbiz.base.util.GeneralException)2 Delegator (org.apache.ofbiz.entity.Delegator)2 GenericEntityException (org.apache.ofbiz.entity.GenericEntityException)2 GenericValue (org.apache.ofbiz.entity.GenericValue)2 EntityCrypto (org.apache.ofbiz.entity.util.EntityCrypto)2 GenericServiceException (org.apache.ofbiz.service.GenericServiceException)2 LocalDispatcher (org.apache.ofbiz.service.LocalDispatcher)2 UnsupportedEncodingException (java.io.UnsupportedEncodingException)1 HashMap (java.util.HashMap)1 LinkedList (java.util.LinkedList)1 ServletContext (javax.servlet.ServletContext)1 HttpSession (javax.servlet.http.HttpSession)1 UtilGenerics.checkMap (org.apache.ofbiz.base.util.UtilGenerics.checkMap)1 EntityCryptoException (org.apache.ofbiz.entity.EntityCryptoException)1 GenericDelegator (org.apache.ofbiz.entity.GenericDelegator)1