35 lines
1.1 KiB
TypeScript
35 lines
1.1 KiB
TypeScript
import { useUserStore } from "@/stores/user";
|
|
import type { NavigationGuardWithThis, RouteLocationNormalized } from "vue-router";
|
|
|
|
export const updateLoggedIn: NavigationGuardWithThis<undefined> = async () => {
|
|
const loggedIn = getCookieValue("loginStatus") === "true";
|
|
const userStore = useUserStore();
|
|
|
|
userStore.$patch({ loggedIn });
|
|
if (loggedIn && !userStore.id) {
|
|
await userStore.fetchUser();
|
|
}
|
|
};
|
|
|
|
export const redirectToLoginIfRequired: NavigationGuardWithThis<undefined> = (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;
|
|
};
|