code.cycling
code.cycling

Reputation: 1274

Angular Auth Guard secure routes

I'm trying to secure my routes by using auth-guard.

My problem is if the user is logged in. The user cant go to sign in/ sign up page and must redirect the user to default page.

routing.module.ts

const routes: Routes = [
 { path: '', component: LoginComponent },
 { path: 'signup', component: SignupComponent },
 { path: 'list-users', component: ListUsersComponent, canActivate: 
 [AuthGuardService] }
];

auth.guard.ts

if (!this.authService.isLoggedIn()) {
  this.router.navigate(['/']);
  console.log('go to login');
  return false;
}
console.log('has access');
return true;

I tried make the code look like this but i get an infinite loop.

if (!this.authService.isLoggedIn()) {
  this.router.navigate(['/']);
  console.log('go to login');
  return false;
} else {
  console.log('redirect when loggedin to list-users');
  this.router.navigate(['list-users']); // infinite loop
  return true;
}

Upvotes: 0

Views: 685

Answers (2)

msmani
msmani

Reputation: 720

Create two services

anonymous-guard.ts

if (!this.authService.isLoggedIn()) {
 this.router.navigate(['/']);
 return false;
} else {
 return true;
}

authenticated-guard-ts

if (this.authService.isLoggedIn()) {
   this.router.navigate(['list-users']);
   return false;
} else {
   retrun true;
}

then apply it to routes

const routes: Routes = [
 { path: '', component: LoginComponent,canActivate: 
 [AuthenticatedGuardService] },
 { path: 'signup', component: SignupComponent,canActivate: 
 [AuthenticatedGuardService] },
 { path: 'list-users', component: ListUsersComponent, canActivate: 
 [AnonymousGuardService] }
];

Upvotes: 1

terahertz
terahertz

Reputation: 3481

My problem is if the user is logged in. The user cant go to sign in/ sign up page and must redirect the user to default page.

You can simply check if user is accessing /login or /signup route (however you named it).

You have created an infinite loop because this.router.navigate(['list-users']); is recursively calling the auth guard, which in turns, executes the "else" block and navigates user back to list-users which calls auth-guard again and so on.

AuthGuard.ts

canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot){
  if (!this.authService.isLoggedIn()) { //user is not logged in
    this.router.navigate(['/']); //go to login
    return false;
  } else { //user is logged in

    if(state.url.indexOf("/login") > 0 || state.url.indexOf("/signup") > 0 ){ //check if logged in user is accessing /login or /signup path
      this.router.navigate('['list-users']');
      return false;
    }else{
      return true;
    }

  }
}

Upvotes: 1

Related Questions