4
votes

This is my router guard for my angular project. Basically in my system i have many user roles. In the guard i check on the userProfile node if the user isLawyer and isLawyerApproved. If these conditions are true, the lawyer can access to the route. in the canActivate function i return this.loggedin && this.isApproved. In my login component i have a ngOnit function that checks if the user is already logged and if is, redirects to the /dashboard route. Actually, that does not working, I want that if an authenticated user visits the login page, automatically be redirected to the /dashboard. Please help me

class MyGuardService implements CanActivate{
  loggedIn = false;
  isApproved:boolean;

  constructor(private authService:AuthService, private router:Router){
    this.authService.isLogged().subscribe((response)=>{
      if(response && response.uid){
        this.loggedIn = true;
        this.authService.getUserProfile(response.uid).valueChanges()
          .subscribe(
             (userProfile:UserProfile)=>{
                if(userProfile.isLawyer && userProfile.isLawyerApproved){
                   this.isApproved = true;
                }
             }
           )
        }else{
          this.loggedIn = false
        }
      }, (error)=>{
      this.loggedIn = false;
    })
  }

  canActivate(route:ActivatedRouteSnapshot, state:RouterStateSnapshot):Observable<boolean>|Promise<boolean>|boolean {
    console.log('El abogado es aprobado??')
    console.log(this.isApproved)
    if(!this.loggedIn){
      this.router.navigate(['/abogado-login']);
    }
    return (this.loggedIn && this.isApproved)
  }
}

// LoginComponent

ngOnInit() {
  this.authService.isLogged().subscribe((result)=>{
    if(result && result.uid){
      console.log('Estoy logueado debo redirigir');
      this.router.navigate(['/abogado'])
    }
  })
}
1

1 Answers

4
votes

In your gaurd just add redirection by improting router on success of login true or what ever your condition and place that gaurd on login route in router module.

constructor(private authService:AuthService, private router:Router){
  this.authService.isLogged().subscribe((response)=>{
  if(response && response.uid){
  this.loggedIn = true;

  this.authService.getUserProfile(response.uid).valueChanges()
  .subscribe(
   (userProfile:UserProfile)=>{
    if(userProfile.isLawyer && userProfile.isLawyerApproved){
     this.isApproved = true;
     this.router.navigate(['/addroutewhereusershouldgowhenapproved']);
    } else {
     this.router.navigate(['/abogado']);
   }
  )
}else{
 this.loggedIn = false
}
}, (error)=>{
 this.loggedIn = false;
})

In router module add gaurd on route path something similar below.

{ path:'', component: LoginComponent, canActivate: [AuthGuard]}