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

AngularJS does not hide the Onsen UI modal

I am new to working with angularjs and onsen ui. I have implemented a modal in an ajax request, which is supposed to hide upon successful response. Everything seems to be working fine, except for the fact that when I navigate back to the page, the modal re ...

How can I access an array option that combines both global and target-specific specifications within a grunt plugin?

Currently, I am in the process of creating a grunt plugin that includes options which can consist of arrays of values. These values are specifically file paths (distinct from the files listed in the task's own 'files' property). The setup fo ...

How can I efficiently extract specific data from JSON using AngularJs?

In my array (_users), there are JSON objects. { "User": { "userid":"19571", "status":"7", "active":"1", "lastlogin":"1339759025307", "Stats": [ { "active":"1", "catid":"10918", "typeid":"71", ...

Ionic: setInterval/setTimer not functioning after 5 minutes in the background

In need of a timer that can send notifications via the OneSignal API after a user-defined time period is reached. Users can set the timer for any value between 1-59 minutes. Despite attempts to use the background mode plugin, specifically setInterval and s ...

Upgrade your development stack from angular 2 with webpack 1 to angular 6 with webpack 4

Recently, I have made the transition from Angular 2 and Webpack 1 to Angular 6 and Webpack 4. However, I am facing challenges finding the best dependencies for this new setup. Does anyone have any suggestions for the best dependencies to use with Angular ...

Is there a way to transfer a JavaScript variable created by an API to a PHP variable within a form submission?

I have some variables that are being generated by a JavaScript script and I am looking for the most effective way to pass them back to the PHP program that initiated the script. Since there are several variables (4-5), I prefer not to pass them through the ...

Scrolling to an id element in Vue.js can be achieved by passing the ID in the URL using the "?" parameter. This

My challenge involves a URL http://localhost:8080/?london that needs to load directly to the element with an id of london in the HTML section <section id="london"> on the page. Using http://localhost:8080/#london is not an option, even though it woul ...

When utilizing Rx.Observable with the pausable feature, the subscribe function is not executed

Note: In my current project, I am utilizing TypeScript along with RxJS version 2.5.3. My objective is to track idle click times on a screen for a duration of 5 seconds. var noClickStream = Rx.Observable.fromEvent<MouseEvent>($window.document, &apos ...

Angular Square Grid Design

Attempting to create a square grid layout using CSS for ng-repeat items. Essentially, I am looking to have one big square followed by four smaller squares that combined have the same width and height as the big square. Here is my CSS: .container{ widt ...

The issue of the marker vanishing upon refreshing the page on AngularJS

Currently, I am encountering a rather peculiar issue. Upon the initial page load, the code snippet below correctly displays a marker at the specified coordinates and ensures the map is properly centered: <div class="paddingtop"> <map data-ng- ...

Selecting radio buttons across multiple div classes

I've been struggling to programmatically select specific radio buttons on a webpage. My goal is to automatically choose the second option in each group of radio buttons, but I'm getting lost in the syntax. Unlike most examples I've found on ...

Issue with calling function from props in React is not being resolved

There seems to be an issue with the function not being called when passed into a functional component. While the onSubmit function is triggered, the login(email, password) function inside the Login component is never executed. Despite placing console.log s ...

In Vue.js, I am looking to pass data from a component to a JS file without involving other components. While I can easily access the data within the component itself, I am facing difficulty in

How can I emit an event from the Abc.vue component and listen to it in a .js file without involving other components? <template> <div class="hello"> <div> <input v-model="clickCount" placeholder="edit me" v-on:change="emit ...

What is the best way to update the displayed data when using Mobx with an observable array?

Is there a way to re-render observable array data in Mobx? I have used the observer decorator in this class. interface IQuiz { quizProg: TypeQuizProg; qidx: number; state: IStateCtx; actions: IActionsCtx; } @observer class Comp extends Rea ...

What is the best method to assign a property to a model within AngularJS by utilizing an attribute parameter?

I am in the process of creating a custom directive in AngularJS for a UI slider that can be used multiple times. Each slider should be able to bind to a specific property. My idea was to use an attribute called "property" which would automatically update w ...

Loading time for page style can be slow when using Next Js

When the user opens or reloads the page, there is a delay in loading the style of the page. I am relatively new to working with next js and still learning the core abilities of the framework. This GIF illustrates the slow loading time when opening or relo ...

Having trouble with Wookmark not working in Jquery UI?

Hey there, just wanted to share that I'm currently utilizing the Wookmark jQuery plugin $.post('get_category',data={type:'All'},function(data) { $.each(data,function(item,i){ var image_ ...

Customize the appearance of radio buttons in HTML by removing the bullets

Is there a way for a specific form component to function as radio buttons, with only one option selectable at a time, without displaying the actual radio bullets? I am looking for alternative presentation methods like highlighting the selected option or ...

Establish height and width parameters for creating a dynamic and adaptable bar chart with recharts

I am currently facing an issue with recharts while trying to implement a BarChart. The setting width={600} and height={300} is causing the Barchart to be fixed in size, rather than responsive. How can I make the BarChart responsive? I attempted using per ...

Computed Property Output Remains Static in Template Usage (Vue3 sans Composition API)

I need to retrieve the width of an item in order to pass it as a CSS variable within a computed property. <div class="wrapper"> <fieldset> <legend :style="`--gap:${legendGap}px`"></legend> </fieldset&g ...