blob: 27fd96e6568d8f0612c729892d96e08f9211a9d2 [file] [log] [blame]
Ed Tanous883a0d52024-03-23 14:56:34 -07001import { createRouter, createWebHistory } from 'vue-router';
Yoshie Muranaka8263d852020-10-16 07:58:06 -07002
3//Do not change store or routes import.
4//Exact match alias set to support
5//dotenv customizations.
Yoshie Muranaka8263d852020-10-16 07:58:06 -07006import store from '../store';
Dixsie Wolmers0a5b9c62020-10-20 10:52:56 -05007import routes from './routes';
Derick Montaguea2988f42020-01-17 13:46:30 -06008
Ed Tanous883a0d52024-03-23 14:56:34 -07009const router = createRouter({
10 history: createWebHistory(process.env.BASE_URL),
Derick Montaguea2988f42020-01-17 13:46:30 -060011 routes,
Derick Montague602e98a2020-10-21 16:20:00 -050012 linkExactActiveClass: 'nav-link--current',
aravinths1b3255412024-05-22 15:52:20 +053013 scrollBehavior() {
14 return { x: 0, y: 0 };
15 },
Derick Montaguea2988f42020-01-17 13:46:30 -060016});
17
Damian Celicoaeb19812022-11-24 02:00:53 +010018function allowRouterToNavigate(to, next, currentUserRole) {
Derick Montague602e98a2020-10-21 16:20:00 -050019 if (to.matched.some((record) => record.meta.requiresAuth)) {
Derick Montaguefded0d12019-12-11 06:16:40 -060020 if (store.getters['authentication/isLoggedIn']) {
Damian Celicoaeb19812022-11-24 02:00:53 +010021 if (to.meta.exclusiveToRoles) {
22 // The privilege for the specific router was verified using the
23 // exclusiveToRoles roles in the router.
24 if (to.meta.exclusiveToRoles.includes(currentUserRole)) {
25 next();
26 } else {
27 next('*');
28 }
29 return;
30 }
Derick Montaguee080a1a2019-12-04 16:30:08 -060031 next();
32 return;
33 }
Derick Montaguefded0d12019-12-11 06:16:40 -060034 next('/login');
Derick Montaguee080a1a2019-12-04 16:30:08 -060035 } else {
36 next();
37 }
Damian Celicoaeb19812022-11-24 02:00:53 +010038}
39
40router.beforeEach((to, from, next) => {
41 let currentUserRole = store.getters['global/userPrivilege'];
42 // condition will get satisfied if user refreshed after login
43 if (!currentUserRole && store.getters['authentication/isLoggedIn']) {
44 // invoke API call to get the role ID
Paul Fertserce7db822024-07-05 11:04:04 +000045 store
46 .dispatch('authentication/getSessionPrivilege')
47 .then(() => {
48 let currentUserRole = store.getters['global/userPrivilege'];
49 allowRouterToNavigate(to, next, currentUserRole);
50 })
51 // our store got out of sync, start afresh
52 .catch(() => {
53 console.log('Failed to obtain current Roles, logging out.');
54 store.dispatch('authentication/logout');
55 });
Damian Celicoaeb19812022-11-24 02:00:53 +010056 } else {
57 allowRouterToNavigate(to, next, currentUserRole);
58 }
Derick Montaguee080a1a2019-12-04 16:30:08 -060059});
60
Derick Montaguea2988f42020-01-17 13:46:30 -060061export default router;