import { useUserStore } from "@/stores/user"; import type { NavigationGuardWithThis, RouteLocationNormalized } from "vue-router"; export const updateLoggedIn: NavigationGuardWithThis = async () => { const loggedIn = getCookieValue("loginStatus") === "true"; const userStore = useUserStore(); userStore.$patch({ loggedIn }); if (loggedIn && !userStore.id) { await userStore.fetchUser(); } }; export const redirectToLoginIfRequired: NavigationGuardWithThis = (to) => { const userStore = useUserStore(); if (loginRequired(to) && !userStore.loggedIn) { return `/login?next=${to.fullPath}`; } }; export 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() || ""; }; const loginRequired = (to: RouteLocationNormalized) => { return !to.meta?.public; };