Angular 6+: Page update goes to the Login area of the application

1

I performed the composition of my CanActivate and CanLoad through the class LoggedInGuard. The problem is that whenever I refresh the page, I'm redirected to the Login page, even logged in. Below my LoggedInGuard class

@Injectable()
export class LoggedInGuard implements CanLoad, CanActivate {
  constructor(private signinService: SigninService, private router: Router) { }

  checkAuthentication(path: string): boolean {
    const loggedin = this.signinService.isLoggedin();
    if (!loggedin) {
      this.router.navigate([ this.signinService.handleLogin('/${ path }') ]);
    }
    return loggedin;
  }

  canLoad(route: Route): boolean {
    return this.checkAuthentication(route.path);
  }

  canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
    return this.checkAuthentication(route.routeConfig.path);
  }

}

My SignService:

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

  private baseUrl: string;
  private user: User;
  private lastUrl: string;

  constructor(private http: HttpClient, private router: Router) {
    this.baseUrl = '${environment.url}/auth/signin';
    this.router.events
      .filter(e => e instanceof NavigationEnd)
      .subscribe((e: NavigationEnd) => this.lastUrl = e.url);
  }

  public isLoggedin(): boolean {
    return this.user !== undefined && localStorage.getItem('token') !== undefined;
  }

  public login(username: string, password: string): Observable<User> {
    const params = new HttpParams()
      .set('username', username)
      .set('password', password);
    return this.http.post<User>('${this.baseUrl}', params).do((user: User) => this.user = user);
  }

  public logout(): void {
    localStorage.clear();
    this.user = undefined;
    this.handleLogin('/');
  }

  public handleLogin(path: string = this.lastUrl) {
    this.router.navigate(['/signin', btoa(path)]);
  }

  public get UserDetail(): User {
    return this.user;
  }


}

The Services are set within the responsibility providers. In my SigninComponent and I log in as follows:

public login(): void {
    console.log(this.signinForm);
    this.signinService.login(this.signinForm.value.username, this.signinForm.value.password ).subscribe((user: User) => {
      this.user = user;
      localStorage.setItem('token', this.user.token.token);
      this.isSuccess = true;
      this.message = 'Usuário encontrado. Aguarde um momento!';
    }, (err: HttpErrorResponse) => {
        this.isSuccess = false;
        this.message = err.error.error.message;
      console.error(err);
      }, () => {
        this.router.navigate([ atob(this.navigateTo) ]);
    });
  }
    
asked by anonymous 24.12.2018 / 02:21

1 answer

0

Solution 1: Because the User is not an Interface, the reference is lost. So I changed the interface format to class, and instantiated it.

this.user = new User();

As above, I could not lose my reference.

The other way, is working with localstorage:

localStorage.setItem('token', this.user.token.token);

In practice, when using the set with an exclusive tooken, then setar token, which is such a common word within the applications can generate conflicts if you have other applications that use the same term. It's rare, but I've seen cases happen. Then, name it thiago_token , for example.

Always when updating, the system will check if the token is in the localstorage or sessionstorage. Where do you prefer to record!

    
29.12.2018 / 05:38