Created
July 26, 2020 00:51
-
-
Save changhuixu/ec0a363258b45dc77983b91399e0c646 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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