blob: 22a3a8ceb5d3aa25293b2df1f44a8dda35538083 [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
45 let username = localStorage.getItem('storedUsername');
Paul Fertserbceaffa2024-04-10 16:27:53 +000046 store.dispatch('authentication/getUserInfo', username).then(() => {
47 let currentUserRole = store.getters['global/userPrivilege'];
48 allowRouterToNavigate(to, next, currentUserRole);
Damian Celicoaeb19812022-11-24 02:00:53 +010049 });
50 } else {
51 allowRouterToNavigate(to, next, currentUserRole);
52 }
Derick Montaguee080a1a2019-12-04 16:30:08 -060053});
54
Derick Montaguea2988f42020-01-17 13:46:30 -060055export default router;