diff --git a/src/app/app.module.ts b/src/app/app.module.ts index 1a09f92bcdb76ec9260abfe447fd3b079976e0c7..e067baf02defc12da0d5703a7fef7b592364940b 100644 --- a/src/app/app.module.ts +++ b/src/app/app.module.ts @@ -47,6 +47,7 @@ import { import { LoginScreenComponent } from './login-screen/login-screen.component'; import { NotificationService } from './notification.service'; import { AuthenticationService } from './authentication.service'; +import { AuthenticationGuard } from './authentication.guard'; @NgModule({ declarations: [ @@ -100,7 +101,8 @@ import { AuthenticationService } from './authentication.service'; ], providers: [ NotificationService, - AuthenticationService + AuthenticationService, + AuthenticationGuard ], bootstrap: [AppComponent] }) diff --git a/src/app/authentication.guard.spec.ts b/src/app/authentication.guard.spec.ts new file mode 100644 index 0000000000000000000000000000000000000000..4e97bbe88ea7771636069bcbc84787607fd1d825 --- /dev/null +++ b/src/app/authentication.guard.spec.ts @@ -0,0 +1,15 @@ +import { TestBed, async, inject } from '@angular/core/testing'; + +import { AuthenticationGuard } from './authentication.guard'; + +describe('AuthenticationGuard', () => { + beforeEach(() => { + TestBed.configureTestingModule({ + providers: [AuthenticationGuard] + }); + }); + + it('should ...', inject([AuthenticationGuard], (guard: AuthenticationGuard) => { + expect(guard).toBeTruthy(); + })); +}); diff --git a/src/app/authentication.guard.ts b/src/app/authentication.guard.ts new file mode 100644 index 0000000000000000000000000000000000000000..c4cf7fe48b391d136528d19c0e46ba80842c0154 --- /dev/null +++ b/src/app/authentication.guard.ts @@ -0,0 +1,25 @@ +import { Injectable } from '@angular/core'; +import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, Router } from '@angular/router'; +import { Observable } from 'rxjs/Observable'; +import { AuthenticationService } from './authentication.service'; +import 'rxjs/add/operator/map'; +import 'rxjs/add/observable/of'; +import 'rxjs/add/operator/catch'; + +@Injectable() +export class AuthenticationGuard implements CanActivate { + constructor(private authenticationService: AuthenticationService, + private router: Router) { + } + + canActivate(next: ActivatedRouteSnapshot, + state: RouterStateSnapshot): Observable<boolean> { + return this.authenticationService.isLoggedIn().map(isLoggedIn => { + if (!isLoggedIn) { + // TODO: redirect to error page + this.router.navigate(['/']); + } + return isLoggedIn; + }); + } +}