xref: /openbmc/webui-vue/src/router/index.js (revision ce7db82c9582c4dac04ac81d9af6b557ae7965e3)
1import { createRouter, createWebHistory } from 'vue-router';
2
3//Do not change store or routes import.
4//Exact match alias set to support
5//dotenv customizations.
6import store from '../store';
7import routes from './routes';
8
9const router = createRouter({
10  history: createWebHistory(process.env.BASE_URL),
11  routes,
12  linkExactActiveClass: 'nav-link--current',
13  scrollBehavior() {
14    return { x: 0, y: 0 };
15  },
16});
17
18function allowRouterToNavigate(to, next, currentUserRole) {
19  if (to.matched.some((record) => record.meta.requiresAuth)) {
20    if (store.getters['authentication/isLoggedIn']) {
21      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      }
31      next();
32      return;
33    }
34    next('/login');
35  } else {
36    next();
37  }
38}
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    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      });
56  } else {
57    allowRouterToNavigate(to, next, currentUserRole);
58  }
59});
60
61export default router;
62