0
votes

I am working on an Angular app where I have a login page in my dashboard component. I am showing a set of data in my table component. I have successfully blocked the table route which the user cannot access until he has logged in. What I want to do is that after the user has logged in in the dashboard component, I want to block the dashboard component so that the user cannot access the login section again until he has logged out, which is my third component. I have tried doing that below but it's not working. Here's my code:

admin-layout.routing.ts

export const AdminLayoutRoutes: Routes = [
{ path: 'dashboard', canActivate: [RoleGuard],     component: DashboardComponent },
{ path: 'user',           component: UserComponent },
{ path: 'table',  canActivate: [AuthGuard],        component: TableComponent },
{ path: 'icons',          component: IconsComponent }
];

auth-guard.service.ts //for the protection of my table component

constructor(private authService: AuthService, private router: Router){}

canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean
  {
   if(this.authService.isAuthenticated())
    {
      return true;
    }
    this.router.navigateByUrl('/dashboard');
    return false;
  }

role-guard.service.ts //for the protection of my dashboard component(login page)

constructor(private router: Router, private authService: AuthService){}

canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) : boolean
{
  if(this.authService.isNotAuthenticated)
  {
    console.log("role guard True cond."); //this gets printed on console always, even after I login

    return true;
  }
  console.log("role guard false cond.")
  this.router.navigateByUrl('/table');
  return false;
}

auth.service.ts //for defining the logic of the above two guards

 export class AuthService
 {
 loggedIn:boolean = false;

 check_Authentication(logIn : boolean)
 {
  if(logIn == true)
  {
    this.loggedIn = true;
  }
  else
  {
    this.loggedIn = false;
  }
 }

isAuthenticated()
{
 if(this.loggedIn == true)
 {
   return true;
 }
 else
 {
   return false;
 }
}

isNotAuthenticated()
{
 if(this.loggedIn != true)
 {
   return true;
 }
 else
 {
   return false;
 }
}

}

dashboard.component.ts //I am sending the variable as true if the user has logged in, here

private onAuthorization(form: NgForm)
{
  this.http.post('http://localhost:3000/auth', form.value, {responseType: "text"})
  .subscribe(responseData =>{
    console.log(responseData);
    if(responseData == "Successfully Authorized")
    {
      this.auth_check = true;
      this.authService.check_Authentication(this.auth_check);
      if(this.authService.isAuthenticated)
      {
        this.router.navigateByUrl('/table');
      }
    }
    else
    {
      this.auth_failed = true;
    }

  }
  ,error => {
    this.connectionToServer = false;
  });
  this.connectionToServer = true;
}

Can anybody tell me what am I doing wrong? EDIT: The login page isn't getting blocked after I navigate the user to the table page, which it should.

3

3 Answers

0
votes

I saw your code, you can use three helper methods and store the state of the user in localStorage on successful login, on logout remove the state(token). and the third one is getState(): boolean for determining the user state.

  1. set state on successfully log in
private saveState(token: string): void {
  localStorage.setItem('state', 'true');
  this.token = token;
}

2)Remove state on log Out and

logout(){
      localStorage.removeItem('token');
      this.router.navigate(['/login'])
}

3)Verify the user by its state and do your work on the basis of true and false response

 private getState(): boolean {
      let token = localStorage.getItem('state');
      if(token){
        return true;
      }
      else {
        return false;
      }
0
votes

I just checked your code, after you login you need to set a value into your localstorage that can be accessible from any service.

for example:

if(responseData === "Successfully Authorized")
{
    localStorage.setItem('loggedIn', true);
}

In your auth guard, you just need to check if the localstorage has value or not, it would be something like this

canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean
{
   let isLoggedIn = localStorage.getItem('loggedIn');
   if (isLoggedIn) {
      return true;
   }
   this.router.navigateByUrl('/dashboard');
   return false;
}

Need to do this in your Role Guard

canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) : boolean
{
  const isLoggedIn = localStorage.getItem('loggedIn');
  if(!isLoggedIn)
  {
    console.log("role guard True cond."); //this gets printed on console always, even after I login
    return true;
  }
  console.log("role guard false cond.");
  this.router.navigateByUrl('/table');
  return false;
}

Hopefully it helps. thanks

0
votes

I was making a simple mistake and it worked perfectly for me.

Everything remained the same except

role-guard.service.ts //for the protection of my dashboard component(login page)

constructor(private router: Router, private authService: AuthService){}

canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) : boolean
{
  if(this.authService.isNotAuthenticated()) //I was missing parenthesis in my function 
                                            //call here
  {
  console.log("role guard True cond."); //this gets printed on console always, even 
                                        //after I login

  return true;
  }
 console.log("role guard false cond.")
 this.router.navigateByUrl('/table');
 return false;
 }