Search in sources :

Example 1 with EntityCryptoException

use of org.apache.ofbiz.entity.EntityCryptoException 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 EntityCryptoException

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

the class EntityCrypto method findKey.

protected byte[] findKey(String originalKeyName, StorageHandler handler) throws EntityCryptoException {
    String hashedKeyName = handler.getHashedKeyName(originalKeyName);
    String keyMapName = handler.getKeyMapPrefix(hashedKeyName) + hashedKeyName;
    if (keyMap.containsKey(keyMapName)) {
        return keyMap.get(keyMapName);
    }
    // it's ok to run the bulk of this method unlocked or
    // unprotected; since the same result will occur even if
    // multiple threads request the same key, there is no
    // need to protected this block of code.
    GenericValue keyValue = null;
    try {
        keyValue = EntityQuery.use(delegator).from("EntityKeyStore").where("keyName", hashedKeyName).queryOne();
    } catch (GenericEntityException e) {
        throw new EntityCryptoException(e);
    }
    if (keyValue == null || keyValue.get("keyText") == null) {
        return null;
    }
    try {
        byte[] keyBytes = handler.decodeKeyBytes(keyValue.getString("keyText"));
        keyMap.putIfAbsent(keyMapName, keyBytes);
        // the same value with the following get().
        return keyMap.get(keyMapName);
    } catch (GeneralException e) {
        throw new EntityCryptoException(e);
    }
}
Also used : GenericValue(org.apache.ofbiz.entity.GenericValue) EntityCryptoException(org.apache.ofbiz.entity.EntityCryptoException) GeneralException(org.apache.ofbiz.base.util.GeneralException) GenericEntityException(org.apache.ofbiz.entity.GenericEntityException)

Example 3 with EntityCryptoException

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

the class EntityCrypto method createKey.

protected void createKey(String originalKeyName, StorageHandler handler, EncryptMethod encryptMethod) throws EntityCryptoException {
    String hashedKeyName = handler.getHashedKeyName(originalKeyName);
    Key key = handler.generateNewKey();
    final GenericValue newValue = delegator.makeValue("EntityKeyStore");
    try {
        newValue.set("keyText", handler.encodeKey(key.getEncoded()));
    } catch (GeneralException e) {
        throw new EntityCryptoException(e);
    }
    newValue.set("keyName", hashedKeyName);
    try {
        TransactionUtil.doNewTransaction(new Callable<Void>() {

            public Void call() throws Exception {
                delegator.create(newValue);
                return null;
            }
        }, "storing encrypted key", 0, true);
    } catch (GenericEntityException e) {
        throw new EntityCryptoException(e);
    }
}
Also used : GenericValue(org.apache.ofbiz.entity.GenericValue) EntityCryptoException(org.apache.ofbiz.entity.EntityCryptoException) GeneralException(org.apache.ofbiz.base.util.GeneralException) GenericEntityException(org.apache.ofbiz.entity.GenericEntityException) Key(java.security.Key) EntityCryptoException(org.apache.ofbiz.entity.EntityCryptoException) IOException(java.io.IOException) GenericEntityException(org.apache.ofbiz.entity.GenericEntityException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) GeneralException(org.apache.ofbiz.base.util.GeneralException)

Example 4 with EntityCryptoException

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

the class EntityCrypto method doDecrypt.

protected Object doDecrypt(String keyName, EncryptMethod encryptMethod, String encryptedString, StorageHandler handler) throws GeneralException {
    byte[] key = this.findKey(keyName, handler);
    if (key == null) {
        throw new EntityCryptoException("key(" + keyName + ") not found in database");
    }
    byte[] decryptedBytes = handler.decryptValue(key, encryptMethod, encryptedString);
    try {
        return UtilObject.getObjectException(decryptedBytes);
    } catch (ClassNotFoundException e) {
        throw new GeneralException(e);
    } catch (IOException e) {
        throw new GeneralException(e);
    }
}
Also used : EntityCryptoException(org.apache.ofbiz.entity.EntityCryptoException) GeneralException(org.apache.ofbiz.base.util.GeneralException) IOException(java.io.IOException)

Aggregations

GeneralException (org.apache.ofbiz.base.util.GeneralException)4 EntityCryptoException (org.apache.ofbiz.entity.EntityCryptoException)4 GenericEntityException (org.apache.ofbiz.entity.GenericEntityException)3 GenericValue (org.apache.ofbiz.entity.GenericValue)3 IOException (java.io.IOException)2 Key (java.security.Key)1 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)1 LinkedList (java.util.LinkedList)1 Map (java.util.Map)1 ServletContext (javax.servlet.ServletContext)1 HttpSession (javax.servlet.http.HttpSession)1 UtilGenerics.checkMap (org.apache.ofbiz.base.util.UtilGenerics.checkMap)1 Delegator (org.apache.ofbiz.entity.Delegator)1 EntityCrypto (org.apache.ofbiz.entity.util.EntityCrypto)1 GenericServiceException (org.apache.ofbiz.service.GenericServiceException)1 LocalDispatcher (org.apache.ofbiz.service.LocalDispatcher)1