Skip to content

Instantly share code, notes, and snippets.

@changhuixu
Created July 26, 2020 00:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save changhuixu/ec0a363258b45dc77983b91399e0c646 to your computer and use it in GitHub Desktop.
Save changhuixu/ec0a363258b45dc77983b91399e0c646 to your computer and use it in GitHub Desktop.
private storageEventListener(event: StorageEvent) {
if (event.storageArea === localStorage) {
if (event.key === 'logout-event') {
this._user.next(null);
}
if (event.key === 'login-event') {
location.reload();
}
}
}
login(username: string, password: string) {
return this.http
.post<LoginResult>(`${this.apiUrl}/login`, { username, password })
.pipe(
map((x) => {
this._user.next({ username: x.username, role: x.role });
this.setLocalStorage(x);
localStorage.setItem('login-event', 'login' + Math.random());
this.startTokenTimer();
return x;
})
);
}
setLocalStorage(x: LoginResult) {
localStorage.setItem('access_token', x.accessToken);
localStorage.setItem('refresh_token', x.refreshToken);
}
private getTokenRemainingTime() {
const accessToken = localStorage.getItem('access_token');
if (!accessToken) {
return 0;
}
const jwtToken = JSON.parse(atob(accessToken.split('.')[1]));
const expires = new Date(jwtToken.exp * 1000);
return expires.getTime() - Date.now();
}
private startTokenTimer() {
const timeout = this.getTokenRemainingTime();
this.timer = of(true)
.pipe(
delay(timeout),
tap(() => this.refreshToken().subscribe())
)
.subscribe();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment