If admin access is enabled, the routing will be affected

Within my application, I have implemented 3 different access levels.

To grant the admin access to all pages, I inserted the following code in the admin section:

else if (claims.admin) { 
 return next() 
}

This configuration successfully allows the admin to navigate through all pages of the application.

However, a drawback arises where upon logging in as the admin, the admin remains on the login page without being redirected. My goal is for the admin to retain access to all pages while being directed to the admin.vue page upon logging in.

Below is the complete code snippet:

router.beforeEach((to, from, next) => {    
firebase.auth().onAuthStateChanged(userAuth => {
if (userAuth) {
  firebase.auth().currentUser.getIdTokenResult()
    .then(function ({
      claims
    }) {

if (claims.customer) {
  if (to.path !== '/customer')
   return next({
    path: '/customer',
   })
  } else if (claims.admin) {
  if (to.path !== '/admin')
   return next({
    path: '/admin',
   })
  } else if (claims.driver) {
if (to.path !== '/driver')
  return next({
   path: '/driver',
  })
 }     
 })
 })

Answer №1

This is simply a demonstration:

import VueRouter from 'vue-router';

const router = new VueRouter({
  routes: [
    {
      path: '/',
      component: homePage
    },
    {
      path: '/admin',
      component: adminPage,
      meta:
      {
        requiresAdmin: true
      }
    },
    {
      path: '/customer',
      component: customerPage,
      meta:
      {
        customerOnly: true
      }
    },
    {
      path: '/driver',
      component: driverPage,
      meta:
      {
        driverOnly: true
      }
    },
  ];
});

router.beforeEach((to, from, next) =>
{
  const role = getCurrentUserRole(); // fetch the role of the current user - or return NULL if the user is not logged in
  const requiresAdmin = to.matched.some(route => route.meta.requiresAdmin);
  const customerOnly = to.matched.some(route => route.meta.customerOnly);
  const driverOnly = to.matched.some(route => route.meta.driverOnly);

  if(!role && (requiresAdmin || customerOnly || driverOnly)) next({name: 'loginPage'});
  else
  {
    if(requiresAdmin)
    {
      if(role == 'admin') next();
      else next({name: 'accessDenied'});
    }
    else if(customerOnly)
    {
      if(['admin', 'customer'].includes(role)) next();
      else next({name: 'accessDenied'});
    }
    else if(driverOnly)
    {
      if(['admin', 'driver'].includes(role)) next();
      else next({name: 'accessDenied'});
    }
    else next(); // this is a public page
  }
});

export default router;

and in your Login.vue

// Utilize any authorization system you prefer
firebase.login().then(user =>
{
  let routeName = 'Dashboard';
  switch(user.role)
  {
    case 'admin':
      routeName = 'AdminHome';
      break;
    case 'drvier':
      routeName = 'DriverHome';
      break;
    case 'customer':
      routeName = 'CustomerHome';
      break;
  }
  this.$router.push({name: routeName});
});

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

Encountering the error "TypeError: Unable to access property 'controls' of undefined" when utilizing formArray in Reactive forms

Hi there, I am currently working on creating a dynamic form using formArray in Angular. However, I have run into an issue with the error message "TypeError: Cannot read property 'controls' of undefined." import { Component, OnInit } from ' ...

Nothing is in the Laravel array when using `$request->all()`

In the process of developing a shopping cart using Laravel. Here are the details : Routes : Route::post('/cart/add', 'CartController@store')->name('cart.store'); Route::patch('/cart/{product}', 'CartContro ...

Add more JSON entries to the data submission in Express

Purpose: My goal is to ensure that the JSON data I submit is formatted correctly when it arrives in the JSON file, regardless of the number of entries I submit. Challenge: Currently, the data I submit does not append properly in the JSON file. It appear ...

Executing the Javascript function after the dynamic loading of the table through an ajax request

After the table finishes loading, I would like to trigger a JavaScript function. Originally, I considered using the onload() function on the table, but I discovered that it does not actually work for tables. ...

What is the method for a JavaScript program to determine if a global property name has been defined according to the ECMA-262 standard

Imagine creating a function called checkIfEcmaGlobal which would return true for recognized names of ECMA-262 globals. $ node > checkIfEcmaGlobal('Array') true > checkIfEcmaGlobal('process') false What approach could be taken to ...

What is the best way to ensure that the bootstrap nav tab content fits perfectly on one line?

Check out this bootstrap navbar example You can see a screenshot here. <ul class="nav nav-tabs" style="display: inlne-block"> <li class="nav-item" style="text-align: center; display: inline;"> <div> <a class="nav ...

Creating a Cubic Bezier Curve connecting two points within a 3D sphere using three.js

I'm currently working on a project where the user can click on two points on a sphere and I want to connect these points with a line along the surface of the sphere, following the great circle path. I have managed to obtain the coordinates of the sele ...

Creating a custom map using React and Leaflet

Can anyone guide me on creating a map using leaflet? I am encountering the following issue. ./src/Map.js Attempted import error: 'Map' is not exported from 'react-leaflet' (imported as 'LeafletMap'). Below is the code I have ...

What is the best way to dynamically insert an object into a field name in react-final-form?

When using the react-final-form component, you can expect the following result: <Field name="answers[0].name" component="input" type="radio" value="0" /> { answers: [ { name: 'value' } ] ...

Maximizing the potential of Next JS 13 Server Components

Exploring the updates in Next JS 13, I have found it intriguing that every component is now a server component by default. This concept has been puzzling for me as I try to grasp how to effectively leverage this feature. For instance, my current challenge ...

Incorporate a dropdown menu based on the selection made in another dropdown menu

I have a scenario on my website where I want to dynamically add select boxes based on the value selected in the previous one. Here is the code snippet: <script type="text/javascript" src="http://code.jquery.com/jquery-1.4.2.js"> </script> & ...

VueJS showcasing information from an API

I'm having an issue with displaying data fetched from an API using Axios. Even though I can see the data when I console.log(app.books), it does not show up on the page as expected. I'm utilizing v-for to populate a table with the data, but someth ...

"Make sure to tick the checkbox if it's not already selected,

Could use some assistance with traversing and logic in this scenario. Here is the logic breakdown: If any checkbox in column3 is checked, then check the first column checkbox. If none in column 3 are selected, uncheck checkbox in column1. If column1 ...

Conflict between multiple jQuery files

Currently, I am in the process of creating a test website for an upcoming project. However, I have encountered some issues with jQuery. This is a static HTML5 website that includes a social widget. The problem arises when I remove a particular jQuery lin ...

What is the process for changing search box suggestions in Google and Wikipedia to radio buttons?

I recently integrated Google and Wikipedia search boxes into a webpage and I'm seeking a method to modify the suggestions based on the selected radio button. Specifically, the suggestion language should adjust according to the checked language option ...

Vue.js: The v-for directive demonstrates distinct behavior with the utilization of template literals

What is the difference in behavior of v-for when using numbers versus template literals? Consider the following scenario: new Vue({ el: "#app", }) <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script> <div i ...

Learn how to effortlessly retrieve shared properties using Vue3 in Single File Components with the new `<script setup>` syntax

There are various ways to extract common props in Vue components, depending on whether you are using Vue 2 or Vue 3. However, when it comes to Single File Components (SFC), the approach differs. // common-props.js export default { commonProps: { enab ...

Retrieving the parent value in React-select grouped options

When using react-select with grouped options, the structure is as follows: { label: PARENT_NAME, value: PARENT_ID, options: [ { label: CHILD_NAME, value: CHILD_ID, } ] } An array of these options is passed to the component lik ...

Tips for duplicating specific div elements

Is there a way to create copies of selected divs within the same panel using a Javascript report designer? I attempted to achieve this by using the following code snippet: function DesignerClone() { $(".ui-selected").each(function () { va ...

Deleting data while retaining it in a separate location by leveraging nodejs and

Is there a way to implement a soft delete in nodejs for MongoDB? If I have the following code, can it be modified to perform a soft delete instead or is there a different approach? Controllers/ category.js exports.remove = (req, res) => { const c ...