From a204a18e99c76890d6bfe4f6719ec43db2778cc3 Mon Sep 17 00:00:00 2001 From: Thomas Cardon Date: Wed, 9 Mar 2022 15:57:38 +0100 Subject: [PATCH] authentification avec Role --- src/app/app-routing.module.ts | 2 +- src/app/services/auth.guard.ts | 10 ++++++++-- src/app/services/auth.service.ts | 8 +++++--- 3 files changed, 14 insertions(+), 6 deletions(-) diff --git a/src/app/app-routing.module.ts b/src/app/app-routing.module.ts index b37f76b..e58f922 100644 --- a/src/app/app-routing.module.ts +++ b/src/app/app-routing.module.ts @@ -23,7 +23,7 @@ const routes: Routes = [ { path: 'Deconnexion', redirectTo: 'home'}, {path: 'restaurants', canActivate: [AuthGuard], /*data : {ROLE : "ROLE_ADMIN"},*/ component: RestoPageComponent}, {path: 'page-not-found',component: PageNotFoundComponent}, - {path: 'admin',canActivate: [AuthGuard], component: AdminPageComponent}, + {path: 'admin',canActivate: [AuthGuard],data : {ROLE : "ROLE_ADMIN"}, component: AdminPageComponent}, {path: '**', redirectTo: 'page-not-found' } ]; diff --git a/src/app/services/auth.guard.ts b/src/app/services/auth.guard.ts index 77c9e97..87a7b9e 100644 --- a/src/app/services/auth.guard.ts +++ b/src/app/services/auth.guard.ts @@ -26,6 +26,8 @@ export class AuthGuard implements CanActivate { const decodedToken = jwt_decode(token); // TODO boucle sur le ['auth'] pour controler le role et en fonction de ca renvoyer true ou false ac redirection page403 + //console.log(decodedToken['auth'][0]['authority']); + console.log('decodedToken : ', decodedToken); @@ -37,13 +39,17 @@ export class AuthGuard implements CanActivate { // le token a expiré, je n'autorise pas l'accès this.tokenService.destroyToken(this.tokenKey); this.router.navigate(['signin']); - + return false; + } + + if(route.data['ROLE'] && route.data['ROLE'] != localStorage.getItem('ROLE')){ + this.router.navigate(['page-not-found']); return false; } } - console.log("C'est ok ! ") return true; + } else { console.log("You shall not pass !!!!") this.router.navigate(['signin']); // redirection de notre utilisateur vers une url de notre application (dans notre code TS) diff --git a/src/app/services/auth.service.ts b/src/app/services/auth.service.ts index 24263ba..0ffb722 100644 --- a/src/app/services/auth.service.ts +++ b/src/app/services/auth.service.ts @@ -34,12 +34,14 @@ export class AuthService { return this.http.post(`${this.apiUrl}/signin`, body).pipe( map((x: any) => { - console.log(x); + //console.log(x); - console.log('Service : ', x.token); + const decodedToken = jwt_decode(x.token); + //console.log('Service : ', x.token); // Modification à faire ici localStorage.setItem(this.tokenKey, x.token); - //localStorage.setItem('ROLE', "ROLE_READER"); + + localStorage.setItem('ROLE', decodedToken['auth'][0]['authority']); return x; // permet de renvoyer la réponse à l'initiateur (page Signin) après le traitement du map }) );