Securing child paths in Vue.js

Having trouble protecting child routes from parent routes, facing some issues

    export default new Router({
    routes: [
    //frontend routes
    {
      {path: 'auth', component: Auth, children: authroutes,
        beforeEnter: (to, from, next) => {
        // check if user is a guest or loggedin
        auth.canAccess(permissions.is_guest)
          .then((res) => {
            if (res.data.status) {
              next();
            } else {
              router.push('/auth/not-allowed');
            }
          })
       }}
      ]
     }
   ]
 })

Currently dealing with child routes

authroutes.js

const authroutes = [
  {path: '', redirect: 'login'},
  {path: 'login', component: Login, name: "login" },
];

Applying the above beforeenter function to child routes works but causes code repetition

Seeking a way to protect children from the parent route

For example: protect /auth/login and /auth/register

Answer №1

To secure specific fields in your routes, utilize the route's meta field in the following manner:

const securedRoutes = [
    {path: '', redirect: 'login', meta: {requiresSecurity: true}},
    {path: 'login', component: Login, name: "login", meta: {requiresSecurity: true}},
];

Subsequently, set up your router to verify if the route contains a designated meta field and execute your redirection logic as needed.

router.beforeEach((to, from, next) => { 
    if (to.matched.some(record => record.meta.requiresSecurity)) { 
        auth.checkPermission(permissions.is_guest)
              .then((res) => {
                if (res.data.status) {
                      next();
                } else {
                     next('/auth/not-allowed');
                }
              })
    } else { 
        next(); // Ensure to always call next()! 
    } 
});

For further details, refer to: Route meta fields

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

I am attempting to implement an Express static middleware as demonstrated in this book, but I am having trouble understanding the intended purpose of the example

I'm currently studying a chapter in this book that talks about Express, specifically concerning the use of express.static to serve files. However, I'm encountering an issue where the code catches an error when no file is found. I've created ...

Error message occurs during compilation of basic Vue file in Webpack

When I execute webpack watch in the VS2017 task runner, it displays the following error: ERROR in ./wwwroot/js/src/App.vue Module build failed: SyntaxError: Unexpected token { at exports.runInThisContext (vm.js:53:16) at Module._compile (module.js:373:25) ...

Utilize a reactive ref to increment values within a v-for iteration

I am encountering a challenge while attempting to showcase two separate arrays using Vue's for loop. The arrays both contain 0-n strings, and I aim to exhibit a maximum of 3 strings combined from both arrays. Here's the gist: Scenario 1: in th ...

What is the best way to bring an image into your nextjs project?

I have a question about importing images into my Next.js project. I created an array of objects and want to import an image stored in a folder on my laptop, specifically in the src folder rather than the public folder. How can I properly achieve this in ...

The for loop encountered an uncaught type error when trying to access the .length property

Currently, I am working on a school project where the task is to create a basic social network posting application using Django and JavaScript. The purpose of using JavaScript is to dynamically load posts onto the webpage and update HTML components. I have ...

JavaScript does not recognize the $ symbol

Firebug is indicating that there is an issue with the $ variable not being defined. I have a basic index.php page that uses a php include to bring in the necessary content. The specific content causing the error is shown below: <script type="text/jav ...

Tips on how to showcase particular keys from json information in React

Here is a sample of Json data that I have: [ { "serial_number": "test1", "added_at": "2021-02-05T18:58:43.382943Z", "ser_mod": [ { "added_at": "2021-02-06T02: ...

Ensuring thoroughness in validation without the use of specific text strings

Implementing the assignment or assertion of never at the end of a function is a strategy commonly used in Typescript to ensure exhaustive checks at compile time. To enable the compiler to recognize this, explicit strings are needed for it to check against ...

having trouble accessing a JavaScript array in AngularJS

Hey there, I'm currently working on a web application using AngularJS and I'm facing an issue with querying arrays. Check out the code snippet below: var angulararray = []; bindleaselistings.bindleaselistingsmethod().then(function(response) { ...

Developing components with jQuery

I have a JavaScript program that works perfectly when I use the following line of code: li = $("<li data-role='collapsible' data-iconpos='right' data-inset='false'></li>"); However, if I change the above line ...

Changing the sliding underline effect in a jQuery navigation bar

Recently, I implemented a sliding underline element in my navigation bar. The idea is that when a link is hovered over, the underline smoothly transitions to that element. You can take a look at the codepen example here: https://codepen.io/lucasengnz/pen/e ...

JavaScript: specify parameters for function inputs

I'm curious about optimizing Javascript/Typescript functions arguments for clean code. To demonstrate, let's consider a basic example. Imagine I have a React component with a view property as props: <Grid view="Horizontal" /> ty ...

Alternative to using the disabled attribute in JavaScript to make a checkbox read-only option

Does anyone know how to make a checkbox readonly so that its value can be submitted, while also disabling it? Using the disable attribute prevents the value from being submitted, and setting it as readonly doesn't seem to work for checkboxes. Your as ...

Designing webpages by superimposing text onto images with customizable positioning

My current project involves developing an HTML document with a floor plan image as the main layer. On top of this image, I need to display employee names extracted from a database and positioned on the map based on a location variable within the database ...

Highcharts displays data with the fourth y axis but doesn't include labels for it

I'm facing an issue with displaying all the labels on my chart. I have 4 series plotted and decided to add two y-axes on each side of the graph, but the labels for the last series named "Stuff Data" are not showing up correctly. Instead, it seems to b ...

Sending JSON array from PHP to jQuery AJAX

Currently, I am working on an experimental project where I need to search for a product in a MySQL database using the product name and retrieve the price in the 'price input' field and sell price in the 'sellprice input' field. You can ...

Issue with jsPDF: PNG file is either incomplete or corrupted

I'm encountering an issue while attempting to pass Image data to the addImage function. I have tried downgrading the versions of jspdf and html2canvas, as well as experimenting with different ways to import the two libraries, but the problem still per ...

Node.js local storage/cookie functionality

Running three different apps on Node.js at ports 3000, 3005, and 3007. I need to set a LocalStorage or Cookie variable at port 3000 and access it from the apps running at ports 3005 and 3007. Folder structure: nodep/ |-app.js (runs at port 30 ...

Load content within the DIV container

I need help finding code that can use JQuery to load a page into a DIV element. Essentially, I want to load displaycatch.php into a specific DIV <div id="results">Content for id "results" Goes Here</div> Furthermore, I would like to add a ...

Exploring the differences between jQuery's methods for retrieving text, HTML, JSON

I'm feeling a bit perplexed: When I use the following code: $.get('http://externhost/somefile.js', callback, 'text'); I receive the error message: XMLHttpRequest cannot load http://externhost/somefile.js. Origin http://www.myho ...