From 926732ce6cc2762892a7be1c9a547639d3a4c59c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Fredrik=20Adel=C3=B6w?= Date: Thu, 6 Feb 2020 10:49:00 +0100 Subject: [PATCH] Persist login (for now - due to constant page reloads) --- .../packages/app/src/login/MockCurrentUser.ts | 33 +++++++++++++++++-- 1 file changed, 31 insertions(+), 2 deletions(-) diff --git a/frontend/packages/app/src/login/MockCurrentUser.ts b/frontend/packages/app/src/login/MockCurrentUser.ts index 76dd04443e..0b90e25fab 100644 --- a/frontend/packages/app/src/login/MockCurrentUser.ts +++ b/frontend/packages/app/src/login/MockCurrentUser.ts @@ -1,17 +1,27 @@ import Observable from 'zen-observable'; import { LoginState } from './types'; +const LOCAL_STORAGE_KEY = 'mock_current_user'; + export class MockCurrentUser { - private listeners: ZenObservable.SubscriptionObserver[] = []; - private currentUser: string | undefined = undefined; + private listeners: ZenObservable.SubscriptionObserver[]; + private currentUser: string | undefined; + + constructor() { + this.listeners = []; + this.currentUser = undefined; + this.loadPrevious(); + } login(user: string) { this.currentUser = user; + this.saveCurrent(); this.notify(); } logout() { this.currentUser = undefined; + this.saveCurrent(); this.notify(); } @@ -25,6 +35,25 @@ export class MockCurrentUser { }); } + private loadPrevious() { + const user = localStorage.getItem(LOCAL_STORAGE_KEY); + if (user) { + try { + this.currentUser = JSON.parse(user); + } catch (e) { + localStorage.removeItem(LOCAL_STORAGE_KEY); + } + } + } + + private saveCurrent() { + if (!this.currentUser) { + localStorage.removeItem(LOCAL_STORAGE_KEY); + } else { + localStorage.setItem(LOCAL_STORAGE_KEY, JSON.stringify(this.currentUser)); + } + } + private notify() { const state = this.getState(); this.listeners.forEach(listener => listener.next(state));