xref: /openbmc/webui-vue/src/router/index.js (revision b325541c)
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  scrollBehavior() {
16    return { x: 0, y: 0 };
17  },
18});
19
20function allowRouterToNavigate(to, next, currentUserRole) {
21  if (to.matched.some((record) => record.meta.requiresAuth)) {
22    if (store.getters['authentication/isLoggedIn']) {
23      if (to.meta.exclusiveToRoles) {
24        // The privilege for the specific router was verified using the
25        // exclusiveToRoles roles in the router.
26        if (to.meta.exclusiveToRoles.includes(currentUserRole)) {
27          next();
28        } else {
29          next('*');
30        }
31        return;
32      }
33      next();
34      return;
35    }
36    next('/login');
37  } else {
38    next();
39  }
40}
41
42router.beforeEach((to, from, next) => {
43  let currentUserRole = store.getters['global/userPrivilege'];
44  // condition will get satisfied if user refreshed after login
45  if (!currentUserRole && store.getters['authentication/isLoggedIn']) {
46    // invoke API call to get the role ID
47    let username = localStorage.getItem('storedUsername');
48    store.dispatch('authentication/getUserInfo', username).then(() => {
49      let currentUserRole = store.getters['global/userPrivilege'];
50      allowRouterToNavigate(to, next, currentUserRole);
51    });
52  } else {
53    allowRouterToNavigate(to, next, currentUserRole);
54  }
55});
56
57export default router;
58