| import { inject } from '@angular/core'; | |
| import { CanActivateFn, Router, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router'; | |
| import { AuthService } from './auth.service'; | |
| import { map, catchError } from 'rxjs/operators'; | |
| import { of } from 'rxjs'; | |
| export const authGuard: CanActivateFn = ( | |
| route: ActivatedRouteSnapshot, | |
| state: RouterStateSnapshot | |
| ) => { | |
| const authService = inject(AuthService); | |
| const router = inject(Router); | |
| return authService.checkSession().pipe( | |
| map(() => { | |
| if (authService.isLoggedIn()) { | |
| return true; | |
| } else { | |
| localStorage.setItem('redirectAfterLogin', state.url); | |
| router.navigate(['/auth']); | |
| return false; | |
| } | |
| }), | |
| catchError(() => { | |
| localStorage.setItem('redirectAfterLogin', state.url); | |
| router.navigate(['/auth']); | |
| return of(false); | |
| }) | |
| ); | |
| }; | |