I am developing a website where in user is required to login to the system to be able to use it. The current functionality is: When user enters username and password, a check is
This is how I managed to do it with the help of link provided by @Satinder singh
.
Global.asax.cs
protected void Application_Start(object sender, EventArgs e)
{
Application["UsersLoggedIn"] = new System.Collections.Generic.List();
}
protected void Session_End(object sender, EventArgs e)
{
// NOTE: you might want to call this from the .Logout() method - aswell -, to speed things up
string userLoggedIn = Session["UserLoggedIn"] == null ? string.Empty : (string)Session["UserLoggedIn"];
if (userLoggedIn.Length > 0)
{
System.Collections.Generic.List d = Application["UsersLoggedIn"]
as System.Collections.Generic.List;
if (d != null)
{
lock (d)
{
d.Remove(userLoggedIn);
}
}
}
}
Login.aspx.cs
protected bool Login(string userId)
{
System.Collections.Generic.List d = Application["UsersLoggedIn"]
as System.Collections.Generic.List;
if (d != null)
{
lock (d)
{
if (d.Contains(userId))
{
// User is already logged in!!!
string userLoggedIn = Session["UserLoggedIn"] == null ? string.Empty : (string)Session["UserLoggedIn"];
if (userLoggedIn == user_id)
{
Session["UserLoggedIn"] = user_id;
return true;
}
else
{
return false;
}
}
else
{
string userLoggedIn = Session["UserLoggedIn"] == null ? string.Empty : (string)Session["UserLoggedIn"];
if (userLoggedIn != user_id)
{
d.Add(userId);
}
}
}
}
Session["UserLoggedIn"] = userId;
return true;
}
With above code, I am allowing any user to be logged in at any time only once. I used session variable to check if the request is from same browser, if so, I am allowing him/her to login else throwing a message "You are already logged in from another system".