Skip to content

Commit 7c59721

Browse files
Handle cross-tab storage events
Listen to (some) storage events to make sure the user doesn't remain on a page that should be inaccessible.
1 parent 9952752 commit 7c59721

File tree

1 file changed

+20
-1
lines changed

1 file changed

+20
-1
lines changed

src/app/auth.service.ts

Lines changed: 20 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,11 @@ export class AuthService {
2828
this.isDoneLoading$
2929
).pipe(map(values => values.every(b => b)));
3030

31+
private navigateToLoginPage() {
32+
// TODO: Remember current URL
33+
this.router.navigateByUrl('/should-login');
34+
}
35+
3136
constructor (
3237
private oauthService: OAuthService,
3338
private router: Router,
@@ -41,6 +46,20 @@ export class AuthService {
4146
}
4247
});
4348

49+
window.addEventListener('storage', (event) => {
50+
// The `key` is `null` if the event was caused by `.clear()`
51+
if (event.key !== 'access_token' && event.key !== null) {
52+
return;
53+
}
54+
55+
console.warn('Noticed changes to access_token (possibly from another tab), updating isAuthenticated');
56+
this.isAuthenticatedSubject$.next(this.oauthService.hasValidAccessToken());
57+
58+
if (!this.oauthService.hasValidAccessToken()) {
59+
this.navigateToLoginPage();
60+
}
61+
});
62+
4463
this.oauthService.events
4564
.subscribe(_ => {
4665
this.isAuthenticatedSubject$.next(this.oauthService.hasValidAccessToken());
@@ -52,7 +71,7 @@ export class AuthService {
5271

5372
this.oauthService.events
5473
.pipe(filter(e => ['session_terminated', 'session_error'].includes(e.type)))
55-
.subscribe(e => this.router.navigateByUrl('/should-login')); // TODO: Remember current URL
74+
.subscribe(e => this.navigateToLoginPage());
5675

5776
this.oauthService.setupAutomaticSilentRefresh();
5877
}

0 commit comments

Comments
 (0)