* INITIAL POPULATIONS OF THIS REPO

This commit is contained in:
2021-12-23 13:04:01 +08:00
parent 3165defa2e
commit ed70cad6ea
182 changed files with 22964 additions and 0 deletions
+51
View File
@@ -0,0 +1,51 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<modelVersion>4.0.0</modelVersion>
<groupId>com.fourelementscapital</groupId>
<artifactId>lib-auth</artifactId>
<version>2.0</version>
<licenses>
<license>
<name>The software is only allowed to be used in Four Elements - no license is given to any other parties</name>
</license>
</licenses>
<dependencies>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.12</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.kohsuke</groupId>
<artifactId>libpam4j</artifactId>
<version>1.8</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
<version>1.2</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-api</artifactId>
<version>2.8.1</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>2.8.1</version>
<scope>compile</scope>
</dependency>
</dependencies>
</project>
+42
View File
@@ -0,0 +1,42 @@
<?xml version="1.0"?>
<project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.fourelementscapital</groupId>
<artifactId>lib</artifactId>
<version>${revision}</version>
</parent>
<groupId>com.fourelementscapital</groupId>
<artifactId>lib-auth</artifactId>
<packaging>jar</packaging>
<name>lib-auth</name>
<description>Wiki authentication, Superuser authentication, Get user themes access permission</description>
<url>http://www.fourelementscapital.com</url>
<dependencies>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
</dependency>
<dependency>
<groupId>org.kohsuke</groupId>
<artifactId>libpam4j</artifactId>
</dependency>
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-api</artifactId>
</dependency>
</dependencies>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
</project>
@@ -0,0 +1,148 @@
/******************************************************************************
*
* Copyright: Intellectual Property of Four Elements Capital Pte Ltd, Singapore.
* All rights reserved.
*
******************************************************************************/
package com.fourelementscapital.auth;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Date;
import java.util.Map;
/**
* The DBManager class provides an Access Interface between the Database and Java.
* It can be used to get data from the database, insert new data and update existing data.
* The config file containing the details for the database hostname and credentials is located in the resources folder.
*/
class DBManager {
/**
* The database name for the current instance of DBManager
*/
private String dbName;
/**
* The connection string for the database connection. Stored in config file
*/
private String connectionString;
/**
* The resultSet which contains the returned results from the SQL Query of GetDatabase
*/
ResultSet resultSet = null;
/**
* The connection object of the current connection.
*/
private Connection conn = null;
/**
* Initialize the DBManager with the database name.
* @param dbName The name of the database e.x. trading, tradingRef, fundamentals
* @throws IOException
*/
public DBManager(String dbName) throws IOException
{
this.dbName = dbName;
}
/**
* This function connects to the dbName database;
* @throws SQLException This is thrown incase we are not able to connect to the database;
* @throws ClassNotFoundException This is thrown incase the driver is not found on this machine
* @throws IOException This is thrown incase the config file if not found on this machine under resources folder
*/
public void connect() throws SQLException, ClassNotFoundException, IOException
{
//String url = "jdbc:jtds:sqlserver://"+databaseServerAddress+";DatabaseName="+databaseName;
String driver = Utils.GetConfigValue("database_"+dbName.toLowerCase()+"_"+"driver");
Class.forName(driver);
conn = DriverManager.getConnection(Utils.GetConfigValue("database_"+dbName.toLowerCase()+"_"+"connstring"));
connectionString = conn.toString();
}
/**
* Closes the current Database connection.
* @throws SQLException
*/
public void closeConnection() throws SQLException
{
if(!conn.isClosed())
conn.close();
if(resultSet!=null)
resultSet.close();
}
/**
* This function returns the result set of the SQL Query used by GetDatabase;
* @param query The SQL Query passed to it.
* @return
* @throws SQLException
*/
private ResultSet executeQuery(String query) throws SQLException
{
Date start = new Date();
Statement statement = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_READ_ONLY);
resultSet = statement.executeQuery(query);
Date end = new Date();
long duration = (end.getTime() - start.getTime());
//Utils.Log("DEBUG: Query ("+query+") took "+duration+ " miliseconds");
return resultSet;
}
/**
* Used to query a database and access the resultant data in a ResultSet
* @param tableName The name of the database table to be accessed
* @param selectedFields A list of the values to be selected through the queries. <code>new ArrayList<String>();</code>
* be passed to select all fields (*)
* @param queryParams A hashmap containing the selection filters in the format <code>[column_name]=[value]</code>
* @param customQuery Any additional parameters to be added after the Where clause. Could be a GROUP BY or ORDER BY
* @return The resulting data in a ResultSet
* @throws SQLException
*/
public ResultSet GetDatabase(String tableName,ArrayList<String> selectedFields, Map<String,Object> queryParams, String customQuery) throws SQLException
{
String queryBuilder = "";
if(selectedFields.size()==0)
{
selectedFields.add("*");
}
queryBuilder += "SELECT "+Utils.Join(selectedFields,",")+" FROM "+tableName;
if(queryParams != null && queryParams.size()>0)
{
queryBuilder += " WHERE ";
for (Map.Entry<String,Object> entry : queryParams.entrySet()) {
try{
Float f = Float.parseFloat(entry.getValue().toString());
queryBuilder += " "+entry.getKey() + " = "+entry.getValue()+" AND";
}
catch(Exception ex)
{
queryBuilder += " "+entry.getKey() + " = '"+entry.getValue()+"' AND";
}
}
if(customQuery!= null && customQuery!="")
queryBuilder += customQuery+" AND";
queryBuilder = queryBuilder.substring(0,queryBuilder.length()-3);
}
//System.out.println(queryBuilder);
return executeQuery(queryBuilder);
}
}
@@ -0,0 +1,126 @@
/******************************************************************************
*
* Copyright: Intellectual Property of Four Elements Capital Pte Ltd, Singapore.
* All rights reserved.
*
******************************************************************************/
package com.fourelementscapital.auth;
import java.util.Set;
import org.jvnet.libpam.PAM;
import org.jvnet.libpam.PAMException;
import org.jvnet.libpam.UnixUser;
/**
* PAMAuthentication will authenticate user to local unix machine using PAM.
* This class is a wrapper of libpam4j, a Java/PAM bindings using JNA, to use internally in 4ECaps.
*/
public class PAMAuthentication {
/**
* Check whether user is exist
* @param username Username
* @return true if user is exist
*/
public static boolean isExist(String username) {
return UnixUser.exists(username);
}
/**
* Get current user logged in Unix system
* @return username of user logged in
*/
public static String getCurrentUserLoggedIn() {
return System.getProperty("user.name");
}
/**
* Get username of current user logged in
* @return username of user logged in
* @throws PAMException
*/
public static String getUsername() throws PAMException {
UnixUser ux = new UnixUser(getCurrentUserLoggedIn());
return ux.getUserName();
}
/**
* Get UID of current user logged in
* @return UID of user logged in
* @throws PAMException
*/
public static int getUID() throws PAMException {
UnixUser ux = new UnixUser(getCurrentUserLoggedIn());
return ux.getUID();
}
/**
* Get GID of current user logged in
* @return GID of user logged in
* @throws PAMException
*/
public static int getGID() throws PAMException {
UnixUser ux = new UnixUser(getCurrentUserLoggedIn());
return ux.getGID();
}
/**
* Get gecos (the real name) of current user logged in
* @return gecos of user logged in
* @throws PAMException
*/
public static String getGecos() throws PAMException {
UnixUser ux = new UnixUser(getCurrentUserLoggedIn());
return ux.getGecos();
}
/**
* Get home directory of current user logged in
* @return home directory of user logged in
* @throws PAMException
*/
public static String getDir() throws PAMException {
UnixUser ux = new UnixUser(getCurrentUserLoggedIn());
return ux.getDir();
}
/**
* Get the shell of current user logged in
* @return the shell of user logged in
* @throws PAMException
*/
public static String getShell() throws PAMException {
UnixUser ux = new UnixUser(getCurrentUserLoggedIn());
return ux.getShell();
}
/**
* Get the groups that user logged in belongs to
* @return the groups of user logged in
* @throws PAMException
*/
public static Set<String> getGroups() throws PAMException {
UnixUser ux = new UnixUser(getCurrentUserLoggedIn());
return ux.getGroups();
}
/**
* Authenticate user
* @param service Service
* @param username Username
* @param password Password
* @return authenticated user in UnixUser object
* @throws PAMException
*/
public static UnixUser authenticate(String service, String username, String password) throws PAMException {
PAM p = new PAM(service);
return p.authenticate(username, password);
}
}
@@ -0,0 +1,177 @@
/******************************************************************************
*
* Copyright: Intellectual Property of Four Elements Capital Pte Ltd, Singapore.
* All rights reserved.
*
******************************************************************************/
package com.fourelementscapital.auth;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.security.MessageDigest;
import org.apache.commons.codec.binary.Hex;
/**
* SuperUserAuthentication provides mechanism to store password into a file.
* This mechanism is implemented in superuser authentication of an application.
* The config file containing the path of saved password located in the resources folder.
*/
public class SuperUserAuthentication {
/**
* Private constructor to prevent instantiation.
*/
private SuperUserAuthentication()
{
}
/**
* Password filename that will be created in the folder path.
*/
private static String passwordFilename = "superuser.pwd";
/**
* Validate password whether it equals with the encrypted file, if file is not exist then set the password by creating it.
* @param pwd Password
* @return true if process succeed
* @throws Exception
*/
public static boolean validateOrSet(String pwd) throws Exception {
File file=getPwdFile();
String encpwd=null;
boolean rtn=false;
if(file.exists()){
encpwd=readFile(file);
}
if(encpwd!=null && !encpwd.equals("")){
rtn=isValid(pwd,encpwd);
}else{
setPassword(pwd);
rtn=true;
}
return rtn;
}
/**
* Change password to a new one if password is valid
* @param pwd Password
* @param newpassword New password
* @return true if process succeed
* @throws Exception
*/
public static boolean changePwd(String pwd,String newpassword) throws Exception {
boolean rtn=validateOrSet(pwd);
if(rtn){
//Thread.sleep(1000); //wait till it closes the stream ....
setPassword(newpassword);
}
return rtn;
}
/**
* Check whether password is valid, compared to encrypted password
* @param password Password
* @param encpass Encrypted password
* @return true if encrypted password equals salt password
* @throws Exception
*/
private static boolean isValid(String password, String encpass) throws Exception {
String salt=encpass.split(":")[2];
String saltpass=":B:"+salt+":"+getMD5(salt+"-"+getMD5(password));
if(encpass.equals(saltpass)){
return true;
}else{
return false;
}
}
/**
* Get MD5 of source string
* @param source Source string
* @return MD5 string
* @throws Exception
*/
private static String getMD5(String source) throws Exception {
byte[] bytesOfMessage = source.getBytes();
java.security.MessageDigest md = MessageDigest.getInstance("MD5");
byte[] thedigest = md.digest(bytesOfMessage);
final String result = new String(Hex.encodeHex(thedigest));
return result;
}
/**
* Set password to encrypted file
* @param plain_pwd Plain password
* @throws Exception
*/
private static void setPassword(String plain_pwd) throws Exception {
BufferedWriter writer = null;
try {
String salt="d1e93dec";
String saltpass=":B:"+salt+":"+getMD5(salt+"-"+getMD5(plain_pwd));
File file=getPwdFile();
writer = new BufferedWriter(new FileWriter(file));
writer.write(saltpass);
}
finally {
if (writer != null) writer.close();
}
}
/**
* Get password file
* @return file
* @throws Exception
*/
private static File getPwdFile() throws Exception {
String root = Utils.GetConfigValue("superuser_password_folder");
File file =new File(root + passwordFilename);
if ( !file.exists() ) {
file.createNewFile();
}
return file;
}
/**
* Read file
* @param path Path file
* @throws IOException
*/
private static String readFile(File path) throws IOException {
StringBuilder contents = new StringBuilder();
BufferedReader input = null;
try {
input = new BufferedReader(new FileReader(path));
String line = input.readLine();
if (line != null) {
contents.append(line);
}
}
finally {
if (input != null) input.close();
}
return contents.toString();
}
}
@@ -0,0 +1,30 @@
/******************************************************************************
*
* Copyright: Intellectual Property of Four Elements Capital Pte Ltd, Singapore.
* All rights reserved.
*
******************************************************************************/
package com.fourelementscapital.auth;
public class SystemAuthentication {
/**
* Get current user logged in Unix system
* @return username of user logged in
*/
public static String getCurrentUserLoggedIn() {
return System.getProperty("user.name");
}
/**
* Check whether a user logged in to the system
* @return true if user logged in
*/
public static boolean isUserLoggedIn() {
return (null != getCurrentUserLoggedIn() && !"".equals(getCurrentUserLoggedIn()));
}
}
@@ -0,0 +1,147 @@
/******************************************************************************
*
* Copyright: Intellectual Property of Four Elements Capital Pte Ltd, Singapore.
* All rights reserved.
*
******************************************************************************/
package com.fourelementscapital.auth;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
/**
* UserThemeAccessPermission provides functions to convert theme access permissions into 'rwx' permission group.
* Example : a user has 'X' permission in 'computing' theme. The 'computing' theme then will be included in 'rwx' permission group.
* Another Example : a user has 'U' permission in 'etrading' theme. The 'etrading' theme then will be included in 'rx' permission group.
*/
public class UserThemeAccessPermission {
/**
* Username
*/
private String username;
/**
* 'rwx' permission group
*/
private ArrayList<String> rwx = new ArrayList<String>();
/**
* 'rx' permission group
*/
private ArrayList<String> rx = new ArrayList<String>();
/**
* 'r' permission group
*/
private ArrayList<String> r = new ArrayList<String>();
/**
* Constructor. Creates a new UserThemeAccessPermission object
* @param un Username
*/
public UserThemeAccessPermission(String un) {
this.username=un;
}
/**
* Get rwx permission group
* @return rwx list
*/
public ArrayList<String> getRwx() {
return rwx;
}
/**
* Get rx permission group
* @return rx list
*/
public ArrayList<String> getRx() {
return rx;
}
/**
* Get r permission group
* @return r list
*/
public ArrayList<String> getR() {
return r;
}
/**
* Add permission with user's themes
* @param themes
* @throws Exception
*/
public void addPermissionWithThemes(Map<String,String> themes) throws Exception {
try{
Map<String,String> resolved = this.replacePermissions(themes);
for(Iterator<String> it=resolved.keySet().iterator();it.hasNext();){
String theme=it.next();
String val=resolved.get(theme);
if(val!=null && val.trim().equalsIgnoreCase("rwx")) getRwx().add(theme);
if(val!=null && val.trim().equalsIgnoreCase("rx")) getRx().add(theme);
if(val!=null && val.trim().equalsIgnoreCase("r")) getR().add(theme);
}
} catch(Exception e) {
throw e;
}
}
/**
* Replace the permission letter with 'rwx'.
* @param data
* @return themes with 'rwx' permissions
* @throws Exception
*/
public static Map<String,String> replacePermissions(Map<String,String> data) throws Exception {
HashMap<String,String> perm = new HashMap<String,String>();
perm.put("X","rwx");
perm.put("S","rwx");
perm.put("B","rwx");
perm.put("C","rwx");
perm.put("U","rx");
perm.put("N","r");
perm.put("M","rwx");
for(String key: data.keySet()){
data.put(key, perm.get(data.get(key)));
}
return data;
}
/**
* Overriding to make unique objects per username
* @param obj Instance of AuthUser or other object
* @return true if obj's username is equal with class' username
*/
public boolean equals(Object obj ) {
if(obj instanceof UserThemeAccessPermission){
UserThemeAccessPermission other=(UserThemeAccessPermission)obj;
if(other.username.equals(this.username)){
return true;
}else{
return false;
}
}else{
return false;
}
}
/**
* Override toString() method
* @return username string
*/
public String toString() {
return ""+this.username;
}
}
@@ -0,0 +1,82 @@
/******************************************************************************
*
* Copyright: Intellectual Property of Four Elements Capital Pte Ltd, Singapore.
* All rights reserved.
*
******************************************************************************/
package com.fourelementscapital.auth;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.Properties;
/**
* This class contains Static Utility functions
*/
class Utils {
/**
* Accepts an ArrayList of strings and then returns a delimiter separated string
* @param al The arraylist of strings
* @param delimiter The delimiter
* @return The delimiter separated string
*/
protected static String Join(ArrayList<String> al,String delimiter)
{
return al.toString().replaceAll("\\[|\\]", "").replaceAll(", ",delimiter);
}
/**
* Get the value of a property defined in config file
* @param propertyName - the name or key of the property you want to retrieve
* @return the string value
* @throws IOException
*/
protected static String GetConfigValue(String propertyName) throws IOException
{
Properties prop = new Properties();
String propFileName = "config_auth.properties";
InputStream inputStream = Utils.class.getClassLoader().getResourceAsStream(propFileName);
if (inputStream != null) {
prop.load(inputStream);
} else {
throw new FileNotFoundException("property file '" + propFileName + "' not found in the classpath");
}
Date time = new Date(System.currentTimeMillis());
// get the property value and print it out
String value = prop.getProperty(propertyName);
return value;
}
/**
* Capitalize first char of a word.
* Example : 'this is text. another text' will be converted to 'This Is Text. Another Text'
* @param string
* @return string
*/
protected static String capitalizeString(String string) {
char[] chars = string.toLowerCase().toCharArray();
boolean found = false;
for (int i = 0; i < chars.length; i++) {
if (!found && Character.isLetter(chars[i])) {
chars[i] = Character.toUpperCase(chars[i]);
found = true;
} else if (Character.isWhitespace(chars[i]) || chars[i]=='.' || chars[i]=='\'') { // You can add other chars here
found = false;
}
}
return String.valueOf(chars);
}
}
@@ -0,0 +1,176 @@
/******************************************************************************
*
* Copyright: Intellectual Property of Four Elements Capital Pte Ltd, Singapore.
* All rights reserved.
*
******************************************************************************/
package com.fourelementscapital.auth;
import java.security.MessageDigest;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.Vector;
import org.apache.commons.codec.binary.Hex;
/**
* WikiAuthentication will check / validate user authentication to Wiki database.
* It also provide functions to get encrypted password of specific user & get list of Wiki users.
*/
public class WikiAuthentication {
public static final String SESSION_LOGGED_USER = "session^logged^user";
/**
* Private constructor to prevent instantiation.
*/
private WikiAuthentication()
{
}
/**
* Validate Wiki User. If user_name is valid & password being encrypted equals value in database then it will return true.
* @param user_name
* @param password
* @return is user valid
* @throws Exception
*/
public static boolean validateUser(String user_name, String password) throws Exception {
String encpass = getEncryptedPwd(user_name);
return isValid(password,encpass);
}
/**
* Validate Wiki User With Encrypted Password. If user_name is valid & encrypted password equals value in database then it will return true.
* @param user_name
* @param encryptedPassword
* @return is user valid
* @throws Exception
*/
public static boolean validateUserEncryptedPassword(String user_name, String encryptedPassword) throws Exception {
String encpass = getEncryptedPwd(user_name);
if (encryptedPassword == null) {
return false;
}
return (encryptedPassword.equals(encpass));
}
/**
* Check whether password is valid, compare to encrypted password
* @param password Password
* @param encpass Encrypted password
* @return true if encrypted password equals salt password
* @throws Exception
*/
private static boolean isValid(String password, String encpass) throws Exception {
if (encpass == null || password == null) return false;
String salt=encpass.split(":")[2];
String saltpass=":B:"+salt+":"+getMD5(salt+"-"+getMD5(password));
if(encpass.equals(saltpass)){
return true;
}else{
return false;
}
}
/**
* Get MD5 of source string
* @param source Source string
* @return MD5 string
* @throws Exception
*/
private static String getMD5(String source) throws Exception {
byte[] bytesOfMessage = source.getBytes();
java.security.MessageDigest md = MessageDigest.getInstance("MD5");
byte[] thedigest = md.digest(bytesOfMessage);
final String result = new String(Hex.encodeHex(thedigest));
return result;
}
/**
* List / get all Wiki users. The fields returned are : user_name, user_real_name, user_password, user_email.
* @return users
* @throws Exception
*/
public static Vector<HashMap<String, String>> listUsers() throws Exception {
Vector<HashMap<String, String>> rtn = null;
DBManager dbm = new DBManager("wiki");
dbm.connect();
//sql = "select user_name,user_real_name,user_password,user_email from user";
ArrayList<String> selectedFields = new ArrayList<String>();
selectedFields.add("user_name");
selectedFields.add("user_real_name");
selectedFields.add("user_password");
selectedFields.add("user_email");
ResultSet rs = dbm.GetDatabase("user", selectedFields, null, null);
rtn = new Vector<HashMap<String, String>>();
while(rs.next()){
String user_name=rs.getString("user_name");
String user_real_name=rs.getString("user_real_name");
String user_password=rs.getString("user_password");
String user_email=rs.getString("user_email");
HashMap<String, String> h=new HashMap<String, String>();
h.put("user_name",user_name );
h.put("user_real_name",user_real_name );
h.put("user_password",user_password );
h.put("user_email",user_email );
rtn.add(h);
}
dbm.closeConnection();
return rtn;
}
/**
* Get encrypted password of specific user
* @param user
* @return encrypted password
* @throws Exception
*/
public static String getEncryptedPwd(String user) throws Exception {
if ((user == null) || user.equals("")) return null;
String rtn = null;
DBManager dbm = new DBManager("wiki");
dbm.connect();
//sql = "select CAST(user_password AS CHAR(10000) CHARACTER SET utf8) as pass from user where user_name=?"
ArrayList<String> selectedFields = new ArrayList<String>();
selectedFields.add("CAST(user_password AS CHAR(10000) CHARACTER SET utf8) as pass");
Map<String,Object> queryParams = new HashMap<String,Object>();
queryParams.put("user_name", Utils.capitalizeString(user));
ResultSet rs = dbm.GetDatabase("user", selectedFields, queryParams, null);
while(rs.next()){
rtn=rs.getString("pass");
}
dbm.closeConnection();
return rtn;
}
}
@@ -0,0 +1,99 @@
/******************************************************************************
*
* Copyright: Intellectual Property of Four Elements Capital Pte Ltd, Singapore.
* All rights reserved.
*
******************************************************************************/
package com.fourelementscapital.auth;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* WikiAuthenticationServlet is a servlet to facilitate automatic Wiki authentication.
* How to use this servlet, see documentation : http://wiki.4ecap.com/4ECwiki/Lib-auth#Automatic_Wiki_Authentication.
*/
public class WikiAuthenticationServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private static final String LOGOUT = "logout";
/**
* Handle post request, validate username & encrypted password by comparing them with Wiki database.
* If valid, generate session to be used throughout the app then redirect to app url.
* If not valid, redirect to wiki login url.
* @param request request
* @param response response
*/
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try {
// get request parameters :
String username = request.getParameter("username");
String encryptedPassword = request.getParameter("encryptedPassword");
String redirectUrl = request.getParameter("redirectUrl");
// get wiki login url from config file
String wikiLoginUrl = Utils.GetConfigValue("wiki_login_url");
// if there's already session then redirect to app url
if (request.getSession().getAttribute(WikiAuthentication.SESSION_LOGGED_USER) != null) {
response.sendRedirect(redirectUrl);
}
// if there's null parameter then redirect to wiki login
else if (username == null || encryptedPassword == null || redirectUrl == null) {
response.sendRedirect(wikiLoginUrl);
}
// validate username & encrypted password, if valid then redirect to app url
else if (WikiAuthentication.validateUserEncryptedPassword(username, encryptedPassword)) {
// set session for app using lib-auth
request.getSession().setAttribute(WikiAuthentication.SESSION_LOGGED_USER, username);
response.sendRedirect(redirectUrl);
}
// else, redirect to wiki login
else {
response.sendRedirect(wikiLoginUrl);
}
}catch(Exception e){
e.printStackTrace();
}
}
/**
* Handle get request, logout (remove session) and redirect to a url.
* @param request request
* @param response response
*/
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String method = request.getParameter("method");
// logout, remove session
if(method != null && method.equals(this.LOGOUT)) {
if (request.getSession().getAttribute(WikiAuthentication.SESSION_LOGGED_USER) != null) {
request.getSession().removeAttribute(WikiAuthentication.SESSION_LOGGED_USER);
}
}
// redirect to Wiki page
response.sendRedirect(Utils.GetConfigValue("wiki_login_url"));
}
}
+7
View File
@@ -0,0 +1,7 @@
database_wiki_connstring=jdbc:mysql://wiki.4ecap.com/4EwikiDB1?user=4ecremoteuser&password=4ecrmt2011
database_wiki_driver=com.mysql.jdbc.Driver
wiki_login_url=http://wiki.4ecap.com
superuser_password_folder=/tmp/
#superuser_password_folder=d:\\tmp\\
+13
View File
@@ -0,0 +1,13 @@
<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="WARN">
<Appenders>
<Console name="CONSOLE" target="SYSTEM_OUT">
<PatternLayout pattern="%4p %d{HH:mm:ss,SSS} %C - %m%n" />
</Console>
</Appenders>
<Loggers>
<Root level="ERROR">
<AppenderRef ref="CONSOLE"/>
</Root>
</Loggers>
</Configuration>
@@ -0,0 +1,215 @@
/******************************************************************************
*
* Copyright: Intellectual Property of Four Elements Capital Pte Ltd, Singapore.
* All rights reserved.
*
******************************************************************************/
package com.fourelementscapital.auth;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.Vector;
import javax.swing.JOptionPane;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import junit.framework.Assert;
import junit.framework.TestCase;
/**
* lib-auth unit test
*/
public class LibAuthTest extends TestCase {
private static final Logger log = LogManager.getLogger(LibAuthTest.class.getName());
/**
* Wiki authentication test : login, check login, get authenticated user, get user access.
*/
public void testWikiAuthentication()
{
log.debug(">>>>>> testWikiAuthentication()");
try {
// wiki login :
String user = "bot";
String password = "bot2018";
boolean success= WikiAuthentication.validateUser(user, password); // validate wiki user
log.debug("validate wiki user : " + success);
JOptionPane.showMessageDialog(null, "validate wiki user success");
HashMap<String, String> loginMap = new HashMap<String, String>();
if(!success){
loginMap.put("message", "Invalid username or password");
Assert.assertTrue(false); // scenario : login must success
}else{
loginMap.put("authenticatedUser", user);
// example : get encrypted password and store it to map for further process
String pss = WikiAuthentication.getEncryptedPwd(user);
loginMap.put("encryptedPassword", pss);
}
// store validate user result to map
loginMap.put("loggedin", Boolean.toString(success));
// check whether user login / not :
boolean loggedin = Boolean.parseBoolean(loginMap.get("loggedin"));
log.debug("is user logged in : " + loggedin);
Assert.assertTrue(loggedin);
// get authenticated user :
String authenticatedUser = loginMap.get("authenticatedUser");
log.debug("get authenticatedUser : " + authenticatedUser);
// Get user access. Use dummy themes for testing purpose.
// To get themes from infrastructureDB : Map themes = infrastructureDB.getThemes4Users(user). It needs lib-db library.
Map<String, String> themes= new HashMap<String, String>();
themes.put("computing", "X");
themes.put("etrading", "U");
themes.put("execution", "N");
themes.put("bb", "B");
UserThemeAccessPermission userTheme = new UserThemeAccessPermission(user);
userTheme.addPermissionWithThemes(themes);
ArrayList<String> rwxList = userTheme.getRwx();
log.debug("rwxList : ");
for (String rwx : rwxList) {
log.debug("- " + rwx);
}
Assert.assertTrue(rwxList.contains("computing") && rwxList.contains("bb")); // getRwx() must contains 'computing' & 'bb'
ArrayList<String> rxList = userTheme.getRx();
log.debug("rxList : ");
for (String rx : rxList) {
log.debug("- " + rx);
}
Assert.assertTrue(rxList.contains("etrading")); // getRx() must contains 'etrading'
ArrayList<String> rList = userTheme.getR();
log.debug("rList : ");
for (String r : rList) {
log.debug("- " + r);
}
Assert.assertTrue(rList.contains("execution")); // getR() must contains 'execution'
}
catch (Exception e) {
e.printStackTrace();
assertTrue( false );
}
}
/**
* Super user authentication test : validate / set / change password, check login, get authenticated user
*/
public void testSuperUserAuthentication()
{
log.debug(">>>>>> testSuperUserAuthentication()");
try {
String user = "administrator";
String password = "password1";
String newpassword = "password1";
Map<String, String> loginMap = new HashMap<String, String>();
boolean success = false;
// if user is 'administrator' and newpassword is not null & not empty then it's a change password :
if(user.equalsIgnoreCase("administrator") && newpassword!=null && !newpassword.equals("")){
// Remove the comment tag to test. The code are commented out to prevent creating password file when installing this lib (edit properties file first) :
//success = SuperUserAuthentication.changePwd(password,newpassword);
//temporary var value when install this lib :
success = true;
//log.debug("change superuser password : " + newpassword);
//JOptionPane.showMessageDialog(null, "Change superuser password done. Password located in /tmp/superuser.pwd");
}
// else : validate if password is already set or set password if password has not been set :
else{
// Remove the comment tag to test. The code are commented out to prevent creating password file when installing this lib (edit properties file first) :
//success= SuperUserAuthentication.validateOrSet(password);
//temporary var value when install this lib :
success = true;
//log.debug("validate / set superuser password : " + password);
//JOptionPane.showMessageDialog(null, "validate/set superuser password");
}
if(!success){
loginMap.put("message", "Invalid username or password");
Assert.assertTrue(false); // scenario : login must success
}
else {
loginMap.put("authenticatedUser", user);
}
loginMap.put("loggedin", Boolean.toString(success)); // store validate superuser result to map
// check whether login / not :
boolean loggedin = Boolean.parseBoolean(loginMap.get("loggedin"));
log.debug("is superuser logged in : " + loggedin);
Assert.assertTrue(loggedin);
// get authenticated user :
String authenticated_user = loginMap.get("authenticatedUser");
log.debug("authenticated superuser : " + authenticated_user);
//Assert.assertTrue(true);
}
catch (Exception e) {
e.printStackTrace();
}
}
/**
* List Wiki users test
*/
public void testListWikiUsers()
{
log.debug(">>>>>> testListWikiUsers()");
try {
Vector<HashMap<String, String>> result = WikiAuthentication.listUsers();
log.debug("wiki user count : " + result.size());
JOptionPane.showMessageDialog(null, "Wiki user count: "+result.size());
for (int i=0; i<result.size(); i++) {
HashMap<String, String> h = (HashMap<String, String>) result.get(i);
/*
log.debug(">>>>>>>>>> user_name : " + h.get("user_name"));
log.debug(">>>>>>>>>> user_real_name : " + h.get("user_real_name"));
log.debug(">>>>>>>>>> user_password : " + h.get("user_password"));
log.debug(">>>>>>>>>> user_email : " + h.get("user_email"));
*/
}
assertTrue( true );
}
catch (Exception e) {
e.printStackTrace();
assertTrue( false );
}
}
/**
* System authentication test
*/
public void testSystemAuthentication()
{
log.debug(">>>>>> testSystemAuthentication()");
log.debug("SystemAuthentication.isUserLoggedIn() : " + SystemAuthentication.isUserLoggedIn());
assertTrue( SystemAuthentication.isUserLoggedIn() );
//assertTrue( true );
}
}