46 lines
1.3 KiB
TypeScript
46 lines
1.3 KiB
TypeScript
|
|
import { Injectable } from '@angular/core';
|
|
import { Router, CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
|
|
import { Utils } from '../shares';
|
|
@Injectable({ providedIn: 'root' })
|
|
export class AuthGuard implements CanActivate {
|
|
msg ="[AuthGuard] ";
|
|
constructor(private router: Router) { }
|
|
|
|
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
|
|
const roleAllowed = (route.data as any).roleAllowed;
|
|
const user = Utils.getCurrentUser();
|
|
const userRole = Utils.getUserRole(user);
|
|
let hasLoggedIn = Utils.getIsAuth();
|
|
console.log(this.msg + " the userlogin ", user);
|
|
if (hasLoggedIn) {
|
|
|
|
if (roleAllowed != undefined)
|
|
{
|
|
console.log("[auth-guard] ther roleAllow ", roleAllowed);
|
|
if (roleAllowed.indexOf(userRole) != -1) {
|
|
return true;
|
|
}
|
|
else {
|
|
this.router.navigate(['/login']);
|
|
return false;
|
|
}
|
|
}
|
|
else //if no role define just return hasLoggedIn
|
|
{
|
|
return hasLoggedIn;
|
|
}
|
|
}
|
|
else
|
|
{
|
|
this.router.navigate(['/login']);
|
|
return false;
|
|
}
|
|
|
|
// not logged in so redirect to login page with the return url
|
|
this.router.navigate(['/login'], { queryParams: { returnUrl: state.url } });
|
|
return false;
|
|
}
|
|
|
|
}
|