xref: /openbmc/webui-vue/src/router/index.js (revision 883a0d59)
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    let username = localStorage.getItem('storedUsername');
46    store.dispatch('authentication/getUserInfo', username).then(() => {
47      let currentUserRole = store.getters['global/userPrivilege'];
48      allowRouterToNavigate(to, next, currentUserRole);
49    });
50  } else {
51    allowRouterToNavigate(to, next, currentUserRole);
52  }
53});
54
55export default router;
56