import type {NavigationGuardWithThis, RouteLocationNormalized} from 'vue-router'; import type {UserState} from '@/stores/user' import {useUserStore} from '@/stores/user' import type {Store} from 'pinia'; const cookieName = 'loginStatus' let userStore: Store | null = null export const updateLoggedIn: NavigationGuardWithThis = (_to) => { const loggedIn = getCookieValue(cookieName) === 'true' const store = getUserStore() store.$patch({ loggedIn }) } export const redirectToLoginIfRequired: NavigationGuardWithThis = (to, _from) => { const store = getUserStore() if(loginRequired(to) && !store.loggedIn) { return { name: 'home' } } } const getCookieValue = (cookieName: string): string => { // https://stackoverflow.com/questions/5639346/what-is-the-shortest-function-for-reading-a-cookie-by-name-in-javascript const cookieValue = document.cookie.match('(^|[^;]+)\\s*' + cookieName + '\\s*=\\s*([^;]+)') if (!cookieValue) { return '' } return cookieValue.pop() || ''; } // Pina is not ready when router is called the first time by app.use(), so we need to load it here const getUserStore = (): UserState & Store => { if (!userStore) { userStore = useUserStore() } return userStore as unknown as UserState & Store } const loginRequired = (to: RouteLocationNormalized) => { return !to.meta?.public } // export const unauthorizedAccess: NavigationGuardWithThis = (to) => { // r loginRequired(to) && getCookieValue('loginStatus') !== 'true'; // }