Is it a bad practice to check Auth on the components I want to crash?

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']);
        }
    });
}

As the app.component was

 ngOnInit(): void {
this.authService.initAuthListener();
                 }

Every first call on the page would go to / login, so I passed the verification to training.component, which is where you need to have authorization.

Is it a bad practice? What would be my alternative?

I modified it as follows, 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']);
                }
        }
    });
}
    
asked by anonymous 07.12.2018 / 20:11

1 answer

0

The practice I use is described in the angular doc using a service with a method called CanActived and putting the validation on the routes.

Example:

auth-guard.service.ts

import { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root'
})
export class AuthGuardService {

  private isAuthenticated: boolean = true;
  constructor() { }

  canActivate() {
    return this.isAuthenticated;
  }

  login(){
    return this.isAuthenticated = !this.isAuthenticated
  }
}

app.module.ts

@NgModule({
  declarations: [

  ],
  imports: [

    RouterModule.forRoot([
      { path: 'login' , component: LoginComponent },

      { path: 'welcome', canActivate: [AuthGuardService], component: WelcomeComponent }

    ])
  ],
  providers: [AuthGuardService],
  bootstrap: [AppComponent]
})
export class AppModule { }
    
11.12.2018 / 04:45