Send the user to a customized dashboard depending on their user role permissions using Vue.js

Currently, I am developing a system that involves handling multiple role-permissions for users. To provide some context, there are 3 distinct users in this scenario: User1 (customer), User2 (employee), and User3 (admin).

For each of these user types, I have created separate dashboard pages. The goal is to automatically redirect users to their respective dashboard based on their assigned role. Additionally, I want to implement route guards to prevent unauthorized access. If an individual attempts to manually navigate to a specific page by typing the URL without permission, they should be redirected to a 404 error page.

Here are some questions that I have regarding the implementation:

  1. What would be the most effective way to store user role-permissions? Should I utilize the browser's local storage or opt for vuex?

  2. Is it advisable to verify the user's role-permissions within the router.js file to facilitate redirection to the appropriate dashboard? Alternatively, should this validation process take place within the login.vue component?

  3. Where should the guards be set up to ascertain whether a user possesses the necessary authorization to access a particular route and handle the redirection to the 404 error page for unauthorized users?

If possible, please provide detailed explanations for your answers. While I have already familiarized myself with vue-router and routing in nuxt.js, I welcome any additional resources or insights that could offer further clarity on this matter. Feel free to share such recommendations in the comments section for my reference.

import { constant } from 'lodash';
import Vue from 'vue';
import Vuex from 'vuex';

Vue.use(Vuex);

export const store = new Vuex.Store({

    //Vuex States
    state:{
        permissions:[],
    },

    //Getters 
    getters:{
        authPermissions: state => state.permissions
    },
    
    //Mutation
    mutations:{
        setPermissions: (state, fetchedData) => (state.permissions = fetchedData)

    },

    //Mutation with Actions
    actions:{
       async fetchAuthPermissions({ commit }){
            let token = localStorage.getItem('token');
            let formData = new FormData();
                formData.append("token", token);
                const response = await axios.post("api/userPermissions/", formData);
                commit('setPermissions', response.data.permissions);
       }
    }
    
})

Answer №1

I will provide answers to the questions that I am confident about.

Question 2

To manage user permissions, you can implement a system in the login page where users are redirected to the appropriate page based on their permissions, and then store these permissions in Vuex for easy access throughout the application.

   Login() {
        axios.post('/login')
            .then(({ data }) => {
               this.$store.commit("SET_ PERMISSIONS", data.data.permissions);
                if (data.data.user.permissions == 'customer') {
                    router.push({ name: "customerComponent" });
                } else if (data.data.user.permissions == 'employee') {
                    router.push({ name: "employeeComponent" });
                } else if (data.data.user.permissions == 'admin') {
                    router.push({ name: "adminComponent" });
                }
            })
            .catch((error) => {
                console.log(error);
        });
    }

Question 3

For restricting access to certain routes based on user permissions, you can utilize the router's beforeEach function. This way, before navigating to a route, the system will check if the user has permission and redirect them to a 404 page if necessary.

router.beforeEach((to, from, next) => {

//split the url
let path = to.path.split("/")[1]

//Customer
if (store.getters.permission == 'custome' && path == 'customer') {
    next()
}
//employee
else if (store.getters.permission == 'employee' && path == 'employee') {
    next()
}
//admin
else if (store.getters.permission == 'admin' && path == 'admin') {
    next()
} else {
    // redirect to 404 page here
    router.push({ name: "404Component" });
}})

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

Using TypeScript: Implementing array mapping with an ES6 Map

If I have an array of key-value objects like this: const data = [ {key: "object1", value: "data1"}, {key: "object2", value: "data2"}, {key: "object3", value: "data3"}, ] const mappedData = data.map(x => [x.key, x.value]); const ES6Map = n ...

What could be causing the issue with the initialization of useState not working as expected?

I have the following React code snippet: import React, { useState, useEffect } from "react"; import axios from "axios"; function App() { const [players, setPlayers] = useState([]); // Fetch all Players const getAllPlayersUrl = & ...

Could you please ensure that the animation activates upon hovering over the "a" element?

Utilizing bootstrap, I have created the following code. I am looking to add functionality that triggers an animation upon mouseover of an img or a element, and stops the animation upon mouseleave. .progress-bar { animation: pr 2s infinite; } @keyfr ...

Is there an efficient method for transferring .env data to HTML without using templating when working with nodejs and expressjs?

How can I securely make an AJAX request in my html page to Node to retrieve process.env without using templating, considering the need for passwords and keys in the future? client-side // source.html $.get( "/env", function( data ) {console.log(data) ...

What is the best way to display live data to multiple users with React and Firebase?

I'm working on a messaging app that needs to update in real-time. Currently, I have implemented the functionality to log in using Google, post messages, and display them on the screen. However, when another user logs in with a different Google account ...

Having trouble with your jQuery code not loading properly?

Currently working on debugging jQuery code and facing an issue where a particular section of the code is not being triggered upon clicking. The HTML/PHP in question: $cartlink .= "<a class='add_to_cart button' data-id='{$product->id} ...

Which symbol is preferable to use in JS imports for Vue.js/Nuxt.js - the @ symbol or the ~ symbol?

I am seeking guidance on a matter that I have not been able to find a clear answer to. Webapck typically uses the ~ symbol as an alias for the root directory. However, I have noticed that some developers use the @ symbol when importing modules using ES6 s ...

What is the best way to handle requests once a SpookyJS script has finished running?

Occasionally, I find myself needing to log in and extract some data from a specific website. To automate this process, I developed a CasperJS script that runs on Heroku. My goal is to create an endpoint like the following: app.get('/test', func ...

Transform a list of file directories into a JSON format using ReactJS

I am developing a function that can convert a list of paths into an object structure as illustrated below; this script will generate the desired output. Expected Output data = [ { "type": "folder", "name": "dir1& ...

Angular 6 CSS spacing dilemmas

We recently made the switch from Angular 5 to Angular 6 and noticed that there is no spacing between the buttons/icons, etc. We are looking to bring back the spaces between the buttons and icons. I have recreated the issue below. As you can see in the Ang ...

How to access the public folder in React from the server directory

I am having an issue with uploading an image to the react public folder using multer in NodeJs. Everything was working fine during development, but once I deployed it, the upload function stopped working. It seems like the multer is unable to reference or ...

Does the notion of "Execution context and the stack" only pertain to web browsers?

Does the concept of "Execution context and the stack" only apply to browsers, or is it also utilized in other environments such as NodeJS? I've crafted 2 statements but unsure if they are accurate: 1- "The environment for JavaScript is not solely the ...

Displaying dynamic text using radio buttons utilizing React

Currently, I am in the process of developing a multiple choice quiz where each question is presented with various options displayed as radio buttons. My main objective is to show specific text related to the option selected by the user when they make a ch ...

Encountering crashes when trying to map JSON data onto React components

I have created a menu items application that displays products from a JSON file. When an item is clicked, it shows some modifiers for that item. Everything works well until certain categories or items are clicked, causing the application to crash. To test ...

Using Javascript to display an element when scrolling within a specific container and each item of an array reaches the top

I'm just starting out with JavaScript and I'm attempting to create a scrollable div that includes items from an array. As the user scrolls and each item reaches the top, I want a hidden element to be displayed. Here's what I have so far: ...

JavaScript: the battle between anonymous and direct function invocation

Here is an interesting observation: when I assign an anonymous function to the onreadystatechange variable, everything works fine. However, if I try to assign a named function to this variable, it does not work as expected. <script language="Javascrip ...

Ways to extract information from JSON files

Currently, I am working on a script to extract viewer count and follower count data from Twitch. While I have successfully retrieved the viewer count information, I am encountering issues with extracting the follower count. The essential information can be ...

Tips for eliminating fade effect during hover in networkD3 chart in R

Currently, I have been exploring the usage examples of networkd3 in r I am curious if there is a way to eliminate the hover effect where everything else fades when hovering over a specific node in the graph. For reference, check out "Interacting with igra ...

Is there a way to prevent the URL of my Next.js app from constantly changing?

Our current Next.js project requires that the static URL remains constant, even when navigating between pages. This is a client requirement that we must adhere to. Can you provide suggestions on how we can achieve this? Maintaining the same URL throughout ...

Concatenating strings with JavaScript

I am currently working on building a web page using a combination of html and javascript. I have a json file that provides inputs for some specific content I need to display. My main goal is to set up an address variable in order to show the Google Maps AP ...