From 5c14275a75a9fff2ffe5200f28f07d039797db26 Mon Sep 17 00:00:00 2001 From: Matthew Aaron Raymer Date: Fri, 2 Dec 2022 18:54:47 +0800 Subject: [PATCH] Added Pinia account state tracking. Also modified router to go to Start if no account is defined. --- src/main.ts | 4 +--- src/router/index.ts | 11 +++++++++++ src/store/account.ts | 17 ++++++++++------- src/store/index.ts | 9 --------- 4 files changed, 22 insertions(+), 19 deletions(-) delete mode 100644 src/store/index.ts diff --git a/src/main.ts b/src/main.ts index 96635806b..13e3105b4 100644 --- a/src/main.ts +++ b/src/main.ts @@ -3,8 +3,7 @@ import { createApp } from "vue"; import App from "./App.vue"; import "./registerServiceWorker"; import router from "./router"; -import store from "./store"; - +import { useAccountStore } from "./store/account"; import "./assets/styles/tailwind.css"; import { library } from "@fortawesome/fontawesome-svg-core"; @@ -50,7 +49,6 @@ import { FontAwesomeIcon } from "@fortawesome/vue-fontawesome"; createApp(App) .component("fa", FontAwesomeIcon) - .use(store) .use(createPinia()) .use(router) .mount("#app"); diff --git a/src/router/index.ts b/src/router/index.ts index 3e87b44e0..45b553f7d 100644 --- a/src/router/index.ts +++ b/src/router/index.ts @@ -1,4 +1,5 @@ import { createRouter, createWebHistory, RouteRecordRaw } from "vue-router"; +import { useAccountStore } from "../store/account"; import HomeView from "../views/HomeView.vue"; const routes: Array = [ @@ -109,4 +110,14 @@ const router = createRouter({ routes, }); +router.beforeEach(async (to) => { + // redirect to start page if no account + const publicPages = ["/start"]; + const authRequired = !publicPages.includes(to.path); + const authStore = useAccountStore(); + + if (authRequired && !authStore.account) { + return "/start"; + } +}); export default router; diff --git a/src/store/account.ts b/src/store/account.ts index aae6a95a4..79c83407a 100644 --- a/src/store/account.ts +++ b/src/store/account.ts @@ -4,16 +4,19 @@ import { defineStore } from "pinia"; export const useAccountStore = defineStore({ id: "account", state: () => ({ - firstName: "", - lastName: "", + account: JSON.parse( + typeof localStorage["account"] == "undefined" + ? null + : localStorage["account"] + ), }), - + getters: { + firstName: (state) => state.account.firstName, + lastName: (state) => state.account.lastName, + }, actions: { reset() { - this.$patch({ - firstName: "", - lastName: "", - }); + localStorage.removeItem("account"); }, }, }); diff --git a/src/store/index.ts b/src/store/index.ts deleted file mode 100644 index 100073ad5..000000000 --- a/src/store/index.ts +++ /dev/null @@ -1,9 +0,0 @@ -import { createStore } from "vuex"; - -export default createStore({ - state: {}, - getters: {}, - mutations: {}, - actions: {}, - modules: {}, -});