Tuesday, September 11, 2007

Remember me in javascript

Hi All,
Just i have developed one Logged in page which will store UserName and password in cookie. Many times (similar to Gmail) user have given the option of Remember me on this computer and user selects that check box and click logged in. Now when second times user hit the login page . After writing it UserName we are checking that user name in cookies. If present the password will get automatically added to password text box see the javascript code.

function readCookie(cookies)
{
var txtuname= document.getElementById('TxtBxUserName');
var txtpass= document.getElementById('TxtBxPassword');
//alert(document.cookie);
if (document.cookie.length>0)
{
// check the index of the username that is entered by user in Username text box
var c_start=document.cookie.indexOf(txtuname.value);
if (c_start!=-1)
{
c_start=c_start + txtuname.value.length +1 ;
var c_end=document.cookie.indexOf(";",c_start);
if (c_end==-1)
{
c_end=document.cookie.length;
}
var value= unescape(document.cookie.substring(c_start,c_end));
var arr = new Array(2);
arr= value.split('',2)
// alert(arr[0]+arr[1]) ;
txtuname.value=arr[0];
txtpass.value=arr[1];
}
else
{
txtpass.value="";
}
}
}

Now the At the server side check user authentications and authenticated user can store it's password


protected void LoggedIn_Click1(object sender, EventArgs e)
{ // do authentication
if(AuthenitcateUser())
// if the remember me check box ic checked
if (ChkBxRememberMe.Checked)
{ // create the cookie with userName as name
HttpCookie cookie = new HttpCookie(TxtBxUserName.Text);
// add cookie first to response
Response.Cookies.Add(cookie);
// add the user name and password as value
cookie.Values.Add("",TxtBxUserName.Text + "" + TxtBxPassword.Text + ";");
// this step is important remember it
Response.Cookies[TxtBxUserName.Text].Expires = DateTime.Now.AddDays(15);
}
}
}


Now call the javascript onfocus event of password textbox in page load



protected void Page_Load(object sender, EventArgs e)
{
TxtBxPassword.Attributes.Add("OnFocus", "javascript:readCookie('"+this.Request.Cookies+"');");
}