📄 loginservices.java
字号:
/* * $Id: LoginServices.java 5462 2005-08-05 18:35:48Z jonesde $ * * Copyright (c) 2001-2005 The Open For Business Project - www.ofbiz.org * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT * OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR * THE USE OR OTHER DEALINGS IN THE SOFTWARE. */package org.ofbiz.securityext.login;import java.sql.Timestamp;import java.util.HashMap;import java.util.LinkedList;import java.util.List;import java.util.Locale;import java.util.Map;import javax.transaction.Transaction;import org.ofbiz.base.crypto.HashCrypt;import org.ofbiz.base.util.Debug;import org.ofbiz.base.util.UtilDateTime;import org.ofbiz.base.util.UtilMisc;import org.ofbiz.base.util.UtilProperties;import org.ofbiz.base.util.UtilValidate;import org.ofbiz.entity.GenericDelegator;import org.ofbiz.entity.GenericEntityException;import org.ofbiz.entity.GenericValue;import org.ofbiz.entity.serialize.XmlSerializer;import org.ofbiz.entity.transaction.GenericTransactionException;import org.ofbiz.entity.transaction.TransactionUtil;import org.ofbiz.security.Security;import org.ofbiz.service.DispatchContext;import org.ofbiz.service.ModelService;import org.ofbiz.service.ServiceUtil;/** * <b>Title:</b> Login Services * * @author <a href="mailto:jaz@ofbiz.org">Andy Zeneski</a> * @author <a href="mailto:jonesde@ofbiz.org">David E. Jones</a> * @version $Rev: 5462 $ * @since 2.0 */public class LoginServices { public static final String module = LoginServices.class.getName(); public static final String resource = "SecurityextUiLabels"; /** Login service to authenticate username and password * @return Map of results including (userLogin) GenericValue object */ public static Map userLogin(DispatchContext ctx, Map context) { Map result = new HashMap(); GenericDelegator delegator = ctx.getDelegator(); Locale locale = (Locale) context.get("locale"); boolean useEncryption = "true".equals(UtilProperties.getPropertyValue("security.properties", "password.encrypt")); // if isServiceAuth is not specified, default to not a service auth boolean isServiceAuth = context.get("isServiceAuth") != null && ((Boolean) context.get("isServiceAuth")).booleanValue(); 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"); // get the visitId for the history entity String visitId = (String) context.get("visitId"); String errMsg = ""; if (username == null || username.length() <= 0) { errMsg = UtilProperties.getMessage(resource,"loginservices.username_missing", locale); } else if (password == null || password.length() <= 0) { errMsg = UtilProperties.getMessage(resource,"loginservices.password_missing", locale); } else { String realPassword = useEncryption ? LoginServices.getPasswordHash(password) : password; boolean repeat = true; // starts at zero but it incremented at the beggining so in the first pass passNumber will be 1 int passNumber = 0; while (repeat) { repeat = false; // pass number is incremented here because there are continues in this loop so it may never get to the end passNumber++; GenericValue userLogin = null; try { // only get userLogin from cache for service calls; for web and other manual logins there is less time sensitivity if (isServiceAuth) { userLogin = delegator.findByPrimaryKeyCache("UserLogin", UtilMisc.toMap("userLoginId", username)); } else { userLogin = delegator.findByPrimaryKey("UserLogin", UtilMisc.toMap("userLoginId", username)); } } catch (GenericEntityException e) { Debug.logWarning(e, "", module); } if (userLogin != null) { String ldmStr = UtilProperties.getPropertyValue("security.properties", "login.disable.minutes"); long loginDisableMinutes = 30; try { loginDisableMinutes = Long.parseLong(ldmStr); } catch (Exception e) { loginDisableMinutes = 30; Debug.logWarning("Could not parse login.disable.minutes from security.properties, using default of 30", module); } Timestamp disabledDateTime = userLogin.getTimestamp("disabledDateTime"); Timestamp reEnableTime = null; if (loginDisableMinutes > 0 && disabledDateTime != null) { reEnableTime = new Timestamp(disabledDateTime.getTime() + loginDisableMinutes * 60000); } boolean doStore = true; // we might change & store this userLogin, so we should clone it here to get a mutable copy userLogin = GenericValue.create(userLogin); // get the is system flag -- system accounts can only be used for service authentication boolean isSystem = (isServiceAuth && userLogin.get("isSystem") != null) ? "Y".equalsIgnoreCase(userLogin.getString("isSystem")) : false; // grab the hasLoggedOut flag boolean hasLoggedOut = userLogin.get("hasLoggedOut") != null ? "Y".equalsIgnoreCase(userLogin.getString("hasLoggedOut")) : false; if (UtilValidate.isEmpty(userLogin.getString("enabled")) || "Y".equals(userLogin.getString("enabled")) || (reEnableTime != null && reEnableTime.before(UtilDateTime.nowTimestamp())) || (isSystem)) { String successfulLogin; if (!isSystem) { userLogin.set("enabled", "Y"); } // 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 if ((userLogin.get("currentPassword") != null && (realPassword.equals(userLogin.getString("currentPassword")) || ("true".equals(UtilProperties.getPropertyValue("security.properties", "password.accept.encrypted.and.plain")) && password.equals(userLogin.getString("currentPassword")))))) { Debug.logVerbose("[LoginServices.userLogin] : Password Matched", module); // update the hasLoggedOut flag if (hasLoggedOut) { userLogin.set("hasLoggedOut", "N"); } // reset failed login count if necessry Long currentFailedLogins = userLogin.getLong("successiveFailedLogins"); if (currentFailedLogins != null && currentFailedLogins.longValue() > 0) { userLogin.set("successiveFailedLogins", new Long(0)); } else if (!hasLoggedOut) { // successful login & no loggout flag, no need to change anything, so don't do the store doStore = false; } successfulLogin = "Y"; if (!isServiceAuth) { // get the UserLoginSession if this is not a service auth GenericValue userLoginSession = null; Map userLoginSessionMap = null; try { userLoginSession = userLogin.getRelatedOne("UserLoginSession"); if (userLoginSession != null) { Object deserObj = XmlSerializer.deserialize(userLoginSession.getString("sessionData"), delegator); //don't check, just cast, if it fails it will get caught and reported below; if (deserObj instanceof Map) userLoginSessionMap = (Map) deserObj; } } catch (GenericEntityException ge) { Debug.logWarning(ge, "Cannot get UserLoginSession for UserLogin ID: " + userLogin.getString("userLoginId"), module); } catch (Exception e) { Debug.logWarning(e, "Problems deserializing UserLoginSession", module); } // return the UserLoginSession Map if (userLoginSessionMap != null) { result.put("userLoginSession", userLoginSessionMap); } } result.put("userLogin", userLogin); result.put(ModelService.RESPONSE_MESSAGE, ModelService.RESPOND_SUCCESS); } else { // password is incorrect, but this may be the result of a stale cache entry, // so lets clear the cache and try again if this is the first pass if (isServiceAuth && passNumber <= 1) { delegator.clearCacheLine("UserLogin", UtilMisc.toMap("userLoginId", username)); repeat = true; continue; } Debug.logInfo("[LoginServices.userLogin] : Password Incorrect", module); // password invalid... errMsg = UtilProperties.getMessage(resource,"loginservices.password_incorrect", locale); // increment failed login count Long currentFailedLogins = userLogin.getLong("successiveFailedLogins"); if (currentFailedLogins == null) { currentFailedLogins = new Long(1); } else { currentFailedLogins = new Long(currentFailedLogins.longValue() + 1); } userLogin.set("successiveFailedLogins", currentFailedLogins); // if failed logins over amount in properties file, disable account String mflStr = UtilProperties.getPropertyValue("security.properties", "max.failed.logins"); long maxFailedLogins = 3; try { maxFailedLogins = Long.parseLong(mflStr); } catch (Exception e) { maxFailedLogins = 3; Debug.logWarning("Could not parse max.failed.logins from security.properties, using default of 3", module); } if (maxFailedLogins > 0 && currentFailedLogins.longValue() >= maxFailedLogins) { userLogin.set("enabled", "N"); userLogin.set("disabledDateTime", UtilDateTime.nowTimestamp()); } successfulLogin = "N"; } // this section is being done in its own transaction rather than in the //current/existing transaction because we may return error and we don't //want that to stop this from getting stored 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();
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -