Redirecting users based on their type - Vue router

Seeking assistance as a novice in vue. Building an app with firebase-connected login. Want to utilize vue-router for user redirections. Goal: Redirect "admin" users to "/admin", others to "/", and non-logged-in users to "/login". Sharing parts of my code:

Main.js

router.beforeEach((to, from, next) => {  
  const currentUser = firebase.auth().currentUser;  
  const requiresAuth = to.meta.requiresAuth;
  if (requiresAuth && !currentUser){ next({ name: 'Login' })} 
  else if (!requiresAuth && currentUser) {next({name: 'Dashboard'}), console.log(currentUser)} 
  else next();
});

authStore.js

const actions = { 
  logIn({ dispatch,commit,rootGetters }){
      firebase.auth().onAuthStateChanged(async (user) => {
        if (user) {       
          commit('SET_USER', user);

         var uid = user.uid;
            db.collection('users').doc(uid)
            .get()
            .then((doc)=>{
            commit('gutscheinStore/SET_USER_ROLE', doc.data().role, {root:true})
            commit('gutscheinStore/SET_USER_STANDORT_ID', doc.data().standortID, {root: true})
            commit('gutscheinStore/SET_USER_BETREIBER_ID', doc.data().betreiberID, {root: true})
                //console.log(rootGetters['gutscheinStore/getUserRole'])
              })
   
          router.push('/')
        } else {
          console.log("No entry without login")
        }
      })
  },

index.js within router

const routes = [
  {
    path: '/',
    name: 'Dashboard',
    component: Dashboard,
    meta: {
      requiresAuth: true,
    }
  },
  {
    path: '/login',
    name: 'Login',
    component: Login
  },
  {
    path: '/admin',
    name:'AdminDashboard',
    component: AdminDashboard,
    meta: {
      requiresAuth: true,
    }

Answer №1

When working in the file authStore.js, consider modifying the following line from router.push("/"):

const actions = { 
          ...
          // snipped for clarity
   
          router.push('/')
        } else {
          console.log("No entry without login")
        }
      })
  },

A better approach could be to make the following changes:

const actions = { 
          ...
          // snipped for clarity

          if(user.role === "admin") { 
            router.push("/admin")
          } else {
            router.push("/")
          }
        } else {
          // router.push("/login")
          router.go()
        }
      })
  },

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

Is there a glitch in my redux-saga?

After developing a React Native app, I encountered an issue with my index.ios.js file where I was adding middlewares to the store. import React, { Component } from 'react' import { AppRegistry, } from 'react-native' import { Provider ...

Customize text using vue.js and slot-scope for added style

Presenting text within an Element-ui table element in the following manner: <el-table> <el-table-column label="Action"> <template slot-scope="scope"> {{formatModel(scope.row.subject_type) + ': ' ...

How can I make the lines of my drawer thicker in Material UI?

Currently, I'm in the process of implementing a left-side navigation bar for a web application I'm developing. The main challenge I'm facing is customizing the styles as desired when using the Drawer component. Specifically, I'm aiming ...

How can I create an event that is specific to only one element in Vue.js?

I am currently facing an issue with Vue events attached to looped elements. My challenge lies in displaying CRUD actions on individual items. Currently, all looped items display their own set of CRUD actions. Is there a way to make these actions unique t ...

What can I do to stop a webpage from automatically refreshing when I submit a form?

I'm currently in the process of building my very first website, and I've run into a bit of a snag that I can't seem to figure out. Whenever a user tries to add an item to the cart or increase the quantity, I want to avoid the page refreshing ...

Retrieving all options from a dropdown list in HTML using ASP.net C#

I am currently working with a select list that looks like this: <select name="Section" id="Section" size="5"> <option>Section1</option> <option>Section2</option> <option>Section3</option> <option>Section4< ...

Encountering a "Window is undefined" error while trying to load a node_module package within a

I am attempting to incorporate the pickr package (a color picker library) into my nuxt.js application. However, I am encountering an error during import, specifically "window is undefined". Below is the code snippet: <script> import Pickr from &apo ...

How to modify this to return a function and eliminate the need for declaring a function

Greetings! I understand that this may seem simple to some of you, but I am feeling quite lost. I've been tasked with removing the function declaration and converting it into a return function. Any assistance would be greatly appreciated. const canView ...

Ways to prevent an array from being reset

My issue involves the clothes and orders tables, along with an array based on Clothes and Orders models. Whenever I add a clothes element into the Orders array and specifically update the amount and price of the selected item, it also updates the Clothes a ...

Mastering the art of integrating HTML5's localstorage feature with Jquery's select2 plugin

Is it possible to integrate HTML5's localstorage method with Jquery's select2 plugin? Currently, all entered data disappears when the browser/tab is closed, leading to potential confusion if you forget what was entered. Here is an example of my ...

Can you explain the step-by-step process of how an await/async program runs in TypeScript/JavaScript or Python?

As a C++ developer specializing in multithreading, I've been diving into the intricacies of async/await. It's been a challenge for me as these concepts differ from how C++ programs are typically executed. I grasp the concept of Promise objects, ...

Issue with Vue3: The imported module is not defined

Update: I recently downgraded vue-cli to version 4.5.19 and now the code is functioning properly. It seems like there might be an issue related to vue-cli or its dependencies. I encountered a problem while working on a simple vue.js project using vue-cli. ...

Displaying an array within a method using Vue.js

As a complete newcomer to Vue, I wanted to experiment with methods a bit. Specifically, I attempted to print out an array of strings using the following method: printStringArray(objectWithArray) { i = 0; s = ''; while(i < ob ...

Is there a way to dynamically insert objects into an array from an ajax json request, in order to iterate through them later on?

I have a current code where I am trying to utilize data to create a new information window from the Google Maps API dynamically. Currently, I am pushing objects of different data types into an array, but I believe that might be the only issue here. How c ...

Scrolling using JavaScript's 'smooth scrolling' feature is currently disabled

Background of the Issue: I am in the process of creating a one-page website using Twitter Bootstrap 3 within an ASP.NET MVC project. The Challenge: My current challenge involves implementing 'smooth scrolling' functionality that scrolls to the ...

Why is the "class" attribute of an SVG node not being applied when I change it?

I am having trouble changing the "class" attribute of a node in SVG using my AngularJS Directive. Even though I've written the code to do so, it doesn't seem to be applied properly. This is the code snippet from my Directive: node = node.data(f ...

Locate the child element that has a particular class assigned to it

I need help writing a code to search through all children elements in order to find a div with a specific class. Unfortunately, the DIV I am looking for does not have an ID. Below is the sample HTML that I will be working with: <div class="outerBUB ...

Having trouble getting "Hello World" to display in ReactJS

I can't seem to get "hello world" as the output in my code. It's a simple code, but I'm getting a different result when using the createElement function. I'm still new to react and could use some help. Here is the code: <!DOCTYPE h ...

Scrolling with jQuery just got a sleek upgrade with our new

Can anyone suggest a jQuery scrollbar that resembles the clean black bar found on the iPhone? I need a simple design without visible up or down buttons. Many scripts I came across offer more features than necessary for my project. My div element has a fi ...

I can't seem to shake off this constant error. Uncaught TypeError: Unable to access property 'classList' of null

I am facing an issue with the "Contact Me" tab as it does not display its content when clicked. Here is the code snippet: <body> <ul class="tabs"> <li data-tab-target="#home" class="active tab">Home< ...