xref: /openbmc/webui-vue/src/router/index.js (revision aeb19816)
1import Vue from 'vue';
2import VueRouter from 'vue-router';
3
4//Do not change store or routes import.
5//Exact match alias set to support
6//dotenv customizations.
7import store from '../store';
8import routes from './routes';
9
10Vue.use(VueRouter);
11const router = new VueRouter({
12  base: process.env.BASE_URL,
13  routes,
14  linkExactActiveClass: 'nav-link--current',
15});
16
17function allowRouterToNavigate(to, next, currentUserRole) {
18  if (to.matched.some((record) => record.meta.requiresAuth)) {
19    if (store.getters['authentication/isLoggedIn']) {
20      if (to.meta.exclusiveToRoles) {
21        // The privilege for the specific router was verified using the
22        // exclusiveToRoles roles in the router.
23        if (to.meta.exclusiveToRoles.includes(currentUserRole)) {
24          next();
25        } else {
26          next('*');
27        }
28        return;
29      }
30      next();
31      return;
32    }
33    next('/login');
34  } else {
35    next();
36  }
37}
38
39router.beforeEach((to, from, next) => {
40  let currentUserRole = store.getters['global/userPrivilege'];
41  // condition will get satisfied if user refreshed after login
42  if (!currentUserRole && store.getters['authentication/isLoggedIn']) {
43    // invoke API call to get the role ID
44    let username = localStorage.getItem('storedUsername');
45    store.dispatch('authentication/getUserInfo', username).then((response) => {
46      if (response?.RoleId) {
47        // set role ID
48        store.commit('global/setPrivilege', response.RoleId);
49        // allow the route to continue
50        allowRouterToNavigate(to, next, response.RoleId);
51      }
52    });
53  } else {
54    allowRouterToNavigate(to, next, currentUserRole);
55  }
56});
57
58export default router;
59