Tips for restricting access to specific routes in VueJS using Store state

Once a user is authorized, their user type is saved to the state. Based on this type, I need to dynamically show or hide specific routes.

src/store/index.js:

import Vue from "vue";
import Vuex from "vuex";
import getters from "./getters";
import user from "./modules/user";

Vue.use(Vuex);

const store = new Vuex.Store({
  modules: { user },
  getters
});

export default store;

src/store/getters.js:

const getters = {
  token: state => state.user.token,
  name: state => state.user.name,
  type: state => state.user.type
};

export default getters;

src/router/index.js:

import Vue from "vue";
import Router from "vue-router";

import Layout from "@/layout";

Vue.use(Router);

export const constantRoutes = [
  {
    path: "/login",
    component: () => import("@/views/Login"),
    hidden: true
  },
  {
    path: "/",
    component: Layout,
    redirect: "/dashboard",
    children: [
      {
        path: "dashboard",
        name: "Dashboard",
        component: () => import("@/views/Dashboard"),
        meta: { title: "routes.dashboard", icon: "el-icon-odometer" }
      }
    ]
  },
  {
    path: "/providers",
    component: Layout,
    redirect: "/providers/list",
    name: "Providers",
    meta: { title: "routes.providers", icon: "el-icon-suitcase-1" },
    children: [
      {
        path: 'list',
        name: "List",
        component: () => import("@/views/providers/ProvidersList"),
        meta: { title: "routes.providersList", icon: "el-icon-document" }
      }
    ]
  }
];

const createRouter = () =>
  new Router({
    scrollBehavior: () => ({ y: 0 }),
    routes: constantRoutes
  });

const router = createRouter();

export function resetRouter() {
  const newRouter = createRouter();
  router.matcher = newRouter.matcher;
}

export default router;

Authorization control functionality is kept in a separate file src/permission.js:

import router from "./router";
import store from "./store";
import { Message } from "element-ui";
import NProgress from "nprogress";
import "nprogress/nprogress.css";
import { getToken } from "@/utils/auth";
import getPageTitle from "@/utils/get-page-title";

NProgress.configure({ showSpinner: false });

const whiteList = ["/login"];

router.beforeEach(async (to, from, next) => {
  NProgress.start();
  document.title = getPageTitle(to.meta.title);
  const hasToken = getToken();

  if (hasToken) {
    if (to.path === "/login") {
      next({ path: "/" });
      NProgress.done();
    } else {
      const hasGetUserInfo = store.getters.name;
      if (hasGetUserInfo) {
        next();
      } else {
        try {
          await store.dispatch("user/getInfo");
          next();
        } catch (error) {
          await store.dispatch("user/resetToken");
          Message.error(error || "An Error Occurred");
          next(`/login?redirect=${to.path}`);
          NProgress.done();
        }
      }
    }
  } else {
    if (whiteList.indexOf(to.path) !== -1) {
      next();
    } else {
      next(`/login?redirect=${to.path}`);
      NProgress.done();
    }
  }
});

router.afterEach(() => {
  NProgress.done();
});

I'm currently facing an issue as my code consists of various copied solutions and I'm unsure how to restrict access to certain routes based on different values of state.user.type. Any guidance on how to approach this would be greatly appreciated.

Answer №1

I have transformed my initial comment into a comprehensive answer.

You may find it beneficial to utilize a pre-existing and proven solution for your needs. Consider exploring options such as Vue-ACL or even delving into something more advanced.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Retrieve the full directory path that has been chosen in an HTML form

I am facing a similar issue in my web application where I am using PHP, HTML, and JavaScript. What I want is to be able to select a folder and obtain the full path of that folder for backing up data. For example, when a user enters backup.php, they should ...

Strip the pound symbol from the end of a URL during an AJAX request

When I click on the News tab in my Rails application (version 2.3.4 and Ruby 1.8.7), an Ajax call is triggered to load data. <a href="News" onclick="load_feed();"><u>Show More...</u></a> <script> function load_feed() { $.a ...

Having difficulty deleting a checkbox element using JavaScript

My goal is to have a feature where users can effortlessly add or remove checkbox div elements as needed. The code I have written successfully adds and resets checkboxes, but I am encountering an issue when trying to remove them. I am struggling to identif ...

What is the best way to dynamically assign a value to an anchor tag upon each click using jQuery?

How can I pass a value to an anchor tag on every click using jQuery? I am encountering an issue with my current code where the value is not being retrieved when I click the button. //HTML snippet <button id="a-selectNm" data-a_name="<?php echo $row[ ...

Having trouble launching the emulator in VS Code for React Native?

I'm having trouble launching the android emulator on VS Code to run React-Native. I already have an emulator set up in Android Studio, but when I try to launch it, I get the error message: Error Failed to launch emulator. Reason: No emulators found as ...

Error encountered: Scrollanimation IOS syntax error- Unexpected token '=.' an open parenthesis '(' was expected before a method's parameter list

Encountering an issue with the scroll animation on older IOS devices (2019 and older) - I receive the following error message: SyntaxError: Unexpected token '='. Expected an opening '(' before a method's parameter list. class Event ...

Find the value of a JavaScript string variable using an alternative name

My latest JavaScript function is designed to fetch JSON data from either a server or local files on any browser. This piece of code processes JSON from two sources: an XMLHttpRequest response, or a variable imported via script. In the case of the latter, ...

Troubleshooting Texture Compatibility Issue with ThreeJS ShaderMaterial on iOS Devices

Seeking assistance with shaders in Threejs. I have a plane that requires a mixture of 10 different textures; currently using ShaderMaterial and passing all textures for blending. Below is my Fragment Shader code: vec3 CFull = texture2D(tFull, vUv).rgb; vec ...

Encountering a TypeScript error in Vue 3 when trying to assign a type of '($event: any) => void' to an event listener

Snippet of component code: <h2 @click="handleEvent(post.id)">{{ post.title }}</h2> function handleEvent(id: number) { router.push("/post/" + id); } Error message in TypeScript: Type '($event: any) => void' i ...

Incorporating a JavaScript workflow into Django

Currently, I am following a tutorial on integrating a modern JavaScript pipeline into my Django application. The objective is to have the JavaScript code write "Hello webpack" onto the page, but unfortunately, it is not displaying as expected. Since I alr ...

What are the steps to generate a multiline chart using d3.js with json data specifically formatted for nvd3?

I attempted to create a multi-line chart using nvd3, but encountered roadblocks when trying to make significant modifications. I am considering building my own chart using d3js directly, but I'm finding it challenging to grasp the concept of 'thi ...

The document.ready function does not seem to be functioning properly within an iframe

In the main page, there's an embedded iframe set up like this: <iframe src="facts.php" style="width:320px; height:500px; border:hidden" id="facts"> </iframe> Within that iframe, a jQuery function is implemented as follows: <script ty ...

Emphasize specific letters in a word by making them bold, according to the user

In my app, there is a search feature that filters data based on user input and displays a list of matching results. I am trying to make the text that was searched by the user appear bold in the filtered data. For example, if the user searches 'Jo&apos ...

Identify when the user intends to open the link in a new window or tab

I am developing an AJAX application where all links on the page are JavaScript links (href="javascript:void(blahblah)"). Some of these links open small webpages in an iframe within a positioned div element that can be moved around. While this design looks ...

Attempting to evenly distribute items within a div container

My goal is to arrange the items in the container div evenly on a single line. I want them to be spaced out like this: I'm struggling to achieve this layout where the items are on the same line and evenly distributed within the available space. This ...

Is it possible to utilize AJAX to load the URL and then extract and analyze the data rather than

I had originally created a web scraping method using PHP, but then discovered that the platform I was developing on (iOS via phone gap) did not support PHP. Fortunately, I was able to find a solution using JS. $(document).ready(function(){ var container ...

WebRTC functions effectively within the same network, but encounters difficulty when communicating between different IP addresses

Please find my code on Github: https://github.com/rashadrussell/webrtc_experiment/blob/master/public/script.js I am currently working on developing a 1-to-1 video conferencing script using WebRTC. The script is hosted on AppFog, a cloud hosting platform. ...

The image slider is blocking the dropdown functionality of the navbar on mobile devices

My code is experiencing a conflict of events. I have created a menu bar using nav bar, as well as an image slider called the caroussel. The issue arises when the window is minimized - the menu bar fails to drop down properly with the presence of the caro ...

Regular expression to detect a space that is escaped

Given a string: rsync -r -t -p -o -g -v --progress --delete -l -H /Users/ken/Library/Application\ Support/Sublime\ Text\ 3/Packages /Users/ken/Google\ Drive/__config-GD/ST3 Attempting to find a regex pattern that matches spaces, but ex ...

Having trouble with Vue component registration repeatedly failing

Currently, I am working on a front-end project using [THIS VUE TEMPLATE][https://www.creative-tim.com/product/vue-material-dashboard-pro] The issue I am facing involves trying to register a component locally and encountering the following error: "1 ...