Reputation: 2909
I have an app that I have setup with an Authentication Guard to make sure users cannot access the app unless they have logged in, like so
import { Injectable } from '@angular/core';
import {
CanActivate, Router,
ActivatedRouteSnapshot,
RouterStateSnapshot,
CanActivateChild } from '@angular/router';
import { AuthContext } from './auth-context.service';
@Injectable()
export class AuthGuard implements CanActivate {
constructor(private router: Router, private authContext: AuthContext) { }
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
// Check to see if a user has a valid JWT
if (this.authContext.userInfo !== undefined && this.authContext.userInfo.isAuthenticated) {
// If they do, return true and allow the user to load the home component
return true;
}
// If not, they redirect them to the login page
this.router.navigate(['/login']);
return false;
}
canActivateChild(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
return this.canActivate(route, state);
}
}
I want to add another guard for Authorization that will check if the user is in a certain role. Currently I am hiding the link in navigation based on this role.
<div *ngIf="userInRole('Admin')">
This is secret stuff
</div>
But if a user knows a route, they can just plug it into the url. How would I add my "userInRole()" type functionality to a Guard? I would have to pass the role name and do the check in code. Do Guards support params?
Upvotes: 7
Views: 11999
Reputation: 543
I found solution this
import { Injectable } from '@angular/core';
import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
import { Observable } from 'rxjs/Observable';
import { AuthService } from './service/auth.service';
@Injectable()
export class IsInRoleGuard implements CanActivate {
constructor(
private _authService: AuthService
) { }
async canActivate(next: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {
const userRole = this._authService.getRole(); // Get role from service
if (next.data['roles'].indexOf(userRole) !== -1) {
return true;
}
return false;
}
}
and in your router-config
import { Routes, RouterModule } from '@angular/router';
import { ModuleWithProviders } from '@angular/core';
import { RootComponent } from './root/root.component';
import { DashboardComponent } from './dashboard/dashboard.component';
import { IsInRoleGuard } from '../../guards/is-in-role.guard';
const routes: Routes = [
{
path: '', component: RootComponent, children: [
{
path: '', pathMatch: 'full', canActivate: [IsInRoleGuard], component: DashboardComponent, data: {
roles: [
'admin',
'super-admin'
]
}
}
]
}
];
export const RouterConfig: ModuleWithProviders = RouterModule.forChild(routes);
Upvotes: 13
Reputation: 12376
A guard is just a class that implements CanActivate or CanDeactivate. But nothing stops you from injecting a service (or a value) that would return you the role of the user. For example,
export class AuthGuard implements CanActivate {
constructor(private router: Router, private authContext: AuthContext,
private user: MyUserService) { }
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
if (!this.user.isAdmin()) return false;
...
}
}
Upvotes: 4