I am using Angular and this is for my authentication check:
export class EnsureAuthenticated implements CanActivate {
constructor(private auth: AuthService, private router: Router) {}
canActivate(): boolean {
if (localStorage.getItem('token')) {
return true;
}
else {
this.router.navigateByUrl('/login');
return false;
}
}
}
{
path: 'path',
component: myComponent,
canActivate: [EnsureAuthenticated]
}
It's working fine but my problem is this page can be accessed by both user and admin.
I know I didn't set any condition on it. How do I set the proper condition on it?
I don't want to access this page to admin
See this example in stackblitz
In your app-routing.module.ts
const routes: Routes = [
{
path: "admin",
component: AdminOnlyComponent,
canActivate: [RoleGuardService],
data: { roles: ['admin']}
},
...
}
In your RoleGuardService
import { Injectable } from '@angular/core';
import { UserRolesService} from './user-roles.service';
import { Router, ActivatedRouteSnapshot } from '@angular/router';
@Injectable({
providedIn: 'root'
})
export class RoleGuardService {
constructor(private getUserRoles: UserRolesService) { }
canActivate(route: ActivatedRouteSnapshot): boolean {
return route.data.roles.some( ai => this.getUserRoles.getRoles().includes(ai) );
}
}
In UserRolesService
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class UserRolesService {
userRoles: string[] = [];
constructor() { }
setRoles(Roles: string[]){
this.userRoles = Roles.slice(0);
}
getRoles(){
return this.userRoles;
}
}
Set roles when user logged in to the system or get those roles from your localstorage....
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With