📄 login.java
字号:
/******************************************************************************
* The contents of this file are subject to the Compiere License Version 1.1
* ("License"); You may not use this file except in compliance with the License
* You may obtain a copy of the License at http://www.compiere.org/license.html
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for
* the specific language governing rights and limitations under the License.
* The Original Code is Compiere ERP & CRM Smart Business Solution. The Initial
* Developer of the Original Code is Jorg Janke. Portions created by Jorg Janke
* are Copyright (C) 1999-2005 Jorg Janke.
* All parts are Copyright (C) 1999-2005 ComPiere, Inc. All Rights Reserved.
* Contributor(s): ______________________________________.
*****************************************************************************/
package org.compiere.util;
import java.security.*;
import java.sql.*;
import java.util.*;
import java.util.logging.*;
import javax.swing.*;
//
import org.compiere.*;
import org.compiere.db.*;
import org.compiere.model.*;
/**
* Login Manager
*
* @author Jorg Janke
* @version $Id: Login.java,v 1.21 2005/11/20 22:40:44 jjanke Exp $
*/
public class Login
{
/**
* Test Init - Set Environment for tests
* @param isClient client session
* @return Context
*/
public static Properties initTest (boolean isClient)
{
// logger.entering("Env", "initTest");
Compiere.startupEnvironment(true);
// Test Context
Properties ctx = Env.getCtx();
Login login = new Login(ctx);
KeyNamePair[] roles = login.getRoles(CConnection.get(),
"System", "System", true);
// load role
if (roles != null && roles.length > 0)
{
KeyNamePair[] clients = login.getClients (roles[0]);
// load client
if (clients != null && clients.length > 0)
{
KeyNamePair[] orgs = login.getOrgs(clients[0]);
// load org
if (orgs != null && orgs.length > 0)
{
KeyNamePair[] whs = login.getWarehouses(orgs[0]);
//
login.loadPreferences(orgs[0], null, null, null);
}
}
}
//
Env.setContext(ctx, "#Date", "2000-01-01");
// logger.exiting("Env", "initTest");
return ctx;
} // testInit
/**
* Java Version Test
* @param isClient client connection
* @return true if Java Version is OK
*/
public static boolean isJavaOK (boolean isClient)
{
// Java System version check
String jVersion = System.getProperty("java.version");
if (jVersion.startsWith("1.5.0"))
return true;
// Warning
boolean ok = false;
// if (jVersion.startsWith("1.4")
// || jVersion.startsWith("1.5.1")) // later/earlier release
// ok = true;
// Error Message
StringBuffer msg = new StringBuffer();
msg.append(System.getProperty("java.vm.name")).append(" - ").append(jVersion);
if (ok)
msg.append("(untested)");
msg.append(" <> 1.5.0");
//
if (isClient)
JOptionPane.showMessageDialog(null, msg.toString(),
org.compiere.Compiere.getName() + " - Java Version Check",
ok ? JOptionPane.WARNING_MESSAGE : JOptionPane.ERROR_MESSAGE);
else
log.severe(msg.toString());
return ok;
} // isJavaOK
/**************************************************************************
* Login
*/
public Login (Properties ctx)
{
if (ctx == null)
throw new IllegalArgumentException("Context missing");
m_ctx = ctx;
} // Login
/** Logger */
private static CLogger log = CLogger.getCLogger(Login.class);
/** Context */
private Properties m_ctx = null;
/** Connection Profile */
private String m_connectionProfile = null;
/**
* (Test) Client Login.
* <p>
* - Get Connection
* - Compare User info
* <p>
* Sets Conext with login info
* @param cc connection
* @param app_user user
* @param app_pwd pwd
* @param force ignore pwd
* @return Array of Role KeyNamePair or null if error
* The error (NoDatabase, UserPwdError, DBLogin) is saved in the log
*/
protected KeyNamePair[] getRoles (CConnection cc,
String app_user, String app_pwd, boolean force)
{
// Establish connection
DB.setDBTarget(cc);
Env.setContext(m_ctx, "#Host", cc.getAppsHost());
Env.setContext(m_ctx, "#Database", cc.getDbName());
if (DB.getConnectionRO() == null)
{
log.saveError("NoDatabase", "");
return null;
}
if (app_pwd == null)
return null;
//
return getRoles (app_user, app_pwd, force);
} // getRoles
/**
* (Web) Client Login.
* <p>
* Compare User Info
* <p>
* Sets Conext with login info
* @param app_user Principal
* @return role array or null if in error.
* The error (NoDatabase, UserPwdError, DBLogin) is saved in the log
*/
public KeyNamePair[] getRoles (Principal app_user)
{
if (app_user == null)
return null;
// login w/o password as previously authorized
return getRoles (app_user.getName(), null, false);
} // getRoles
/**
* Client Login.
* <p>
* Compare User Info
* <p>
* Sets Conext with login info
* @param app_user user id
* @param app_pwd password
* @return role array or null if in error.
* The error (NoDatabase, UserPwdError, DBLogin) is saved in the log
*/
public KeyNamePair[] getRoles (String app_user, String app_pwd)
{
return getRoles (app_user, app_pwd, false);
} // login
/**
* Actual DB login procedure.
* @param app_user user
* @param app_pwd pwd
* @param force ignore pwd
* @return role array or null if in error.
* The error (NoDatabase, UserPwdError, DBLogin) is saved in the log
*/
private KeyNamePair[] getRoles (String app_user, String app_pwd, boolean force)
{
log.info("User=" + app_user);
long start = System.currentTimeMillis();
if (app_user == null)
{
log.warning("No Apps User");
return null;
}
// Authentification
boolean authenticated = false;
MSystem system = MSystem.get(m_ctx);
if (system.isLDAP())
{
authenticated = system.isLDAP(app_user, app_pwd);
if (authenticated)
app_pwd = null;
// if not authenticated, use AD_User as backup
}
else if (app_pwd == null || app_pwd.length() == 0)
{
log.warning("No Apps Password");
return null;
}
KeyNamePair[] retValue = null;
ArrayList<KeyNamePair> list = new ArrayList<KeyNamePair>();
//
StringBuffer sql = new StringBuffer("SELECT u.AD_User_ID, r.AD_Role_ID,r.Name,")
.append(" u.ConnectionProfile ")
.append("FROM AD_User u")
.append(" INNER JOIN AD_User_Roles ur ON (u.AD_User_ID=ur.AD_User_ID AND ur.IsActive='Y')")
.append(" INNER JOIN AD_Role r ON (ur.AD_Role_ID=r.AD_Role_ID AND r.IsActive='Y') ")
.append("WHERE COALESCE(u.LDAPUser,u.Name)=?") // #1
.append(" AND u.IsActive='Y'")
.append(" AND EXISTS (SELECT * FROM AD_Client c WHERE u.AD_Client_ID=c.AD_Client_ID AND c.IsActive='Y')");
if (app_pwd != null)
sql.append(" AND (u.Password=? OR u.Password=?)"); // #2/3
sql.append(" ORDER BY r.Name");
PreparedStatement pstmt = null;
try
{
pstmt = DB.prepareStatement(sql.toString(), null);
pstmt.setString(1, app_user);
if (app_pwd != null)
{
pstmt.setString(2, app_pwd);
pstmt.setString(3, SecureEngine.encrypt(app_pwd));
}
// execute a query
ResultSet rs = pstmt.executeQuery();
if (!rs.next()) // no record found
if (force)
{
Env.setContext(m_ctx, "#AD_User_Name", "System");
Env.setContext(m_ctx, "#AD_User_ID", "0");
Env.setContext(m_ctx, "#AD_User_Description", "System Forced Login");
Env.setContext(m_ctx, "#User_Level", "S "); // Format 'SCO'
Env.setContext(m_ctx, "#User_Client", "0"); // Format c1, c2, ...
Env.setContext(m_ctx, "#User_Org", "0"); // Format o1, o2, ...
rs.close();
pstmt.close();
retValue = new KeyNamePair[] {new KeyNamePair(0, "System Administrator")};
return retValue;
}
else
{
rs.close();
pstmt.close();
log.saveError("UserPwdError", app_user, false);
return null;
}
Env.setContext(m_ctx, "#AD_User_Name", app_user);
Env.setContext(m_ctx, "#AD_User_ID", rs.getInt(1));
Env.setContext(m_ctx, "#SalesRep_ID", rs.getInt(1));
//
Ini.setProperty(Ini.P_UID, app_user);
if (Ini.isPropertyBool(Ini.P_STORE_PWD))
Ini.setProperty(Ini.P_PWD, app_pwd);
m_connectionProfile = rs.getString(4); // User Based
if (m_connectionProfile != null)
{
CConnection cc = CConnection.get();
if (!cc.getConnectionProfile().equals(m_connectionProfile))
{
cc.setConnectionProfile(m_connectionProfile);
Ini.setProperty(Ini.P_CONNECTION, cc.toStringLong());
Ini.saveProperties(false);
}
}
do // read all roles
{
int AD_Role_ID = rs.getInt(2);
if (AD_Role_ID == 0)
Env.setContext(m_ctx, "#SysAdmin", "Y");
String Name = rs.getString(3);
KeyNamePair p = new KeyNamePair(AD_Role_ID, Name);
list.add(p);
}
while (rs.next());
rs.close();
pstmt.close();
pstmt = null;
//
retValue = new KeyNamePair[list.size()];
list.toArray(retValue);
log.fine("User=" + app_user + " - roles #" + retValue.length);
}
catch (SQLException ex)
{
log.log(Level.SEVERE, sql.toString(), ex);
log.saveError("DBLogin", ex);
retValue = null;
}
//
try
{
if (pstmt != null)
pstmt.close();
pstmt = null;
}
catch (Exception e)
{
pstmt = null;
}
return retValue;
} // getRoles
/**************************************************************************
* Load Clients.
* <p>
* Sets Role info in context and loads its clients
* @param role role information
* @return list of valid client KeyNodePairs or null if in error
*/
public KeyNamePair[] getClients (KeyNamePair role)
{
if (role == null)
throw new IllegalArgumentException("Role missing");
// s_log.fine("loadClients - Role: " + role.toStringX());
ArrayList<KeyNamePair> list = new ArrayList<KeyNamePair>();
KeyNamePair[] retValue = null;
String sql = "SELECT DISTINCT r.UserLevel, r.ConnectionProfile, " // 1/2
+ " c.AD_Client_ID,c.Name " // 3/4
+ "FROM AD_Role r"
+ " INNER JOIN AD_Client c ON (r.AD_Client_ID=c.AD_Client_ID) "
+ "WHERE r.AD_Role_ID=?" // #1
+ " AND r.IsActive='Y' AND c.IsActive='Y'";
PreparedStatement pstmt = null;
// get Role details
try
{
pstmt = DB.prepareStatement(sql, null);
pstmt.setInt(1, role.getKey());
ResultSet rs = pstmt.executeQuery();
if (!rs.next())
{
rs.close();
pstmt.close();
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -