import { createRouter, createWebHistory } from 'vue-router'; import { frontendURL } from '../helper/URLHelper'; import dashboard from './dashboard/dashboard.routes'; import store from 'dashboard/store'; import { validateLoggedInRoutes } from '../helper/routeHelpers'; import { isOnOnboardingView } from 'v3/helpers/RouteHelper'; import AnalyticsHelper from '../helper/AnalyticsHelper'; const ONBOARDING_STEPS = ['account_details', 'enrichment']; const routes = [ { path: '/', redirect: '/app/login' }, ...dashboard.routes, ]; export const router = createRouter({ history: createWebHistory(), routes }); const PUBLIC_ROUTE_NAMES = [ 'login', 'sso_login', 'auth_signup', 'auth_confirmation', 'auth_verify_email', 'auth_password_edit', 'auth_reset_password', ]; export const validateAuthenticateRoutePermission = async (to, next) => { const { isLoggedIn, getCurrentUser: user } = store.getters; if (PUBLIC_ROUTE_NAMES.includes(to.name)) { return next(); } if (!isLoggedIn) { return next(frontendURL('login')); } const { accounts = [], account_id: accountId } = user; if (!accounts.length) { if (to.name === 'no_accounts') { return next(); } return next(frontendURL('no-accounts')); } const routeAccountId = Number(to.params?.accountId || accountId); const userAccount = accounts.find(a => a.id === routeAccountId); const isAdmin = userAccount?.role === 'administrator'; const isActive = userAccount?.status === 'active'; const needsOnboarding = ONBOARDING_STEPS.includes(userAccount?.onboarding_step) && isAdmin && isActive; if (to.name === 'no_accounts' || !to.name) { const target = needsOnboarding ? 'onboarding' : 'dashboard'; return next(frontendURL(`accounts/${routeAccountId}/${target}`)); } if (needsOnboarding && !isOnOnboardingView(to)) { return next(frontendURL(`accounts/${routeAccountId}/onboarding`)); } if (!needsOnboarding && isOnOnboardingView(to)) { return next(frontendURL(`accounts/${routeAccountId}/dashboard`)); } const nextRoute = validateLoggedInRoutes(to, store.getters.getCurrentUser); return nextRoute ? next(frontendURL(nextRoute)) : next(); }; export const initalizeRouter = () => { const userAuthentication = store.dispatch('setUser'); router.beforeEach(async (to, _from, next) => { AnalyticsHelper.page(to.name || '', { path: to.path, name: to.name, }); await userAuthentication; await validateAuthenticateRoutePermission(to, next, store); }); }; export default router;