Skip to content

Commit 1cae011

Browse files
committed
fix(sample): make sense of the guard
1 parent 9710f60 commit 1cae011

File tree

3 files changed

+30
-9
lines changed

3 files changed

+30
-9
lines changed

projects/sample/src/app/home/home.component.html

+4
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,10 @@
22
<h1 *ngIf="!givenName">Welcome!</h1>
33
<h1 *ngIf="givenName">Welcome, {{ givenName }} {{ familyName }}!</h1>
44

5+
<div *ngIf="login" style="color: red">
6+
You have to login before you can search for flights.
7+
</div>
8+
59
<div class="panel panel-default">
610
<div class="panel-body">
711
<p>Login with Authorization Server</p>

projects/sample/src/app/home/home.component.ts

+11-1
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ import { authConfig } from '../auth.config';
22
import { Component, OnInit } from '@angular/core';
33
import { OAuthService } from 'angular-oauth2-oidc';
44
import { authCodeFlowConfig } from '../auth-code-flow.config';
5+
import { ActivatedRoute } from '@angular/router';
56

67
@Component({
78
templateUrl: './home.component.html'
@@ -10,10 +11,19 @@ export class HomeComponent implements OnInit {
1011
loginFailed: boolean = false;
1112
userProfile: object;
1213
usePopup: boolean;
14+
login: false;
1315

14-
constructor(private oauthService: OAuthService) {}
16+
constructor(
17+
private route: ActivatedRoute,
18+
private oauthService: OAuthService) {
19+
}
1520

1621
ngOnInit() {
22+
23+
this.route.params.subscribe(p => {
24+
this.login = p['login'];
25+
});
26+
1727
// This would directly (w/o user interaction) redirect the user to the
1828
// login page if they are not already logged in.
1929
/*
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,23 @@
11
import { Injectable } from '@angular/core';
22
import {
3-
CanActivate,
4-
ActivatedRouteSnapshot,
5-
RouterStateSnapshot
3+
CanActivate, Router
64
} from '@angular/router';
5+
import { OAuthService } from 'angular-oauth2-oidc';
76

87
@Injectable()
98
export class AuthGuard implements CanActivate {
10-
canActivate(
11-
route: ActivatedRouteSnapshot,
12-
state: RouterStateSnapshot
13-
): boolean {
14-
return true;
9+
10+
constructor(
11+
private router: Router,
12+
private oauthService: OAuthService) {
13+
}
14+
15+
canActivate() {
16+
if (this.oauthService.hasValidAccessToken() && this.oauthService.hasValidIdToken()) {
17+
return true;
18+
} else {
19+
this.router.navigate(['/home', {login: true}]);
20+
return false;
21+
}
1522
}
1623
}

0 commit comments

Comments
 (0)