diff options
Diffstat (limited to 'src/stores/UserStore.ts')
-rw-r--r-- | src/stores/UserStore.ts | 36 |
1 files changed, 36 insertions, 0 deletions
diff --git a/src/stores/UserStore.ts b/src/stores/UserStore.ts index 0616acdad..f98f7d340 100644 --- a/src/stores/UserStore.ts +++ b/src/stores/UserStore.ts | |||
@@ -50,6 +50,11 @@ export default class UserStore extends TypedStore { | |||
50 | 'getInfo', | 50 | 'getInfo', |
51 | ); | 51 | ); |
52 | 52 | ||
53 | @observable requestNewTokenRequest: CachedRequest = new CachedRequest( | ||
54 | this.api.user, | ||
55 | 'requestNewToken', | ||
56 | ); | ||
57 | |||
53 | @observable updateUserInfoRequest: Request = new Request( | 58 | @observable updateUserInfoRequest: Request = new Request( |
54 | this.api.user, | 59 | this.api.user, |
55 | 'updateInfo', | 60 | 'updateInfo', |
@@ -174,6 +179,11 @@ export default class UserStore extends TypedStore { | |||
174 | @computed get data() { | 179 | @computed get data() { |
175 | if (!this.isLoggedIn) return {}; | 180 | if (!this.isLoggedIn) return {}; |
176 | 181 | ||
182 | const newTokenNeeded = this._shouldRequestNewToken(this.authToken); | ||
183 | if (newTokenNeeded) { | ||
184 | this._requestNewToken(); | ||
185 | } | ||
186 | |||
177 | return this.getUserInfoRequest.execute().result || {}; | 187 | return this.getUserInfoRequest.execute().result || {}; |
178 | } | 188 | } |
179 | 189 | ||
@@ -367,6 +377,32 @@ export default class UserStore extends TypedStore { | |||
367 | } | 377 | } |
368 | 378 | ||
369 | // Helpers | 379 | // Helpers |
380 | _shouldRequestNewToken(authToken): boolean { | ||
381 | try { | ||
382 | const decoded = jwt.decode(authToken); | ||
383 | if (!decoded) { | ||
384 | throw new Error('Invalid token'); | ||
385 | } | ||
386 | |||
387 | if (decoded.uid) { | ||
388 | return true; | ||
389 | } | ||
390 | |||
391 | return false; | ||
392 | } catch { | ||
393 | return true; | ||
394 | } | ||
395 | } | ||
396 | |||
397 | _requestNewToken(): void { | ||
398 | // Logic to request new token (use an endpoint for that) | ||
399 | const data = this.requestNewTokenRequest.execute().result; | ||
400 | if (data) { | ||
401 | this.authToken = data.token; | ||
402 | localStorage.setItem('authToken', data.token); | ||
403 | } | ||
404 | } | ||
405 | |||
370 | _parseToken(authToken) { | 406 | _parseToken(authToken) { |
371 | try { | 407 | try { |
372 | const decoded = jwt.decode(authToken); | 408 | const decoded = jwt.decode(authToken); |