Monday, May 21, 2007

asp.net 2.0 Login Control "Remember me" functionality example

const string IMASHOPS_LOGIN = "http://imashops.com/tv/";

protected void Page_Load(object sender, EventArgs e)
{
if (Request.Cookies[IMASHOPS_LOGIN] != null)
{
HttpCookie cookie = Request.Cookies.Get(IMASHOPS_LOGIN);
string sUserName = cookie.Values["login"].ToString();
string sPassword = cookie.Values["Pass"].ToString();

if (Authenticate(sUserName, sPassword))
{
Response.Redirect("~/Default.aspx");
}
else
{
LoginCtrl.UserName = sUserName;
}
}
}

private bool Authenticate(string sUsername, string sPassword)
{
UsersTableAdapter pta = new UsersTableAdapter();
Permissions.UsersDataTable udt = pta.Login(sUsername, sPassword);

bool bAuthenticated = (udt.Rows.Count == 1);

if (bAuthenticated)
{
UserRow = udt[0];
Permissions = upta.GetDataByUserID(UserRow.UserID);
}

return bAuthenticated;
}


protected void LoginCtrl_LoggedIn(object sender, EventArgs e)
{
CheckBox rm = (CheckBox)LoginCtrl.FindControl("RememberMe");

if (rm.Checked)
{
HttpCookie myCookie = new HttpCookie(IMASHOPS_LOGIN);
Response.Cookies.Remove(IMASHOPS_LOGIN);
Response.Cookies.Add(myCookie);
myCookie.Values.Add("login", LoginCtrl.UserName.ToString());
myCookie.Values.Add("pass", LoginCtrl.Password.ToString());
DateTime dtExpiry = DateTime.Now.AddDays(15);
Response.Cookies[IMASHOPS_LOGIN].Expires = dtExpiry;
}

if (UserRow.RoleID == (int)eRoles.Administrator)
Response.Redirect("~/Default.aspx");
}

protected void btnLogOut_Click(object sender, EventArgs e)
{
Session.Abandon();
HttpCookie cookie = Request.Cookies.Get(IMASHOPS_LOGIN);
// do not use Remove method to remove cookie. also Do not use DateTime.MinValue, they do not work
cookie.Expires = DateTime.Now.AddYears(-30);
Response.Cookies.Add(cookie);
Response.Redirect("~/Login.aspx");
}

asp:Login... .net 2.0 login control and Default page button

How to make Login button of control default on enter button
If your login control is defined like this:

asp:Login ID="LoginCtrl" runat="server" />


add this code to Page_Load handler


protected void Page_Load(object sender, EventArgs e)
{
Button btn = (Button)LoginCtrl.FindControl("LoginButton");
if (btn != null)
Page.Form.DefaultButton = btn.UniqueID;
}


Note: This works only if LoginButtonType is Button, if not this does not work