Signing in automatically with a cookieAaaah, cookies. Love 'em or hate 'em? Most developers love them since we understand their limitations and realize that by themselves they can't share your SSN and Visa number with the world.For my site I wanted to allow the member to stay "signed in" by storing a cookie that contained their email and password, then looking for that whenever they visit the site. Big Important Note: As mentioned above, security isn't an issue on my site. In real life, storing a password in a cookie would be suicidal. The automatic sign in was implemented in IsLoggedIn( ) - the function incompletely discussed above. The real code is shown below ( I lied before!): // am I logged in?
if ( ! ( bLoggedIn = Session ( 'Authenticated' ) ) )
{
// no, so try to get data from cookie
if ( "" != Request.Cookies ( sCookieEmail ) )
{
// yes I have a cookie...
var sEmail = "" + Request.Cookies ( sCookieEmail );
var sPassword = "" + Request.Cookies ( sCookiePassword );
//..so act as though they have just entered it
bLoggedIn = ValidateLogin ( sEmail, sPassword, true );
}
}
|
So, if a cookie exists the data is sent into ValidateLogin( ) just as though it was typed into the form. Hey Presto! The cookie is created in ValidateLogin( ), as below, with an expiry date 1 year hence: Response.Cookies ( sCookieEmail ) = sEmail;
Response.Cookies ( sCookiePassword ) = sPassword;
// get a date 1 year in the future
var d = new Date;
var sDate = d.getDate ( ) + '/' + (d.getMonth ( ) + 1) + '/' + (d.getFullYear ( ) + 1);
Response.Cookies ( sCookieEmail ).Expires = sDate;
Response.Cookies ( sCookiePassword ).Expires = sDate;
|
Lastly, the cookie is erased whenever a sign in fails, or when the member signs out. function KillLoginCookies ( )
{
Response.Cookies ( sCookieEmail ) = '';
Response.Cookies ( sCookieEmail ).Expires = '01 jan 1980';
Response.Cookies ( sCookiePassword ) = '';
Response.Cookies ( sCookiePassword ).Expires = '01 jan 1980';
}
|
Part 5: Forgotten passwords... |