Persist login (for now - due to constant page reloads)

This commit is contained in:
Fredrik Adelöw
2020-02-06 10:49:00 +01:00
parent 2b58a65598
commit 926732ce6c
@@ -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<LoginState>[] = [];
private currentUser: string | undefined = undefined;
private listeners: ZenObservable.SubscriptionObserver<LoginState>[];
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));