-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhas-role.guard.ts
More file actions
60 lines (52 loc) · 1.73 KB
/
has-role.guard.ts
File metadata and controls
60 lines (52 loc) · 1.73 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
import { Injectable } from '@angular/core'
import { MatSnackBar } from '@angular/material/snack-bar'
import {
ActivatedRouteSnapshot,
CanActivate,
CanActivateChild,
CanLoad,
Route,
Router,
RouterStateSnapshot,
UrlSegment,
UrlTree,
} from '@angular/router'
import { Observable } from 'rxjs'
import { UserService } from './user.service'
@Injectable({
providedIn: 'root',
})
export class HasRoleGuard implements CanActivate, CanActivateChild, CanLoad {
constructor(private userService: UserService, private router: Router, private snackBar: MatSnackBar) {}
canActivate(
route: ActivatedRouteSnapshot,
state: RouterStateSnapshot
): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree {
return this.hasRole(route.data['role'])
}
canActivateChild(
childRoute: ActivatedRouteSnapshot,
state: RouterStateSnapshot
): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree {
return this.hasRole(childRoute.data['role'])
}
canLoad(route: Route, segments: UrlSegment[]): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree {
return this.hasRole(route.data ? route.data['role'] : undefined)
}
private hasRole(allowed: string | string[] | undefined): boolean {
if (!allowed) {
return true
}
if (typeof allowed === 'string' && this.userService.current.roles.includes(allowed)) {
return true
}
for(const allowedRole of allowed as Array<string>) {
if (this.userService.current.roles.includes(allowedRole)) {
return true
}
}
this.snackBar.open(`Vous n'avez pas le rôle ${allowed}`, 'Ok', {verticalPosition: 'top'})
this.router.navigate(['/home'])
return false
}
}