Merge pull request #60 from spotify/freben/persist-login

Persist login (for now - due to constant page reloads)
This commit is contained in:
Stefan Ålund
2020-02-06 11:05:37 +01:00
committed by GitHub
@@ -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));