Skip to content

Commit

Permalink
Implementa Guard para rotas de admin
Browse files Browse the repository at this point in the history
davimarinho <[email protected]>
  • Loading branch information
nYCSTs committed Nov 15, 2023
1 parent fa07dde commit 463b12a
Show file tree
Hide file tree
Showing 6 changed files with 51 additions and 13 deletions.
3 changes: 2 additions & 1 deletion src/app/app-routing.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import { ResetPasswordComponent } from './pages/reset-password/reset-password.co
import { AuthGuard } from './services/auth.guard';
import { EditUserComponent } from './pages/edit-user/edit-user.component';
import { UpdateRoleComponent } from './pages/update-role/update-role.component';
import { AdminGuard } from './services/admin.guard';

const routes: Routes = [
{ path: 'login', component: LoginComponent },
Expand All @@ -25,7 +26,7 @@ const routes: Routes = [
{ path: 'changePassword', component: ResetPasswordComponent },
{ path: 'profile', component: ProfileComponent, canActivate: [AuthGuard], },
{ path: 'editUser/:id', component: EditUserComponent, canActivate: [AuthGuard], },
{ path: 'update-role', component: UpdateRoleComponent, canActivate: [AuthGuard], data:{roles:["ADMIN"]} },
{ path: 'update-role', component: UpdateRoleComponent, canActivate: [AdminGuard], },
{ path: '', component: HomePageComponent, canActivate: [AuthGuard], },
];

Expand Down
2 changes: 0 additions & 2 deletions src/app/pages/profile/profile.component.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,8 +33,6 @@ export class ProfileComponent {
getUser() {
this.userService.getUser(this.userId).subscribe({
next: (data) => {
console.log(data);
localStorage.setItem('role', data.role);
this.user = data;
},
error: (error) => {
Expand Down
16 changes: 16 additions & 0 deletions src/app/services/admin.guard.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import { TestBed } from '@angular/core/testing';

import { AdminGuard } from './admin.guard';

describe('AdminGuard', () => {
let guard: AdminGuard;

beforeEach(() => {
TestBed.configureTestingModule({});
guard = TestBed.inject(AdminGuard);
});

it('should be created', () => {
expect(guard).toBeTruthy();
});
});
23 changes: 23 additions & 0 deletions src/app/services/admin.guard.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import { Injectable } from '@angular/core';
import { ActivatedRouteSnapshot, CanActivate, Router, RouterStateSnapshot, UrlTree } from '@angular/router';
import { Observable } from 'rxjs';
import { UserService } from './user.service';

@Injectable({
providedIn: 'root'
})
export class AdminGuard implements CanActivate {
constructor(
private router: Router,
private userService: UserService
) {}
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree {
const roles = this.userService.getRoles();
if (roles !== "ADMIN") {
this.router.navigate(["/"]);
return false;
}
return true;
}

}
12 changes: 2 additions & 10 deletions src/app/services/auth.guard.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,20 +9,12 @@ import { AuthService } from './auth.service';
export class AuthGuard implements CanActivate {
constructor(private authService: AuthService, private router: Router) {}

canActivate(route:ActivatedRouteSnapshot): boolean {
const roles: string[]= route.data?.roles;
console.log(roles)
const role = localStorage.getItem("role") || ""
console.log(role)
canActivate(): boolean {
if (this.authService.isAuthenticated()) {
if (roles) {

return roles.includes(role)
}
return true;
} else {
this.router.navigate(['/login']);
return false;
}
}
}
}
8 changes: 8 additions & 0 deletions src/app/services/user.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { Injectable } from '@angular/core';
import { environment } from '../environment/environment';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
import jwt_decode from 'jwt-decode';

interface IGetAllUsers {
name?: string;
Expand Down Expand Up @@ -40,6 +41,13 @@ export class UserService {
return this.http.get(`${this.apiURL}/users${queryString && '?' + queryString}`, {observe: 'response'});
}

getRoles() {
const access_token = localStorage.getItem("token");
const payload: any = jwt_decode(access_token as string);
const userRole: string = payload.role;
return userRole;
}

updateUser(id: any, body: any): Observable<any> {
return this.http.patch(`${this.apiURL}/users/${id}`, body);
}
Expand Down

0 comments on commit 463b12a

Please sign in to comment.