25 lines
897 B
TypeScript
25 lines
897 B
TypeScript
import { inject } from '@angular/core';
|
|
import { MatSnackBar } from '@angular/material/snack-bar';
|
|
import { CanActivateFn, Router } from '@angular/router';
|
|
|
|
import { AuthService } from './auth.service';
|
|
|
|
export const authGuard: CanActivateFn = (route, state) => {
|
|
const user = inject(AuthService).user;
|
|
const permission =
|
|
route.data['permission'] === undefined
|
|
? route.data['permission']
|
|
: route.data['permission'].replace(/ /g, '-').toLowerCase();
|
|
if (!user) {
|
|
// not logged in so redirect to login page with the return url
|
|
inject(Router).navigate(['/login'], { queryParams: { returnUrl: state.url } });
|
|
return false;
|
|
}
|
|
if (permission !== undefined && user.perms.indexOf(permission) === -1) {
|
|
inject(MatSnackBar).open('You do not have the permission to access this area.', 'Danger');
|
|
return false;
|
|
}
|
|
// logged in so return true
|
|
return true;
|
|
};
|