Commit ba3c5ec5 authored by Almouhannad's avatar Almouhannad

(F) Add role-based guard

parent 0669d39a
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { HomeComponent } from './components/home/home.component';
import { RoleGuard } from './services/authentication/guards/role-guard';
import { Roles } from './classes/Authentication/roles';
const routes: Routes = [
{ path: '', redirectTo: 'home', pathMatch: 'full' },
{ path: 'home', component: HomeComponent }
{
path: '',
redirectTo: 'home',
pathMatch: 'full',
},
{
path: 'home',
component: HomeComponent,
canActivate: [RoleGuard],
data: { role: Roles.NotRegistered }
}
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
......
......@@ -2,4 +2,5 @@ export class Roles {
public static readonly Admin: string = "admin";
public static readonly Doctor: string = "doctor";
public static readonly Receptionist: string = "receptionist";
public static readonly NotRegistered: string = "notRegistered";
}
\ No newline at end of file
import { Injectable } from '@angular/core';
import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
import { AuthenticationService } from '../authentication.service';
import { Roles } from '../../../classes/Authentication/roles';
import { UserData } from '../../../classes/Authentication/user-data';
@Injectable({
providedIn: 'root'
})
export class RoleGuard implements CanActivate {
constructor(private authenticationService: AuthenticationService) { }
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
const userData: UserData | null = this.authenticationService.getUserData();
const requiredRole: string = route.data['role'];
if (!requiredRole)
return true;
if (requiredRole === Roles.NotRegistered)
return true;
if (!userData)
return false;
return userData.role === requiredRole;
}
}
\ No newline at end of file
......@@ -15,7 +15,7 @@ export class AuthenticationInterceptor implements HttpInterceptor {
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
const jwt = JWTHandler.getJwtFromCookie();
console.log(req);
// console.log(req);
req = req.clone({
headers: this.HTTP_HEADERS
});
......@@ -26,7 +26,7 @@ export class AuthenticationInterceptor implements HttpInterceptor {
}
});
}
console.log(req);
// console.log(req);
return next.handle(req);
}
}
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment