<%@ page import = "com.eg.EgCrypt"%>
<%@ page import = "com.eg.EgConMonHelper"%>
<%@ page import = "com.eg.IniFile"%>
<%@ page import = "com.eg.EgInstallInfo"%>
<%@ page import = "com.eg.EgConfigFilesSync"%>
<%@ page import="egurkha.EgDBConnectUI"%>
<%@ page import="com.egurkha.admin.AuditLogThread"%>
<%@ page import = "java.util.*"%>
<%@ page import="java.net.InetAddress"%>
<%@ page import="java.sql.*"%>

<%@ taglib prefix = "egui" uri="../WEB-INF/eg-taglib.tld"%>

<%
	response.setHeader("Cache-Control","no-store");
	response.setHeader("Pragma","no-cache");
	response.setDateHeader("Expires", -1);

	String tool = "smpwd";
	String sessionInUse = request.getParameter("sessionInUse");
	String pwd = request.getParameter("pwd");
	String authenticated = (String)session.getAttribute("authenticated");
	
	if (authenticated == null)
	{
		// Direct access from the browser address bar or from inside the toolkit via the tool
		if (pwd == null)
		{
			if (sessionInUse == null)
			{
				response.sendRedirect(request.getContextPath()+"/toolkitlogin?comeFrom="+tool+"&tools="+tool);
			}
			else
			{
%>
				<script>
					window.parent.location.href ="/final/toolkitlogin";
				</script>
<%
			}
		}
		else
		{
			// Direct access from the browser address bar
			if (!pwd.equals(EgConMonHelper.executePwd))
			{
				response.sendRedirect(request.getContextPath()+"/toolkitlogin?comeFrom="+tool+"&tools="+tool);
			}
			else
			{
				session.setAttribute("reqFromForTk","smpwd");
				session.setAttribute("validate_tools","true");
				session.setAttribute("tools",tool);
				String redirectURL = request.getContextPath()+"/toolkit";
				response.sendRedirect(redirectURL);
			}
		}
	}
	else
	{
		// Direct access from the browser address bar and session in use
		if (sessionInUse == null)
		{
			session.setAttribute("validate_tools","true");
			session.setAttribute("tools",tool);
			response.sendRedirect(request.getContextPath()+"/toolkit");
		}
	}
	session.setAttribute("treeViewSrc","smpwd");
	session.setAttribute("reqFromForTk","smpwd");

	String operation = request.getParameter("operation");
	String password = request.getParameter("newpwd");
	String label_msg = null;

	String supermanager_ini_file = EgInstallInfo.getInstallDir()+"/manager/config/eg_supermanager.ini";
	IniFile supermanager_ini = new IniFile(supermanager_ini_file);
	String existing_smpwd = EgCrypt.decrypt(supermanager_ini.getValue("SM_USER_LOGIN","SMPASS"));
	supermanager_ini = null;
	if(operation != null && operation.equalsIgnoreCase("changepwd") && password != null && (password=password.trim()).length()>0)
	{
		Connection conn = null;
		Statement stmt = null;
		EgDBConnectUI dbconnect = new EgDBConnectUI();
		int update = 0;
		try
		{
			String s_query = "update user_info set user_pass='"+EgCrypt.encrypt(password)+"' where user_id='egsm'";
			conn = dbconnect.getConnection();
			stmt = conn.createStatement();
			update = stmt.executeUpdate(s_query);
		}
		catch(Exception e)
		{
			e.printStackTrace();
			dbconnect.changeConn();
			label_msg = "Error!|egsm password does not updated!";
		}
		finally
		{
			try
			{
				if(stmt != null)
					stmt.close();
				dbconnect.releaseConnection();
			}
			catch(Exception e1)
			{
				e1.printStackTrace();
			}
			stmt=null;
		}
		if(update != 0)
		{
			supermanager_ini = EgConfigFilesSync.getInstance(supermanager_ini_file);
			supermanager_ini.setValue("SM_USER_LOGIN","SMPASS",EgCrypt.encrypt(password));
			supermanager_ini.saveFile();
			EgConfigFilesSync.releaseInstance(supermanager_ini);
			label_msg = "Success!|egsm password has been updated successfully.";
			InetAddress inetAddress = InetAddress.getLocalHost();
			AuditLogThread auditLogThread = new AuditLogThread();
			auditLogThread.setValue("Category","Admin");
			auditLogThread.setValue("User_id","egsm");
			auditLogThread.setValue("Host_ip",inetAddress.getHostAddress());
			auditLogThread.setValue("Session_id",session.getId());
			auditLogThread.setValue("Module","User Profile");
			auditLogThread.setValue("Activity","Update Profile");
			auditLogThread.setPreviousValue("Password","*****");
			auditLogThread.setCurrentValue("Password","******");
			auditLogThread.setValue("Description","egsm user password has been modified from toolkit");
			auditLogThread.sendItToDB();
		}
	}

	int pass_length = 0;
	int pwdComplexityCount = 0;
	boolean isDouble = com.eg.EgDbInfo.doubleByteEnabled;

	IniFile egUI = new IniFile(EgInstallInfo.getInstallDir()+ "/manager/config/eg_ui.ini");
	String pwdLength = egUI.getValue("MISC_ARGS","PwdMinLen");
	if(pwdLength != null && pwdLength.trim().length()>0)
	{
		pass_length = Integer.parseInt(pwdLength); 
	}
	String pwdComplexity = egUI.getValue("MISC_ARGS","PwdComplexity");
	if(pwdComplexity != null && pwdComplexity.length()>0)
	{
		StringTokenizer pwdComplexStrTknzr = new StringTokenizer(pwdComplexity,",");
		pwdComplexityCount = pwdComplexStrTknzr.countTokens();
	}

	if (pass_length < 2)
	{
		pass_length = 8;
	}
	else if(pass_length < pwdComplexityCount)
	{
		pass_length = pwdComplexityCount;
	}
%>

<html>
<head>
<script language="javascript" src="/final/admin/eg_scripts/timeout.js"></script>
<script language="javascript1.2" src="eg_scripts/validate.js"></script>
<script src="/final/jquery/jquery.js"></script>

<script language="JavaScript">
var pass_length = parseInt('<%=pass_length%>');
var pass_CompCount = parseInt('<%=pwdComplexityCount%>');
var labelMsg = '<%=label_msg%>';
var focusOnNewPwd = true;

var password = "<egui:intnl text='admin.profile.Please enter the new password'/>.";
var cpwd = "<egui:intnl text='admin.profile.Please enter the confirm new password'/>.";
var pwdmatch = "<egui:intnl text='admin.profile.Passwords does not match'/>.";
var dblquts = "<egui:intnl text='admin.profile.Double quotes not allowed'/>.";
var pwdlength = "<egui:intnl text='admin.user.Password length should be greater than one'/>.";
var userpassMsg = '<egui:intnl text="admin.user.Password cannot be same as user name"/>.';
var passLabel1 = '<egui:intnl text="admin.user.Password should contain atleast"/>';
var passLabel2 = '<egui:intnl text="admin.user.characters"/>';
var passStr = '<egui:intnl text="admin.user.Password strength"/>';

var existingpassMsg = '<egui:intnl text="admin.user.New password cannot be same as existing password"/>.';
var alertForPwdComplexity1 = '<egui:intnl text="admin.user.a lowercase alphabet"/>';
var alertForPwdComplexity2 = '<egui:intnl text="admin.user.an uppercase alphabet"/>';
var alertForPwdComplexity3 = '<egui:intnl text="admin.user.a number"/>';
var alertForPwdComplexity4 = '<egui:intnl text="admin.user.a special character other than double quotes"/>.';
var alertForPwdComplexity5 = '<egui:intnl text="admin.user.Password policy requirements are not satisfied"/>';
var pwdbyte = "<egui:intnl text='admin.user.Password is not allowed in DBL(Chinese,Korean,Japanese),since manager is SingleByte'/>.";


function pwdComplexityCheck(newPassword)
{
	var _start = "^";
	var _mid = "";
	var _end = ".+$";
	var result = "";
	var dot = ".";
	var brk = "<br/>";
	var pwdComplexity = '<%=pwdComplexity%>';
	if(pwdComplexity != null && pwdComplexity != undefined)
	{
		if(pwdComplexity.indexOf(",") > -1)
		{
			result = "false#";
			var pwdComplexVal = pwdComplexity.split(",");
			for(var k=0; k<pwdComplexVal.length; k++)
			{
				var temp = pwdComplexVal[k].toLowerCase().trim();
				if(temp == "lc")
				{
					_mid += "(?=.*[a-z])";
					result += brk+(k+1)+dot+" "+alertForPwdComplexity1;
				}
				else if(temp == "uc")
				{
					_mid += "(?=.*[A-Z])";
					result += brk+(k+1)+dot+" "+alertForPwdComplexity2;
				}
				else if(temp == "dg")
				{
					_mid += "(?=.*[0-9])";
					result += brk+(k+1)+dot+" "+alertForPwdComplexity3;
				}
				else if(temp == "sp")
				{
					_mid += "(?=.*[^0-9a-zA-Z])";
					result += brk+(k+1)+dot+" "+alertForPwdComplexity4;
				}
			}
		}
		else
		{
			result = "false#";
			var temp = pwdComplexity.toString().toLowerCase().trim();
			if(temp == "lc")
			{
				_mid += "(?=.*[a-z])";
				result +=  alertForPwdComplexity1;
			}
			else if(temp == "uc")
			{
				_mid += "(?=.*[A-Z])";
				result +=  alertForPwdComplexity2;
			}
			else if(temp == "dg")
			{
				_mid += "(?=.*[0-9])";
				result +=  alertForPwdComplexity3;
			}
			else if(temp == "sp")
			{
				_mid += "(?=.*[^0-9a-zA-Z])";
				result +=  alertForPwdComplexity4;
			}
		}
		var regExp = new RegExp(_start + _mid + _end);
		if(regExp.test(newPassword))
		{
			result = "true";
		}
	}
	return result;
}

function updatePassword()
{
	var new_pwd = $("#smpwd").val();
	var confirm_pwd = $("#csmpwd").val();
	var pwdComplexity = pwdComplexityCheck(new_pwd);
	if(!isEmpty(labelMsg))
		labelMsg = "";
	if (isEmpty(new_pwd)) 
	{
		focusOnNewPwd = true;
		showDisplayMsg('Error!',password);
		return;
	}
	else if (new_pwd.trim().toLowerCase() == 'egsm')
	{
		focusOnNewPwd = true;
		showDisplayMsg('Error!',userpassMsg);
		return;
	}
	else if (isEmpty(confirm_pwd))
	{
		focusOnNewPwd = false;
		showDisplayMsg('Error!',cpwd);
		return;
	}
	else if (new_pwd != confirm_pwd)
	{
		focusOnNewPwd = false;
		showDisplayMsg('Error!',pwdmatch);
		return;
	}
	else if('<%=existing_smpwd%>' == new_pwd)
	{
		focusOnNewPwd = true;
		showDisplayMsg('Error!',existingpassMsg);
		return;
	}
	else if (new_pwd.length < pass_length)
	{
		focusOnNewPwd = true;
		showDisplayMsg('Error!',passLabel1+" "+pass_length+" "+passLabel2);
		return;
	} 
	else if(pwdComplexity.indexOf("false") > -1)
	{
		focusOnNewPwd = true;
		var resMsg = pwdComplexity.substring(pwdComplexity.indexOf("false#")+6);
		showDisplayMsg('Error!',alertForPwdComplexity5+". "+passLabel1+" "+resMsg+".");
		return;
	}
	else if(new_pwd.indexOf("\"") >-1)
	{
		focusOnNewPwd = true;
		showDisplayMsg('Error!',dblquts);
		return;
	}
	else if ('<%=isDouble%>' == "false" && !validateSingleByte(new_pwd))
	{
		focusOnNewPwd = true;
		showDisplayMsg('Error!',pwdbyte);
		return;
	}
	var thisForm = document.ChangeSmPwd;
	thisForm.action="/final/admin/EgChangeSmPwd.jsp?sessionInUse=true&fromToolKit=fromToolKit&operation=changepwd&newpwd="+new_pwd;
	thisForm.submit();
}

function passStrength(value)
{
	var regExp = /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[^\da-zA-Z]).+$/;
	var regExp2 = /^(?=.*\d)(?=.*[a-zA-Z])(?=.*[^\da-zA-Z]).+$/;
	var regExp3 = /^(?=.*\d)(?=.*[a-zA-Z]).+$/;
	var msg = "";
	var result = true;
	if (value.length >= pass_length && regExp.test(value))
	{
		msg = passStr+': <span style="color:green">Strong</span>';
	}
	else if(value.length >= pass_length && value.match(regExp2))
	{
		msg = passStr+':  <span style="color:green">Good</span>';
	}
	else if(value.length >= pass_length && value.match(regExp3))
	{
		msg = passStr+': <span style="color:#D35400">Fair</span>';
	}
	else if (isEmpty(value))
	{
		msg = '<span style="color:red">Password should not be blank!</span>';
		result = false;
	}
	else
	{
		msg = passStr+': <span style="color:red">Weak</span>';
		result = false;
	}
	$("#label_smpwd").css('color','black');
	$("#label_smpwd").html(msg);
	return result;
}

function lengthPassword(value)
{
	if(value == undefined)
	{
		value = $("#smpwd").val();
	}
	if(value.length >= pass_length)
	{
		$("#label_smpwd").html('');
		return;
	}
	var msg = 'Password should contain at least '+pass_length+' characters';
	if(isEmpty(value))
		msg = 'Password should not be blank!';
	$("#label_smpwd").css('color','red');
	$("#label_smpwd").html(msg);
}

function matchPassword(value)
{
	var smpwd = $("#smpwd").val();
	if(isEmpty(smpwd) || isEmpty(value))
	{
		$("#label_csmpwd").css('color','red');
		$("#label_csmpwd").html('Password should not be blank!');
		return;
	}
	if(smpwd != value)
	{
		$("#label_csmpwd").css('color','red');
		$("#label_csmpwd").html('Password does not match!');
		return;
	}
	else
	{
		$("#label_csmpwd").css('color','green');
		$("#label_csmpwd").html('Password matched');
		return true;
	}
}

function lengthOnfocus(value)
{
	$("#alertMsg").css("display","none");
	if(!isEmpty(value))
		return;
	$("#label_smpwd").css('color','black');
	$("#label_smpwd").html(passLabel1+' '+pass_length+' '+passLabel2);
}

function isEmpty(val)
{
	return (val == null || val =='null' || val == '' || val.trim().length == 0);
}

function showDisplayMsg(msgHeader,msgBody)
{
	$("#label_smpwd").html('');
	$("#label_csmpwd").html('');
	$("#alertMsg").css("display","block");
	$("#displayLabel").html("<b style='color:white;font-size:20px'>"+msgHeader+"</b> "+msgBody);
}

function autoFocus()
{
	if(!isEmpty(labelMsg))
		return;
	if(focusOnNewPwd)
		$("#smpwd").focus();
	else
		$("#csmpwd").focus();
}

</script>
<link rel="stylesheet" href="eg_styles\adminstyle_blue.css"/>
<style>
.alert {
  padding: 30px 60px;
  margin:50px 60px 30px 60px;
  background-color: #BFC9CA;
  display:none;
}
.closebtn {
  margin-left:15px;
  margin-right: 5px;
  margin-top: 5px;
  color: white;
  font-weight: bold;
  float: right;
  font-size: 22px;
  line-height: 20px;
  cursor: pointer;
  transition: 0.3s;
}
.closebtn:hover {
  color: black;
}
.display-label{
	margin-right:10px;
	font-size:14px;
	text-align: justify;
	text-justify: inter-word;
}
</style>
</head>

<body style="overflow:auto" id="space6" >
<form name="ChangeSmPwd" method="POST" style="margin:0px">
<table align="center" cellspacing="0" cellpadding="0" width="100%" border="0">
	<tr>
		<td id="eg_blankspace" height="10" nowrap>&nbsp;</td>
	</tr>
	<tr>
		<td width="100%" height="24" id="eg_title" align="center"> &nbsp;Change egsm Password</td>
	</tr>
	<tr>
		<td height="20" align="center">
			<table align="center" width="85%" cellspacing="0" cellpadding="4" border="0">
				<tr>
					<td height="24" nowrap align="right" width="35%" class="eg_cellbglits"><img src="/final/admin/eg_images/info2.gif"> </td>
					<td height="24" nowrap align="left" class="eg_cellbglits">This page enables the administrator to change the egsm password.</td>
				</tr>
			</table>
		</td>
	</tr>
	<tr>
		<td id="eg_blankspace" height="10" nowrap></td>
	</tr>
	<tr>
		<td width="100%" id="eg_whitebg" align="center" height="100%" valign="top">
			<table align="center" width="80%" cellspacing="0" cellpadding="0" border="0">
				<tr>
					<td id="eg_blankspace" height="5" nowrap>&nbsp;</td>
				</tr>
				<tr>
					<td width="100%" valign="top" align="center" class="eg_cellbglits">
						<table align="center" width="100%" cellspacing="0" cellpadding="2" border="0" class="eg_subcontentbg">
							<tr class="eg_cellbglits" height="10">
								<td  colspan="8"></td>
							</tr>
							<tr class="eg_cellbglits">
								<td class="form_spacing" style="width:2%"></td>
								<td style="width:15;"><egui:intnl text="admin.user.New Password"/></td>
								<td class="form_spacing" style="width:10%">&nbsp;:&nbsp;</td>
								<td style="width:25%;"><input type="password" name="smpwd" id="smpwd" oninput="javascript:passStrength(this.value)" onchange="javascript:lengthPassword(this.value)" onfocus="javascript:lengthOnfocus(this.value)" style="width:250px" oncopy="return false"></td>
								<td style="width:40%;">&nbsp;<label style="border:0px solid green" id="label_smpwd"></label></td>
							</tr>
							<tr class="eg_cellbglits">
								<td class="form_spacing" style="width:2%"></td>
								<td style="width:15;"><egui:intnl text="admin.user.Confirm New Password"/></td>
								<td class="form_spacing" style="width:10%">&nbsp;:&nbsp;</td>
								<td style="width:25%;"><input type="password" name="csmpwd" id="csmpwd" style="width:250px" oninput="javascript:matchPassword(this.value)" onfocus="javascript:lengthPassword()" onpaste="return false"></td>
								<td style="width:40%;">&nbsp;<label style="border:0px solid green" id="label_csmpwd"></label></td>
							</tr>
							<tr class="eg_cellbglits" height="10">
								<td  colspan="8"></td>
							</tr>
						</table>
					</td>
				</tr>
				<tr>
					<td id="eg_blankspace" height="5" nowrap>&nbsp;</td>
				</tr>
				<tr>
					<td align="center" valign="top">
						<table align="center" width="100%" cellspacing="0" cellpadding="0" border="0" class="eg_subcontentbg">
							<tr>
								<td colspan="6" align='center' id="eg_whitebg" nowrap>
									<input type="button" style="cursor:pointer" name="update" id="eg_back" value="Update" onClick="javascript:updatePassword();">
								</td>
							</tr>
						</table>
					</td>
				</tr>
			</table>
		</td>
	</tr>
</table>
<div class="alert" id="alertMsg">
	<table width="100%">
		<tr>
			<td><div id="displayLabel" class="display-label"></div></td>
			<td><span class="closebtn" onclick="$('#alertMsg').css('display','none');autoFocus();">&times;</span></td>
		</tr>
	</table>
</div>
</form>
<script>
if(!isEmpty(labelMsg))
{
	var idx = labelMsg.indexOf("|");
	showDisplayMsg(labelMsg.substring(0,idx),labelMsg.substring(idx+1));
}
</script>
</body>
</html>



