import { inject } from '@angular/core';
import { CanActivateFn, Router, ActivatedRouteSnapshot } from '@angular/router';
import { AuthService } from './auth.service';
export const authGuard: CanActivateFn = async (
route: ActivatedRouteSnapshot
) => {
const authService = inject(AuthService);
const router = inject(Router);
const isLoggedIn = await authService.getIsLoggedIn();
const isAuthPage =
route.routeConfig?.path === 'login' ||
route.routeConfig?.path === 'registration';
if (isLoggedIn && isAuthPage) {
router.navigate(['/']);
return false;
}
if (!isLoggedIn && !isAuthPage) {
router.navigate(['/login']);
return false;
}
return true;
};
Routing with lazy loading and auth guards
import { Routes } from '@angular/router';
import { authGuard } from './auth/auth.guard';
export const appRoutes: Routes = [
{
path: '',
children: [
{
path: '',
redirectTo: 'cases',
pathMatch: 'full',
},
{
path: 'cases',
canActivate: [authGuard], // Csak bejelentkezett felhasználóknak elérhető
loadComponent: () =>
import('./features/cases/cases.component').then(
(m) => m.CasesComponent
),
},
{
path: 'login',
canActivate: [authGuard], // Ha be vagy jelentkezve, átirányít a főoldalra
loadComponent: () =>
import('./auth/login/login.component').then((m) => m.LoginComponent),
},
{
path: 'registration',
canActivate: [authGuard], // Ha be vagy jelentkezve, átirányít a főoldalra
loadComponent: () =>
import('./auth/registration/registration.component').then(
(m) => m.RegistrationComponent
),
},
{
path: '404',
loadComponent: () =>
import('./core/not-found/not-found.component').then(
(m) => m.NotFoundComponent
),
},
{
path: '**',
redirectTo: '404',
},
],
},
];
