File size: 880 Bytes
e4ab6d0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
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);
    })
  );
};