If I refresh the page when I'm logged in, the Guard redirects me to the login page. Is there a way for redirecting to the login page only if the user truly log out? I am using frontend as angular (version: 12.2.13)and backend as firebase.
auth.guard.ts
import { Injectable } from "@angular/core";
import { ActivatedRouteSnapshot, CanActivate, Router, RouterStateSnapshot } from "@angular/router";
import { AuthService } from "./auth.service";
@Injectable()
export class AuthGuard implements CanActivate {
constructor(private authService: AuthService, private router: Router){}
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot){
if(this.authService.isAuth()){
return true;
} else {
this.router.navigate(['/auth']);
}
}
}
CodePudding user response:
When user logged in the application, user's status should be saved in sessionStorage or Redux.Then An AuthGuard service must be defined.Finally the AuthGuard must be added to each Routes.
@Injectable({
providedIn: 'root'
})
export class AuthGuard implements CanActivate {
constructor(private router: Router) {}
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
const userLoginStatus = sessionStorage.getItem("userLogin");
const IsUserLogin: boolean | null = userLoginStatus ? JSON.parse(userLoginStatus) : null;
if ( IsUserLogin ) {
return true
}
else {
this.router.navigateByUrl("/");
return false
}
}
}
CodePudding user response:
Routes with home route protected by AuthGuard
import { Routes, RouterModule } from '@angular/router';
import { LoginComponent } from './login/index';
import { HomeComponent } from './home/index';
import { AuthGuard } from './_guards/index';
const appRoutes: Routes = [
{ path: 'login', component: LoginComponent },
// home route protected by auth guard
{ path: '', component: HomeComponent, canActivate: [AuthGuard] },
// otherwise redirect to home
{ path: '**', redirectTo: '' }
];
export const routing = RouterModule.forRoot(appRoutes);
AuthGuard redirects to login page if user isn't logged in
import { Injectable } from '@angular/core';
import { Router, CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
@Injectable()
export class AuthGuard implements CanActivate {
constructor(private router: Router) { }
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
if (localStorage.getItem('currentUser')) {
// logged in so return true
return true;
}
// not logged in so redirect to login page with the return url
this.router.navigate(['/login'], { queryParams: { returnUrl: state.url }});
return false;
}
}