Added basic userstore
This commit is contained in:
61
src/lib/UserStore.js
Normal file
61
src/lib/UserStore.js
Normal file
@@ -0,0 +1,61 @@
|
||||
import { writable } from 'svelte/store';
|
||||
import localForage from 'localforage';
|
||||
|
||||
const userStore = () => {
|
||||
const state = {
|
||||
token: undefined,
|
||||
username: undefined,
|
||||
isLoggedIn: false,
|
||||
refreshInterval: undefined
|
||||
};
|
||||
|
||||
const { subscribe, set, update } = writable(state);
|
||||
|
||||
const methods = {
|
||||
init() {
|
||||
localForage.config({
|
||||
name: 'linkylinky',
|
||||
version: 1.0,
|
||||
storeName: 'linkylinky_dashboard',
|
||||
description: 'linkylinky Dashboard'
|
||||
});
|
||||
},
|
||||
login(authresponse) {
|
||||
update((state) => {
|
||||
state.token = authresponse.token;
|
||||
state.isLoggedIn = true;
|
||||
//
|
||||
localForage.setItem("userdata", state);
|
||||
//
|
||||
state.refreshInterval = setInterval(() => {
|
||||
//this.refreshAuth();
|
||||
// 2min
|
||||
}, 2 * 60000);
|
||||
//
|
||||
return state;
|
||||
});
|
||||
},
|
||||
logout() {
|
||||
update((state) => {
|
||||
state.isLoggedIn = false;
|
||||
state.token = undefined;
|
||||
//
|
||||
clearInterval(state.refreshInterval);
|
||||
state.refreshInterval = undefined;
|
||||
localForage.clear();
|
||||
//
|
||||
return state;
|
||||
});
|
||||
location.replace("/");
|
||||
}
|
||||
};
|
||||
|
||||
return {
|
||||
subscribe,
|
||||
set,
|
||||
update,
|
||||
state,
|
||||
...methods
|
||||
};
|
||||
};
|
||||
export default userStore();
|
||||
@@ -1,6 +1,15 @@
|
||||
<script>
|
||||
import '../app.postcss';
|
||||
import Sidebar from '$lib/Sidebar.svelte';
|
||||
import UserStore from '$lib/UserStore';
|
||||
|
||||
$: isLoggedIn = false;
|
||||
|
||||
UserStore.init();
|
||||
const unsubscribe = UserStore.subscribe((value) => {
|
||||
isLoggedIn = value.isLoggedIn;
|
||||
});
|
||||
onDestroy(unsubscribe);
|
||||
</script>
|
||||
|
||||
<div style="min-height: 640px;" class="bg-white dark:bg-gray-800">
|
||||
|
||||
Reference in New Issue
Block a user