portfolio-admin/src/app/guards/auth-guard.ts

21 lines
655 B
TypeScript

import { inject, PLATFORM_ID } from '@angular/core';
import { isPlatformBrowser } from '@angular/common';
import { CanActivateFn, Router } from '@angular/router';
import { AuthService } from '../auth/auth.service';
export const authGuard: CanActivateFn = (route, state) => {
const platformId = inject(PLATFORM_ID);
// During SSR there is no localStorage — skip the guard and let the client enforce auth after hydration
if (!isPlatformBrowser(platformId)) {
return true;
}
const auth = inject(AuthService);
const router = inject(Router);
return auth.currentToken
? true
: router.parseUrl(`login?returnUrl=${state.url}`);
};