diff options
author | vnugent <public@vaughnnugent.com> | 2023-12-13 17:58:51 -0500 |
---|---|---|
committer | vnugent <public@vaughnnugent.com> | 2023-12-13 17:58:51 -0500 |
commit | 4b8ae76132d2342f40cec703b3d5145ea075c451 (patch) | |
tree | 62b942b6181261566cd3245ee35cd15a138aabf2 /front-end/src/store/pageProtectionPlugin.ts | |
parent | b564708f29cf8a709c3e3d981477b2ec8440673e (diff) |
log time coming ui and lib updates
Diffstat (limited to 'front-end/src/store/pageProtectionPlugin.ts')
-rw-r--r-- | front-end/src/store/pageProtectionPlugin.ts | 79 |
1 files changed, 79 insertions, 0 deletions
diff --git a/front-end/src/store/pageProtectionPlugin.ts b/front-end/src/store/pageProtectionPlugin.ts new file mode 100644 index 0000000..9831dad --- /dev/null +++ b/front-end/src/store/pageProtectionPlugin.ts @@ -0,0 +1,79 @@ +import 'pinia' +import { watch } from 'vue'; +import { } from '@vnuge/vnlib.browser'; +import { useSessionStorage, get, set } from '@vueuse/core'; +import { PiniaPluginContext, PiniaPlugin, storeToRefs } from 'pinia' +import { includes, startsWith } from 'lodash-es'; +import { useRouter } from 'vue-router'; + +declare module 'pinia' { + export interface PiniaCustomProperties { + + } +} + +export const pageProtectionPlugin = (router: ReturnType<typeof useRouter>): PiniaPlugin => { + + return ({ store }: PiniaPluginContext) => { + + const { loggedIn, headerRoutes } = storeToRefs(store) + + const lastPageStore = useSessionStorage('lastPageStore', undefined) + + //Setup nav guards + router.beforeEach((to, from) => { + if(!to.name){ + return true; + } + + //see if to route is login route + if(startsWith(to.name as string, 'Login')){ + + //If the user is logged-in, redirect to the last page + if(get(loggedIn) === true){ + const lastPath = get(lastPageStore); + set(lastPageStore, undefined) //Clear the last page + + return lastPath ? { path: lastPath } : true; + } + else{ + //Set last page as from page + set(lastPageStore, from.fullPath) + } + return true; + } + + //See if the to route is not in allowed routes + if (!includes(get(headerRoutes), to.name as string)){ + //Check if the user is logged in + if(get(loggedIn) === false){ + + //Save the last page + set(lastPageStore, to.fullPath) + + //Redirect to login + return { name: 'Login' } + } + } + + //Allow + return true; + }) + + router.afterEach(() => { + //scroll window back to top + window.scrollTo(0, 0) + }) + + watch(loggedIn, (loggedIn) => { + //If the user gets logged out, redirect to login + if(loggedIn === false && router.currentRoute.value.name !== 'Login'){ + router.push({ name: 'Login' }) + } + }) + + return { + + } + } +}
\ No newline at end of file |