Skip to content

Commit 9fd6f2c

Browse files
author
Your Name
committed
angular security course
1 parent c506b90 commit 9fd6f2c

File tree

3 files changed

+50
-3
lines changed

3 files changed

+50
-3
lines changed

src/app/app.module.ts

+14-2
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@ import {ReactiveFormsModule} from "@angular/forms";
1212

1313
import {AuthService} from "./services/auth.service";
1414
import {AdminComponent} from './admin/admin.component';
15-
import {RouterModule} from "@angular/router";
15+
import {Router, RouterModule} from "@angular/router";
1616

1717

1818
import 'rxjs/add/operator/switchMap';
@@ -24,6 +24,7 @@ import 'rxjs/add/operator/catch';
2424
import 'rxjs/add/operator/first';
2525
import 'rxjs/add/observable/of';
2626
import {RbacAllowDirective} from "./common/rbac-allow.directive";
27+
import {AuthorizationGuard} from "./services/authorization.guard";
2728

2829

2930
@NgModule({
@@ -47,7 +48,18 @@ import {RbacAllowDirective} from "./common/rbac-allow.directive";
4748
],
4849
providers: [
4950
LessonsService,
50-
AuthService
51+
AuthService,
52+
{
53+
provide: 'adminsOnlyGuard',
54+
useFactory: (authService:AuthService,
55+
router:Router) =>
56+
new AuthorizationGuard(['ADMIN'], authService, router),
57+
deps: [
58+
AuthService,
59+
Router
60+
]
61+
62+
}
5163
],
5264
bootstrap: [AppComponent]
5365
})

src/app/routes.config.ts

+2-1
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,8 @@ export const routesConfig: Routes = [
1919
},
2020
{
2121
path: 'admin',
22-
component: AdminComponent
22+
component: AdminComponent,
23+
canActivate: ["adminsOnlyGuard"]
2324
},
2425
{
2526
path: '',
+34
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
2+
import {ActivatedRouteSnapshot, CanActivate, Router, RouterStateSnapshot} from "@angular/router";
3+
import {Observable} from "rxjs/Observable";
4+
import {AuthService} from "./auth.service";
5+
import * as _ from 'lodash';
6+
import {Injectable} from "@angular/core";
7+
8+
@Injectable()
9+
export class AuthorizationGuard implements CanActivate {
10+
11+
12+
constructor(private allowedRoles:string[],
13+
private authService:AuthService, private router:Router) {
14+
15+
}
16+
17+
18+
canActivate(
19+
route: ActivatedRouteSnapshot,
20+
state: RouterStateSnapshot): Observable<boolean> {
21+
22+
return this.authService.user$
23+
.map(user => _.intersection(this.allowedRoles, user.roles).length > 0 )
24+
.first()
25+
.do(allowed => {
26+
if (!allowed) {
27+
this.router.navigateByUrl('/');
28+
}
29+
});
30+
31+
32+
}
33+
34+
}

0 commit comments

Comments
 (0)