Created
July 25, 2023 06:43
-
-
Save Sathasivamthirumoorthi/0549ed3b80b0fdbcb039e4040465d919 to your computer and use it in GitHub Desktop.
auth.guard.ts
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { Injectable, inject } from '@angular/core'; | |
import { Router, CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, CanActivateFn } from '@angular/router'; | |
import { CredentialsService } from '../services/auth'; | |
@Injectable({ providedIn: 'root' }) | |
export class AuthGuard{ | |
constructor( | |
private router: Router, | |
private credential: CredentialsService | |
) { } | |
canActivate(route: ActivatedRouteSnapshot) { | |
const user = this.credential.userValue; | |
if (user) { | |
// check if route i s restricted by role | |
if (route.data['roles'] && route.data['roles'].indexOf(user.role) === -1) { | |
// role not authorised so redirect to home page | |
this.router.navigate(['authentication/login']); | |
return false; | |
} | |
// authorised so return true | |
return true; | |
} | |
// not logged in so redirect to login page with the return url | |
this.router.navigate(['authentication/login']); | |
return true; | |
} | |
} | |
export const teamAuthGuard: CanActivateFn = | |
(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) => { | |
return inject(AuthGuard).canActivate(route); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment