0
I have the following authentication logic
initAuthListener() {
this.afAuth.authState.subscribe(user => {
if (user) {
this.store.dispatch(new Auth.SetAuthenticated());
this.router.navigate(['/training']);
} else {
this.trainingServices.cancelSubscriptions();
this.store.dispatch(new Auth.SetUnauthenticated());
this.router.navigate(['/login']);
}
});
}
How the.Component app was
ngOnInit(): void {
this.authService.initAuthListener();
}
Every first call on the page went to /login, so I passed the check to training.Component, which is where you need to get authorization.
Is it a bad practice? What would be my alternative?
I modified it this way, apparently it’s okay:
initAuthListener() {
this.afAuth.authState.subscribe(user => {
if (user) {
this.store.dispatch(new Auth.SetAuthenticated());
this.router.navigate(['/training']);
} else {
if((this.ROTAS_LIBERADAS.includes(this.router.url))){
this.trainingServices.cancelSubscriptions();
this.store.dispatch(new Auth.SetUnauthenticated());
}else{
this.trainingServices.cancelSubscriptions();
this.store.dispatch(new Auth.SetUnauthenticated());
this.router.navigate(['/login']);
}
}
});
}
better you use a router Guard https://angular.io/guide/router#canload-Guard-Guarding-unauthorized-loading-of-Feature-modules
– Eduardo Vargas
@Eduardovargas thanks for the tip, I’ll give a read on the doc you gave me. I looked over and it looks like that’s what I’m wearing, but I could be wrong.
– rpsouza
then answering about the bad practice I did it before, I preferred to save a token in the cokkies and then check it in the backend axo Middle that wears less the server, imagine every click you have to make a request
– Willian