Search in sources :

Example 91 with Delegator

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

the class LdapAuthenticationServices method userLogin.

public static boolean userLogin(DispatchContext ctx, Map<String, ?> context) {
    if (Debug.verboseOn())
        Debug.logVerbose("Starting LDAP authentication", module);
    Properties env = UtilProperties.getProperties("jndiLdap");
    String username = (String) context.get("login.username");
    if (username == null) {
        username = (String) context.get("username");
    }
    String password = (String) context.get("login.password");
    if (password == null) {
        password = (String) context.get("password");
    }
    String dn = null;
    Delegator delegator = ctx.getDelegator();
    boolean isServiceAuth = context.get("isServiceAuth") != null && ((Boolean) context.get("isServiceAuth")).booleanValue();
    GenericValue userLogin = null;
    try {
        userLogin = EntityQuery.use(delegator).from("UserLogin").where("userLoginId", username).cache(isServiceAuth).queryOne();
    } catch (GenericEntityException e) {
        Debug.logWarning(e, "", module);
    }
    if (userLogin != null) {
        dn = userLogin.getString("userLdapDn");
    }
    if (UtilValidate.isEmpty(dn)) {
        String dnTemplate = (String) env.get("ldap.dn.template");
        if (dnTemplate != null) {
            dn = dnTemplate.replace("%u", username);
        }
        if (Debug.verboseOn())
            Debug.logVerbose("Using DN template: " + dn, module);
    } else {
        if (Debug.verboseOn())
            Debug.logVerbose("Using UserLogin.userLdapDn: " + dn, module);
    }
    env.put(Context.SECURITY_PRINCIPAL, dn);
    env.put(Context.SECURITY_CREDENTIALS, password);
    try {
        // Create initial context
        DirContext ldapCtx = new InitialDirContext(env);
        ldapCtx.close();
    } catch (NamingException e) {
        if (Debug.verboseOn())
            Debug.logVerbose("LDAP authentication failed: " + e.getMessage(), module);
        return false;
    }
    if (Debug.verboseOn())
        Debug.logVerbose("LDAP authentication succeeded", module);
    if (!"true".equals(env.get("ldap.synchronize.passwords"))) {
        return true;
    }
    // Synchronize user's OFBiz password with user's LDAP password
    if (userLogin != null) {
        boolean useEncryption = "true".equals(EntityUtilProperties.getPropertyValue("security", "password.encrypt", delegator));
        String currentPassword = userLogin.getString("currentPassword");
        boolean samePassword;
        if (useEncryption) {
            samePassword = HashCrypt.comparePassword(currentPassword, LoginServices.getHashType(), password);
        } else {
            samePassword = currentPassword.equals(password);
        }
        if (!samePassword) {
            if (Debug.verboseOn())
                Debug.logVerbose("Starting password synchronization", module);
            userLogin.set("currentPassword", useEncryption ? HashCrypt.cryptUTF8(LoginServices.getHashType(), null, password) : password, false);
            Transaction parentTx = null;
            boolean beganTransaction = false;
            try {
                try {
                    parentTx = TransactionUtil.suspend();
                } catch (GenericTransactionException e) {
                    Debug.logError(e, "Could not suspend transaction: " + e.getMessage(), module);
                }
                try {
                    beganTransaction = TransactionUtil.begin();
                    userLogin.store();
                } catch (GenericEntityException e) {
                    Debug.logError(e, "Error saving UserLogin", module);
                    try {
                        TransactionUtil.rollback(beganTransaction, "Error saving UserLogin", e);
                    } catch (GenericTransactionException e2) {
                        Debug.logError(e2, "Could not rollback nested transaction: " + e2.getMessage(), module);
                    }
                } finally {
                    try {
                        TransactionUtil.commit(beganTransaction);
                        if (Debug.verboseOn())
                            Debug.logVerbose("Password synchronized", module);
                    } catch (GenericTransactionException e) {
                        Debug.logError(e, "Could not commit nested transaction: " + e.getMessage(), module);
                    }
                }
            } finally {
                if (parentTx != null) {
                    try {
                        TransactionUtil.resume(parentTx);
                        if (Debug.verboseOn())
                            Debug.logVerbose("Resumed the parent transaction.", module);
                    } catch (GenericTransactionException e) {
                        Debug.logError(e, "Could not resume parent nested transaction: " + e.getMessage(), module);
                    }
                }
            }
        }
    }
    return true;
}
Also used : GenericValue(org.apache.ofbiz.entity.GenericValue) Delegator(org.apache.ofbiz.entity.Delegator) Transaction(javax.transaction.Transaction) GenericEntityException(org.apache.ofbiz.entity.GenericEntityException) GenericTransactionException(org.apache.ofbiz.entity.transaction.GenericTransactionException) NamingException(javax.naming.NamingException) DirContext(javax.naming.directory.DirContext) InitialDirContext(javax.naming.directory.InitialDirContext) InitialDirContext(javax.naming.directory.InitialDirContext) Properties(java.util.Properties) UtilProperties(org.apache.ofbiz.base.util.UtilProperties) EntityUtilProperties(org.apache.ofbiz.entity.util.EntityUtilProperties)

Example 92 with Delegator

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

the class StatusServices method getStatusItems.

public static Map<String, Object> getStatusItems(DispatchContext ctx, Map<String, ?> context) {
    Delegator delegator = ctx.getDelegator();
    List<String> statusTypes = checkList(context.get("statusTypeIds"), String.class);
    Locale locale = (Locale) context.get("locale");
    if (UtilValidate.isEmpty(statusTypes)) {
        return ServiceUtil.returnError(UtilProperties.getMessage(resource, "CommonStatusMandatory", locale));
    }
    List<GenericValue> statusItems = new LinkedList<GenericValue>();
    for (String statusTypeId : statusTypes) {
        try {
            List<GenericValue> myStatusItems = EntityQuery.use(delegator).from("StatusItem").where("statusTypeId", statusTypeId).orderBy("sequenceId").cache(true).queryList();
            statusItems.addAll(myStatusItems);
        } catch (GenericEntityException e) {
            Debug.logError(e, module);
        }
    }
    Map<String, Object> ret = new LinkedHashMap<String, Object>();
    ret.put("statusItems", statusItems);
    return ret;
}
Also used : Locale(java.util.Locale) GenericValue(org.apache.ofbiz.entity.GenericValue) Delegator(org.apache.ofbiz.entity.Delegator) GenericEntityException(org.apache.ofbiz.entity.GenericEntityException) LinkedList(java.util.LinkedList) LinkedHashMap(java.util.LinkedHashMap)

Example 93 with Delegator

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

the class LoginServices method checkNewPassword.

public static void checkNewPassword(GenericValue userLogin, String currentPassword, String newPassword, String newPasswordVerify, String passwordHint, List<String> errorMessageList, boolean ignoreCurrentPassword, Locale locale) {
    Delegator delegator = userLogin.getDelegator();
    boolean useEncryption = "true".equals(EntityUtilProperties.getPropertyValue("security", "password.encrypt", delegator));
    String errMsg = null;
    if (!ignoreCurrentPassword) {
        // if the password.accept.encrypted.and.plain property in security is set to true allow plain or encrypted passwords
        // if this is a system account don't bother checking the passwords
        boolean passwordMatches = checkPassword(userLogin.getString("currentPassword"), useEncryption, currentPassword);
        if ((currentPassword == null) || (!passwordMatches)) {
            errMsg = UtilProperties.getMessage(resource, "loginservices.old_password_not_correct_reenter", locale);
            errorMessageList.add(errMsg);
        }
        if (checkPassword(userLogin.getString("currentPassword"), useEncryption, newPassword)) {
            errMsg = UtilProperties.getMessage(resource, "loginservices.new_password_is_equal_to_old_password", locale);
            errorMessageList.add(errMsg);
        }
    }
    if (UtilValidate.isEmpty(newPassword) || UtilValidate.isEmpty(newPasswordVerify)) {
        errMsg = UtilProperties.getMessage(resource, "loginservices.password_or_verify_missing", locale);
        errorMessageList.add(errMsg);
    } else if (!newPassword.equals(newPasswordVerify)) {
        errMsg = UtilProperties.getMessage(resource, "loginservices.password_did_not_match_verify_password", locale);
        errorMessageList.add(errMsg);
    }
    int passwordChangeHistoryLimit = 0;
    try {
        passwordChangeHistoryLimit = EntityUtilProperties.getPropertyAsInteger("security", "password.change.history.limit", 0).intValue();
    } catch (NumberFormatException nfe) {
        // No valid value is found so don't bother to save any password history
        passwordChangeHistoryLimit = 0;
    }
    Debug.logInfo(" password.change.history.limit is set to " + passwordChangeHistoryLimit, module);
    if (passwordChangeHistoryLimit > 0) {
        Debug.logInfo(" checkNewPassword Checking if user is tyring to use old password " + passwordChangeHistoryLimit, module);
        try {
            List<GenericValue> pwdHistList = EntityQuery.use(delegator).from("UserLoginPasswordHistory").where("userLoginId", userLogin.getString("userLoginId")).orderBy("-fromDate").queryList();
            for (GenericValue pwdHistValue : pwdHistList) {
                if (checkPassword(pwdHistValue.getString("currentPassword"), useEncryption, newPassword)) {
                    Map<String, Integer> messageMap = UtilMisc.toMap("passwordChangeHistoryLimit", passwordChangeHistoryLimit);
                    errMsg = UtilProperties.getMessage(resource, "loginservices.password_must_be_different_from_last_passwords", messageMap, locale);
                    errorMessageList.add(errMsg);
                    break;
                }
            }
        } catch (GenericEntityException e) {
            Debug.logWarning(e, "", module);
            Map<String, String> messageMap = UtilMisc.toMap("errorMessage", e.getMessage());
            errMsg = UtilProperties.getMessage(resource, "loginevents.error_accessing_password_change_history", messageMap, locale);
        }
    }
    int minPasswordLength = 0;
    try {
        minPasswordLength = EntityUtilProperties.getPropertyAsInteger("security", "password.length.min", 0).intValue();
    } catch (NumberFormatException nfe) {
        minPasswordLength = 0;
    }
    if (newPassword != null) {
        // Matching password with pattern
        String passwordPattern = EntityUtilProperties.getPropertyValue("security", "security.login.password.pattern", "^.*(?=.{5,}).*$", delegator);
        boolean usePasswordPattern = UtilProperties.getPropertyAsBoolean("security", "security.login.password.pattern.enable", true);
        if (usePasswordPattern) {
            Pattern pattern = Pattern.compile(passwordPattern);
            Matcher matcher = pattern.matcher(newPassword);
            boolean matched = matcher.matches();
            if (!matched) {
                // This is a mix to handle the OOTB pattern which is only a fixed length
                Map<String, String> messageMap = UtilMisc.toMap("minPasswordLength", Integer.toString(minPasswordLength));
                String passwordPatternMessage = EntityUtilProperties.getPropertyValue("security", "security.login.password.pattern.description", "loginservices.password_must_be_least_characters_long", delegator);
                errMsg = UtilProperties.getMessage(resource, passwordPatternMessage, messageMap, locale);
                errorMessageList.add(errMsg);
            }
        } else {
            if (!(newPassword.length() >= minPasswordLength)) {
                Map<String, String> messageMap = UtilMisc.toMap("minPasswordLength", Integer.toString(minPasswordLength));
                errMsg = UtilProperties.getMessage(resource, "loginservices.password_must_be_least_characters_long", messageMap, locale);
                errorMessageList.add(errMsg);
            }
        }
        if (newPassword.equalsIgnoreCase(userLogin.getString("userLoginId"))) {
            errMsg = UtilProperties.getMessage(resource, "loginservices.password_may_not_equal_username", locale);
            errorMessageList.add(errMsg);
        }
        if (UtilValidate.isNotEmpty(passwordHint) && (passwordHint.toUpperCase(Locale.getDefault()).indexOf(newPassword.toUpperCase(Locale.getDefault())) >= 0)) {
            errMsg = UtilProperties.getMessage(resource, "loginservices.password_hint_may_not_contain_password", locale);
            errorMessageList.add(errMsg);
        }
    }
}
Also used : GenericValue(org.apache.ofbiz.entity.GenericValue) Pattern(java.util.regex.Pattern) Matcher(java.util.regex.Matcher) Delegator(org.apache.ofbiz.entity.Delegator) GenericEntityException(org.apache.ofbiz.entity.GenericEntityException) LinkedHashMap(java.util.LinkedHashMap) Map(java.util.Map)

Example 94 with Delegator

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

the class PreferenceServices method getUserPreference.

/**
 * Retrieves a single user preference from persistent storage. Call with
 * userPrefTypeId and optional userPrefLoginId. If userPrefLoginId isn't
 * specified, then the currently logged-in user's userLoginId will be
 * used. The retrieved preference is contained in the <b>userPrefMap</b> element.
 * @param ctx The DispatchContext that this service is operating in.
 * @param context Map containing the input arguments.
 * @return Map with the result of the service, the output parameters.
 */
public static Map<String, Object> getUserPreference(DispatchContext ctx, Map<String, ?> context) {
    Locale locale = (Locale) context.get("locale");
    if (!PreferenceWorker.isValidGetId(ctx, context)) {
        return ServiceUtil.returnError(UtilProperties.getMessage(resource, "getPreference.permissionError", locale));
    }
    Delegator delegator = ctx.getDelegator();
    String userPrefTypeId = (String) context.get("userPrefTypeId");
    if (UtilValidate.isEmpty(userPrefTypeId)) {
        return ServiceUtil.returnError(UtilProperties.getMessage(resource, "getPreference.invalidArgument", locale));
    }
    String userLoginId = PreferenceWorker.getUserLoginId(context, true);
    Map<String, String> fieldMap = UtilMisc.toMap("userLoginId", userLoginId, "userPrefTypeId", userPrefTypeId);
    String userPrefGroupTypeId = (String) context.get("userPrefGroupTypeId");
    if (UtilValidate.isNotEmpty(userPrefGroupTypeId)) {
        fieldMap.put("userPrefGroupTypeId", userPrefGroupTypeId);
    }
    Map<String, Object> userPrefMap = null;
    try {
        GenericValue preference = EntityQuery.use(delegator).from("UserPreference").where(fieldMap).cache(true).queryFirst();
        if (preference != null) {
            userPrefMap = PreferenceWorker.createUserPrefMap(preference);
        }
    } catch (GeneralException e) {
        Debug.logWarning(e.getMessage(), module);
        return ServiceUtil.returnError(UtilProperties.getMessage(resource, "getPreference.readFailure", new Object[] { e.getMessage() }, locale));
    }
    Map<String, Object> result = ServiceUtil.returnSuccess();
    result.put("userPrefMap", userPrefMap);
    if (userPrefMap != null) {
        // Put the value in the result Map too, makes access easier for calling methods.
        Object userPrefValue = userPrefMap.get(userPrefTypeId);
        if (userPrefValue != null) {
            result.put("userPrefValue", userPrefValue);
        }
    }
    return result;
}
Also used : Locale(java.util.Locale) GenericValue(org.apache.ofbiz.entity.GenericValue) GeneralException(org.apache.ofbiz.base.util.GeneralException) Delegator(org.apache.ofbiz.entity.Delegator)

Example 95 with Delegator

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

the class PreferenceServices method removeUserPreference.

public static Map<String, Object> removeUserPreference(DispatchContext ctx, Map<String, ?> context) {
    Delegator delegator = ctx.getDelegator();
    Locale locale = (Locale) context.get("locale");
    String userLoginId = PreferenceWorker.getUserLoginId(context, false);
    String userPrefTypeId = (String) context.get("userPrefTypeId");
    if (UtilValidate.isEmpty(userLoginId) || UtilValidate.isEmpty(userPrefTypeId)) {
        return ServiceUtil.returnError(UtilProperties.getMessage(resource, "setPreference.invalidArgument", locale));
    }
    try {
        GenericValue rec = EntityQuery.use(delegator).from("UserPreference").where("userLoginId", userLoginId, "userPrefTypeId", userPrefTypeId).queryOne();
        if (rec != null) {
            rec.remove();
        }
    } catch (GenericEntityException e) {
        Debug.logWarning(e.getMessage(), module);
        return ServiceUtil.returnError(UtilProperties.getMessage(resource, "setPreference.writeFailure", new Object[] { e.getMessage() }, locale));
    }
    return ServiceUtil.returnSuccess();
}
Also used : Locale(java.util.Locale) GenericValue(org.apache.ofbiz.entity.GenericValue) Delegator(org.apache.ofbiz.entity.Delegator) GenericEntityException(org.apache.ofbiz.entity.GenericEntityException)

Aggregations

Delegator (org.apache.ofbiz.entity.Delegator)869 GenericValue (org.apache.ofbiz.entity.GenericValue)721 GenericEntityException (org.apache.ofbiz.entity.GenericEntityException)611 Locale (java.util.Locale)485 HashMap (java.util.HashMap)328 LocalDispatcher (org.apache.ofbiz.service.LocalDispatcher)324 GenericServiceException (org.apache.ofbiz.service.GenericServiceException)278 BigDecimal (java.math.BigDecimal)205 LinkedList (java.util.LinkedList)166 Timestamp (java.sql.Timestamp)163 GeneralException (org.apache.ofbiz.base.util.GeneralException)130 IOException (java.io.IOException)117 Map (java.util.Map)113 EntityCondition (org.apache.ofbiz.entity.condition.EntityCondition)61 Security (org.apache.ofbiz.security.Security)60 HttpSession (javax.servlet.http.HttpSession)59 Properties (java.util.Properties)37 UtilProperties (org.apache.ofbiz.base.util.UtilProperties)37 EntityUtilProperties (org.apache.ofbiz.entity.util.EntityUtilProperties)35 EntityListIterator (org.apache.ofbiz.entity.util.EntityListIterator)33