1
I performed the composition of my Canactivate and Canload, through the Loggedinguard class. The problem is that whenever I refresh the page, I am redirected to the Login page, even logged in. Below my class Loggedinguard
@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;
}
}
Services are set within responsibility providers. In my, Signincomponent and perform the Login 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) ]);
});
}
the method isLoggedin ta returning true or false??
– Eduardo Vargas
It’s @Eduardovargas! So... It seems like he loses the user reference when he updates the page. Something I wouldn’t want to happen. so, the method to be fake! I did localstorage only, but I don’t find it very confident.
– Thiago Cunha