Tuesday, 26 January 2016

Prevent simultaneous logins by a single User ID


You can prevent simultaneous logins by a single User ID.
Use the below coding in your c# web application.
in Login.aspx 
function ShowErrorMsg() 
{
   Alert(document.getElementById("hdnMsg").value); 
}
<input type="hidden" runat="server" id="hdnMsg" /> 
in Login.aspx.cs
private bool isAlreadyLogged(string sUserId, string sPwd)
{
       string sKey = sUserId + sPwd;
       string sUser = Convert.ToString(Cache[sKey]);
       if (sUser == null || sUser == String.Empty)             
       {
           // No Cache item, so session is either expired or user is new sign-on
           // Set the cache item and Session hit-test for this user---
           TimeSpan SessTimeOut = new TimeSpan(0, 0, HttpContext.Current.Session.Timeout, 0, 0);
           HttpContext.Current.Cache.Insert(sKey, sKey, null, DateTime.MaxValue, SessTimeOut, System.Web.Caching.CacheItemPriority.NotRemovable, null);
           Session["LoginInfo"] = sUserId + sPwd;
           return false;
        }
        else
           return true;
} 
protected void btnLogin_Click(object sender, EventArgs e)
{
     if ("Password is correct")
     {  // After checking Login Credentials validation against your DB
        if (isAlreadyLogged(sUserId, sPwd))
        {
             hdnMsg.Value = "User already Logged IN, through other browser/machine. ";
             ClientScript.RegisterStartupScript(GetType(), "Msg1", "ShowErrorMsg();", true);
        }
        else
        {
             Response.Redirect("Index.html", false);
        }
        }
}
else
{
     hdnMsg.Value = "User Id or Password not valid!.";
     ClientScript.RegisterStartupScript(GetType(), "Msg1", "ShowErrorMsg();", true);
}
in Logout.aspx.cs 
protected void Page_Load(object sender, EventArgs e)
{
     Cache.Remove(Session["LoginInfo"].ToString());

     Session["LoginInfo"] = "";
     Session.Abandon();
     Session.Clear();
}
in Index.aspx (Main Page)
If user close the browser by clicking on ‘X’ button then our Logout page should call, Then only the Cache will erase and the same user can login again, otherwise Cache will not allow the user to login again. For that purpose,
Note: Make sure to allow popup blocker.
<script language="Javascript" type="text/javascript">
function GotoLogout() {
    window.open('Logout.aspx', 'mywindow', 'location=1,status=1,scrollbars=1, width=1,height=1');           
}
</script>
<body onbeforeunload="GotoLogout();">