51 lines
1.5 KiB
TypeScript
51 lines
1.5 KiB
TypeScript
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<undefined> = (_to) => {
|
|
const loggedIn = getCookieValue(cookieName) === 'true'
|
|
const store = getUserStore()
|
|
|
|
store.$patch({ loggedIn })
|
|
}
|
|
|
|
export const redirectToLoginIfRequired: NavigationGuardWithThis<undefined> = (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<undefined> = (to) => {
|
|
// r loginRequired(to) && getCookieValue('loginStatus') !== 'true';
|
|
// }
|