salix-front/src/router/hooks.js

96 lines
2.9 KiB
JavaScript

import { useRole } from 'src/composables/useRole';
import { useUserConfig } from 'src/composables/useUserConfig';
import { useTokenConfig } from 'src/composables/useTokenConfig';
import { useAcl } from 'src/composables/useAcl';
import { isLoggedIn } from 'src/utils/session';
import { useSession } from 'src/composables/useSession';
import { useStateQueryStore } from 'src/stores/useStateQueryStore';
import { watch } from 'vue';
import { i18n } from 'src/boot/i18n';
let session = null;
const { t, te } = i18n.global;
export async function navigationGuard(to, from, next, Router, state) {
if (!session) session = useSession();
const outLayout = Router.options.routes[0].children.map((r) => r.name);
if (!session.isLoggedIn() && !outLayout.includes(to.name)) {
return next({ name: 'Login', query: { redirect: to.fullPath } });
}
if (isLoggedIn()) {
const stateRoles = state.getRoles().value;
if (stateRoles.length === 0) {
await useRole().fetch();
await useAcl().fetch();
await useUserConfig().fetch();
await useTokenConfig().fetch();
}
const matches = to.matched;
const hasRequiredAcls = matches.every((route) => {
const meta = route.meta;
if (!meta?.acls) return true;
return useAcl().hasAny(meta.acls);
});
if (!hasRequiredAcls) return next({ path: '/' });
}
next();
}
export async function stateQueryGuard(to, from, next) {
if (to.name !== from.name) {
const stateQuery = useStateQueryStore();
await waitUntilFalse(stateQuery.isLoading());
}
next();
}
export function setPageTitle(to) {
let title = t(`login.title`);
const matches = to.matched;
if (matches && matches.length > 1) {
const module = matches[1];
const moduleTitle = module.meta?.title;
if (moduleTitle) {
title = t(`globals.pageTitles.${moduleTitle}`);
}
}
const childPage = to.meta;
const childPageTitle = childPage?.title;
if (childPageTitle && matches.length > 2) {
if (title != '') title += ': ';
const moduleLocale = `globals.pageTitles.${childPageTitle}`;
const pageTitle = te(moduleLocale)
? t(moduleLocale)
: t(`globals.pageTitles.${childPageTitle}`);
const idParam = to.params?.id;
const idPageTitle = `${idParam} - ${pageTitle}`;
const builtTitle = idParam ? idPageTitle : pageTitle;
title += builtTitle;
}
document.title = title;
}
function waitUntilFalse(ref) {
return new Promise((resolve) => {
if (!ref.value) return resolve();
const stop = watch(
ref,
(val) => {
if (!val) {
stop();
resolve();
}
},
{ immediate: true },
);
});
}