ekangularbase
Version:
Authentication service for usermanagement(oidc client)
60 lines (55 loc) • 2.22 kB
text/typescript
// src/app/auth/role-guard.service.ts
import { Injectable } from '@angular/core';
import {
Router,
CanActivate,
ActivatedRouteSnapshot
} from '@angular/router';
import { AuthService } from './auth.service';
import {MessageService} from 'primeng/api';
()
export class PermissionGuardService implements CanActivate {
constructor(public auth: AuthService, public router: Router,
public messageService: MessageService) { }
canActivate(route: ActivatedRouteSnapshot): boolean {
// this will be passed from the route config
// on the data property
const expectedpermission: string[] = route.data.expectedPermission;
//const token = localStorage.getItem('token');
// decode the token to get its payload
//const tokenPayload = decode(token);
// alert(JSON.stringify(this.auth.getPermissions()));
// alert(JSON.stringify(this));
var permissionmatch: boolean = false;
var permissionarray:string[] = this.auth.getPermissions();
// console.log(permissionarray);
// alert(JSON.stringify(permissionarray));
for (let x in expectedpermission) {
// alert(expectedpermission[x]);
try {
//var roleexist = rolearray.find(role => expectedRole[x] == role);
var r:string = expectedpermission[x].toString();
if (permissionarray.find(s => s.toUpperCase() === r.toUpperCase()))
//(permissionarray.indexOf(expectedpermission[x]) >= 0)
// if (permissionarray.indexOf(expectedpermission[x]) > -1)
{
permissionmatch = true;
break;
}
}
catch (error) {
// alert(error);
}
}
if (
!this.auth.isLoggedIn() ||
!permissionmatch
) {
// alert("No Permission!");
this.messageService.add({severity:'error', summary:'Authorization', detail:'No Permission'});
this.router.navigate(['/']);
return false;
}
return true;
}
}