Authguard doesn’t work, what to do?

Asked

Viewed 200 times

0

If my user is logged in, he can access any route of my application and if he tries to access the route ' ' (empty) will be redirected to Dashboard, if it is unattended will only be redirected to ' ' (empty)

the problem is that with my logged-in user I can access the route ' ' (empty) which is where I type my login, but my user is already logged in, where I am errandow

    canActivate(
        route: ActivatedRouteSnapshot,
        state: RouterStateSnapshot): boolean | Observable<Boolean> | Promise<boolean> {
           if(!this.userService.isLogged()){
            this.router.navigate([''])
            console.log('Vai fazer login!') 
           }
            return true;
        }

}

1 answer

0

Maybe you need two different guardians. One in case the user is already logged in and the other case is not yet logged in.

Here I go like this, maybe I’ll help you:

export class AuthGuard implements CanActivate {

  constructor(private router: Router){}

  canActivate(
    route: ActivatedRouteSnapshot,
    state: RouterStateSnapshot): Observable<boolean> | boolean {
      if(localStorage.getItem('token') != null){ //Se tiver token permite acessar a dash
        return true;
      }else{
      this.router.navigate(['/login']);
        return false;
    }
  }
}

Guard if not yet logged in:

@Injectable() 
export class LoginGuard implements CanActivate {

  constructor(private router: Router){}

  canActivate(
    route: ActivatedRouteSnapshot,
    state: RouterStateSnapshot): Observable<boolean> | boolean {
      if(localStorage.getItem('token') == null){ //caso o usuário ainda não tiver token(ainda não logou), permite acesso a tela de login, caso contrário é redirecionado para a home em caso de tentar acessar a rota de login já estando na home
        return true;
      }else{
        this.router.navigate(['dash/home']);
        return false;
    }
  }
}

Routes of my Dash:

{
    path: 'dash',
    component: HomeComponent,
    canActivate:[AuthGuard],
    children: []...
 }

Login routes:

const routes: Routes = [
  {
    path: '',
    redirectTo: 'login'
  },
  {path: 'login', loadChildren: 'src/app/components/entrar-app/login/login.module#LoginModule', canActivate:[LoginGuard] },
  {path: 'registrar', loadChildren: 'src/app/components/entrar-app/registrar/registrar.module#RegistrarModule', canActivate:[LoginGuard] },
  {path: 'recuperarsenha/:token', component: CallbackrecuperacaosenhaComponent}
];
  • For each route I want to protect I need to create a file of Guard?

  • No, it only takes two Guards. A Guard in case the user is already logged in, allow access to home and if trying to go pro login direct to home. And one that does the opposite, in case you are not yet logged in and try to access the home route to login. I advise you to modularize your routes (if you’re not already doing it) so you can apply Lazy loading

  • I can share my project on github with you ?

  • Yes, but I can only see the night

  • Pass me your user in git, please, and thank you so much for the help :)

  • my github: veronesecoms

  • Tks, invitation sent!

  • the way you’re doing there the browser crashes because it’s in an infinite loop

Show 4 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.