Search code examples
angulartypescriptangular6angular-route-guards

if first user already login, how to prevent second user login on another tab


I am trying to prevent multiple simultaneous logins where if first user already login, it will prevent second user from login on another tab, i need advice on what should I need to do, based on google, i can use localstorage and authguard, and had implemented both but not solve the problem,

authentication.service.ts

isUserAuthenticated(): boolean {
    const user = localStorage.getItem(appConstant.currentUser);
    return user != null;
}

login.component.ts

ngOnInit(): void {
if (this.authenService.isUserAuthenticated()) {
  this.router.navigate([UrlConstants.UserSetting])
 }
}

when first user already login, open the second tab by paste login Url, it work, login will redirect to user setting, but when login page have been ready for both tab, when the first user login, the second user also can login using different account.


Solution

  • when you are setting the data to localStorage we need to check is there any user already in logged in.

    isUserAuthenticated(): boolean {
      if(localStorage.getItem(currentUser) != null)    
           return true;
      else {
         localStorage.setItem('currentUser',user);
           return false;
        }
      }
    

    i think this will solve your issue :)