Troubles arising from JavaScript functions within vue-router

I have implemented a function to authorize users, enabling restrictions on specific components based on their permissions. The function currently works effectively with the 'beforeEnter' navigation guard in Vue Router. However, I am facing difficulties trying to integrate the same function within the router's beforeEach guard.

When attempting to write the function inside the beforeEach guard, I encountered issues with JavaScript functions like 'forEach' and 'includes' not working as expected within router.beforeEach.

Below is the function used for authorization:

function authorizeUser(to) {
  const currentUser = store.getters["auth/isCurrentUser"];
  console.log(currentUser);
  currentUser.teams.forEach((team) => {
    const validPermissions = team.permissions.filter((item) => { return to.meta.neededPermissions.includes(item.permissionType); }); 
    const mappedValidPermissions = validPermissions.map((item) => { return item.permissionType; });
    console.log(
      JSON.stringify(to.meta.neededPermissions),
      JSON.stringify(mappedValidPermissions),  
    );
    if (!to.meta.neededPermissions.every(i => mappedValidPermissions.includes(i))) {
      router.push({ path: "/:notFound(.*)" });     
    }  
  });
}

Below is the router.beforeEach navigation guard code snippet:

router.beforeEach((to, from, next) => { 
  if (to.meta.requiresAuth && !store.getters["auth/isLoggedIn"]) {
    next({
      name: "Authentication",
      params: {
        desiredRoute: to.fullPath,
      },
    });
  } else {
    next();
  }
});

I am seeking guidance on how to effectively utilize the above function alongside the specified if condition within the beforeEach guard to validate each router link before granting access.

Answer №1

Which version of vue-router do you have installed? It's important to note that the latest version has made a change to the signature of the beforeEach method. Now, instead of simply calling next, you can choose to either return false or a route location object.

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

angular-in-memory-web-api encounters a 404 error

I recently completed the heroes tour and now I am trying to work on something similar, but I seem to be having trouble understanding angular-in-memory-web-api. Here is a snippet of my code: clients-data.service.ts import { Injectable } from '@angular/ ...

Is it possible to retrieve HTML content using YQL?

Imagine the scenario where you need to retrieve information from a web page structured like this: <table> <tr> <td><a href="Link 1">Column 1 Text</a></td> <td>Column 2 Text</td> <td>Colum ...

problem with making ajax requests during the server-side processing of DataTables

Currently tackling server-side processing with datatables, but encountering an ajax error that I'll detail shortly. First things first, here's my code: Table <table id="call_analysis_basic_table" class="display" cellspacing="0" width="100%"& ...

The click event that is dynamically added is triggered multiple times

On clicking a button, I am dynamically adding a row to an HTML table. The row contains a cell with a list item (li) element which has a click event assigned to it. However, when I click on the list item, the event fires multiple times and I'm unsure w ...

Error with jQuery variables

I'm encountering an issue with my code. The input box I have should display the value of a button when clicked. What I want is for the currently displayed value in the input box to be saved in a variable when a button is pressed, and then update to s ...

Leveraging the fromNow() method in UTC with moment.js

How can I ensure that my VueJS filter converts a given date into the fromNow() format in UTC time? fromNow(date) { return moment.utc(date).fromNow(); } The timestamp provided by my Laravel backend is already generated in UTC, but the ...

What is the best way to choose a single li element?

I am working on creating a reservation system using HTML, CSS, and JS. I want to customize the color of the border for each list item (li). However, I want only one li to be selected at a time. When I click on a different li, it should remove the selection ...

How can the onclick attribute be modified in an HTML document?

I am looking to update the data-pro-bar-percent attribute of a progress bar from 80 to 100 when a specific link is clicked. The change in attribute needs to be as follows: data-pro-bar-percent="80" --> data-pro-bar-percent="100" This is the current HT ...

Incorporating traditional Bootstrap styling directly into a React application without relying on the react-bootstrap library

My goal is to incorporate my existing bootstrap components into a React project without having to rewrite them to work with the react-bootstrap library. While I have successfully integrated the bootstrap CSS, I am facing issues with the functionality aspec ...

Using Javascript to Assign Value to Variables

I have been working on this code snippet: http://jsfiddle.net/9B84H/26/ function autosuggest() { var input = document.getElementById('location'); var options = {types: [],}; var autocomplete = new google.maps.places.Autocomplete(input, o ...

Unusual Characteristics of Synchronous Ajax Requests in JavaScript

First and foremost, I'd like to apologize if my approach seems unconventional. My background is primarily in C development, so I tend to tackle AJAX issues in a way that reflects my experience in C programming. The scenario at hand involves a script ...

Searching for text using JQuery autocomplete feature with results fetched from an external source

I am currently working on integrating an input field with autocomplete functionality using the Google Books API to suggest book titles based on user input. My framework of choice for this implementation is Django. So far, I have managed to achieve the fol ...

Delete an entry in a singular mapping in a one-to-one connection [TypeORM]

Is there a way to remove an index from a one-to-one relationship in TypeORM? @OneToOne(() => Customer, { cascade: true }) @JoinColumn({ name: 'customer', referencedColumnName: 'uid' }) customer: Customer I searched the d ...

What is the correct way to add a period to the end of a formatted text?

Hello, this marks the beginning of my inquiry. I apologize if it comes across as trivial but I have come across this piece of code: function format(input){ var num = input.value.replace(/\./g,''); if(!isNaN(num)){ num = num.toString ...

Error in Firebase Cloud Function: Function did not return the expected Promise or value and instead returned undefined

I've been encountering an issue with my cloud function that triggers on specific database writes (onCreate). It seems to be working fine, but I keep getting an error message stating "Function returned undefined, expected Promise or value" even though ...

Struggling to make EJS button functional on the template

I am currently facing an issue with a loop that populates a webpage with multiple items, each containing an image, text, button, and a unique ID associated with it. Although I have written a function to retrieve the ID and plan name when the button is clic ...

What is the best way to clear the selected option in a dropdown menu when choosing a new field element?

html <div class="row-fluid together"> <div class="span3"> <p> <label for="typeofmailerradio1" class="radio"><input type="radio" id="typeofmailerradio1" name="typeofmailerradio" value="Postcards" />Postcards& ...

Split an array of simple data types in JavaScript into separate sections

Is there a way to divide an unordered array of primitive types into specific segments like this: var array = [102,103,104,201,203,204,303,301,302,405,406,408,101]; => newArray = [[101,102,103,104],[201,203,204],[303,301,302],[405,406,408]] The divi ...

Incorporating external resources into Laravel

Though it may be an old question, I have never attempted it before and have been unable to find a solution (all the samples I found were in scss files). Currently, I am using JavaScript scaffolding as my front-end, so all I have in my layout assets is: & ...

What is the process for assigning a value to the body in a div element?

Within a div, there is a body element structured like this: <div id = "TextBox1"> <iframe id = "TextBox1_1"> #document <html> <head></head> <body></body> </html> </iframe> </div> I have attempte ...