Skip to content

Instantly share code, notes, and snippets.

@NetanelBasal
Created October 31, 2022 09:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save NetanelBasal/2096594e647ea6ac2970742286d57103 to your computer and use it in GitHub Desktop.
Save NetanelBasal/2096594e647ea6ac2970742286d57103 to your computer and use it in GitHub Desktop.
import { inject } from '@angular/core';
import { CanMatchFn, Router } from '@angular/router';
import { AuthService } from './auth-service';
export function authGuard({
redirectTo,
isProtected = true,
}: {
redirectTo?: any[];
isProtected?: boolean;
} = {}): CanMatchFn {
return () => {
const authService = inject(AuthService);
const router = inject(Router);
const isLoggedIn = authService.isLoggedIn();
if (isProtected) {
if (isLoggedIn) {
return true;
}
return router.createUrlTree(redirectTo ?? ['login']);
} else {
if (!isLoggedIn) {
return true;
}
return router.createUrlTree(redirectTo ?? ['dashboard']);
}
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment