Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How not to show the login page for a logged in user in angular

I have an auth module and the routing auth module contains the following routes:

const authRoutes: Routes = [
    {
        path: 'sign-in', component: SignInComponent
    }
];

The dashboard routing module contains the following routes:

const dashboardRoutes: Routes = [
  { path: 'home', component: HomeComponent, canActivate: [IsAuthenticatedGuard] }
];

The app (root) routing module contains the following route configurations:

const appRoutes: Routes = [
  { path: '', redirectTo: 'home', pathMatch: 'full' },
  { path: '**', component: PageNotFoundComponent }
];

So when a user is logged in if he goes to the root, they get redirected to the home page, when not logged in they end up on the sign-in page which is the desired behaviour. However, when user is logged they can still go to the sign-in page and I think, in that case it makes sense to redirect the user to the home page, since they are logged in and don't need the sign in page.

I cannot do this in the IsAuthenticatedGuard because if I write something like:

@Injectable({
  providedIn: 'root'
})
export class IsAuthenticatedGuard implements CanActivate {
  private isSignedIn: boolean = true;

  constructor(
    private router: Router
  ) {}
  canActivate(
    next: ActivatedRouteSnapshot,
    state: RouterStateSnapshot): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree {
    if (this.isSignedIn) {
      // this.router.navigate(['home']);
      return true;
    } else {
      this.router.navigate(['sign-in']);
      return false;
    }
  }
}

Pay attention to the commented out line, it will stuck in an infinite loop which is pretty apparent. What would be the right way to achieve it?

EDIT:

The solution I can think of right now is add the redirection logic to the sign-in component, basically something like this:

  ngOnInit() {
    if (this.isSignedIn) {
      this.router.navigate(['home']);
    }
  }
like image 346
igor Avatar asked Dec 31 '22 13:12

igor


1 Answers

You can define a guard and add to your route as below:

@Injectable()
export class IsSignedInGuard implements CanActivate {
  // here you can inject your auth service to check that user is signed in or not
  constructor(private authService: AuthService,private router: Router) { }
  canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
    if (this.authService.isSignedIn()) {
      this.router.navigate(["/"]); // or home
      return false;
    }
    return true;
  }
}

Then in your routing:

const authRoutes: Routes = [
    {
        path: 'sign-in', component: SignInComponent , canActivate: [IsSignedInGuard]
    }
];

NOTE : You do not need to check in ngOnInit hook;

like image 87
AbolfazlR Avatar answered Jan 05 '23 16:01

AbolfazlR