From b2726f702067d87c6a32ac2dfff7d37d730fc8c3 Mon Sep 17 00:00:00 2001 From: Shivanee Date: Fri, 24 Jul 2020 11:24:38 +0530 Subject: [PATCH] Modified edit user guard based on managers --- .../guards/edit-user-guard.service.ts | 27 ++++++++++++------- src/app/services/users.service.ts | 5 ++++ 2 files changed, 23 insertions(+), 9 deletions(-) diff --git a/src/app/services/guards/edit-user-guard.service.ts b/src/app/services/guards/edit-user-guard.service.ts index 64a8986..1515601 100644 --- a/src/app/services/guards/edit-user-guard.service.ts +++ b/src/app/services/guards/edit-user-guard.service.ts @@ -1,10 +1,10 @@ import { Injectable } from '@angular/core'; import { RouterStateSnapshot, Router, ActivatedRouteSnapshot } from '@angular/router'; import { UsersService } from '../users.service'; -import { map, catchError } from 'rxjs/operators'; +import { map, catchError, take } from 'rxjs/operators'; import { AuthService } from '../auth.service'; import { USER_PERMISSION } from './permissions'; -import { of } from 'rxjs'; +import { of, Observable } from 'rxjs'; @Injectable({ providedIn: 'root' @@ -13,16 +13,25 @@ export class EditUserGuard { constructor(private router : Router, private userService : UsersService, private authService : AuthService) { } - canActivate(route : ActivatedRouteSnapshot, state : RouterStateSnapshot) { - let role = this.authService.userLoggedIn().role.roleString; + canActivate(route : ActivatedRouteSnapshot, state : RouterStateSnapshot) : Observable{ + let loggedInUser = this.authService.userLoggedIn(); + let role = loggedInUser.role.roleString; + let userId = loggedInUser.id; let routeId = parseInt(route.params.id, 10); - if(!USER_PERMISSION.write.includes(role)) return false; - return this.userService.getAll() - .pipe(map((users : any) => users.map(user => user.id )), map(users => { - if(users.includes(routeId)) + if(!USER_PERMISSION.write.includes(role) || userId === routeId) return of(false).pipe(take(1)); + return this.userService.getManagers(routeId) + .pipe( + take(1), + map((users : any) => { + let managers = users.map(user => user.id); + if(managers.includes(userId)) return true; + else { + this.router.navigate(['/dashboard']); + return false; + } }), catchError(err => { - this.router.navigateByUrl('/dashboard'); + this.router.navigate(['/dashboard']); return of(false); })); } diff --git a/src/app/services/users.service.ts b/src/app/services/users.service.ts index f2164d0..85dd4a2 100644 --- a/src/app/services/users.service.ts +++ b/src/app/services/users.service.ts @@ -23,6 +23,11 @@ export class UsersService extends DataService{ return this.http.get(url); } + getManagers(id) { + let url = 'http://localhost:8080/users/managers/' + id; + return this.http.get(url); + } + changePassword(oldPassword, newPassword) { return new Promise((resolve, reject) => { // POST request to server with email and password