C effectively prevents multiple logins of the same account (with three methods)

  • 2021-08-28 20:51:01
  • OfStack

This article first introduces how to use cache Cache to realize this function conveniently.
There is one difference between Cache and Session. Cache is a global object, and its scope is the whole application and all users.
Session is a user session object, which is a local object and is used to store the information of a single user.
As long as the user information after each user login is stored in Cache, the Key name of Cache is set as the user login name, the expiration time of Cache is set as the timeout time of Session, and whether Cache [user name] has a value is judged every time the user logs in. If there is no value, it proves that the user has not logged in, otherwise the user has logged in.
Let's give you an example.


/// <summary>
///  Prevent multiple logins 
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void Button1_Click(object sender, System.EventArgs e)
{
string strUser = string.Empty;
string strCacheKey = this.TextBox1.Text;

strUser = Convert.ToString(Cache[strCacheKey]);

if (strUser == string.Empty)
{
TimeSpan SessTimeOut = new TimeSpan(0, 0, System.Web.HttpContext.Current.Session.Timeout, 0, 0);

Cache.Insert(strCacheKey, strCacheKey, null, DateTime.MaxValue, SessTimeOut, CacheItemPriority.NotRemovable, null);
Session["User"] = strCacheKey;
this.Label1.Text = Session["User"].ToString();
}
else
{
this.Label1.Text = " This user has logged in! ";
}
}

I searched the Internet again and found two other solutions:
1. Judge whether the user has logged in through the database status bit.
2. Use session listener to monitor the login status of every logged-in user.
The first solution is very simple, but it needs to consider the situation that the user exits abnormally, such as closing the browser directly, etc., and its usability is low.
Next, it mainly introduces the implementation of the second scheme: using session listener to monitor the login situation of every logged-in user.
A. After the user logs in, first go to the database to inquire whether the login name exists and is locked. Under the condition that the login name exists and is not locked, take out all login information from the built-in scope object of application and check whether the login name has been logged in. If it is logged in, it will be friendly. On the contrary, it means that you can log in, and the login information is saved in application.
The main code is as follows:


//
// All login information 
Map<String, String> loginUserMap = (Map<String, String>) super.getApplicationAttr(Constant.LOGIN_USER_MAP);
boolean isExist = false;
String sessionId = super.getSessionId(false);
if(loginUserMap==null){
loginUserMap = new HashMap<String, String>();
}
for (String username : loginUserMap.keySet()) {
// Judge whether the information of the logged-in user has been saved and whether it is the same 1 Repeated login for users 
if(!username.equals(user.getFuUserName()) || loginUserMap.containsValue(sessionId)){
continue;
}
isExist = true;
break;
}
if(isExist){
// The user is logged in 
//
}else {
// The user is not logged in 
loginUserMap.put(result.getFuUserName(), sessionId);
//
}
//

B. After login is considered, consider exiting.
When a user logs out normally, we need to remove the user's login information from session. We can write an Session listener. When listening for the destruction of sessioon, we log off the logged-in user, that is, remove it from application. Indicates that the user is offline.

The main code is as follows:


//
public void sessionDestroyed(HttpSessionEvent event) { 
  //  
  // In session At the time of destruction   Put loginUserMap Clear the key-value pairs saved in  
  User user = (User)event.getSession().getAttribute("loginUser"); 
  if(user!=null){ 
    Map<String, String> loginUserMap = (Map<String, String>)event.getSession().getServletContext().getAttribute("loginUserMap"); 
    loginUserMap.remove(user.getFuUserName()); 
event.getSession().getServletContext().setAttribute("loginUserMap",loginUserMap); 
  } 
  //
} 
//

In addition, there is another problem, if the logged-in user suddenly closes the browser without clicking the exit button. Then you can use the beforeunload event to trigger when the browser refreshes or closes.


// Events called on refresh or shutdown 
$(window).bind('beforeunload',function(){
 $.ajax({
  url:"${ctx}/system/user/user!logout.action",
  type:"post",
  success:function(){
   alert(" You have been logged out ");
  }
 });
});

In this way, the requirements are basically realized.
You can use the above code to their own project, test 1, effectively prevent the same account repeat login, I hope you like these methods.


Related articles: