What are the steps to restrict a user from accessing a specific website?

In my Vue.js project, I've implemented a function that hides a specific menu item for users with insufficient permissions:

<a :href="href" @click="navigate" v-if="hideMenuItem()">
    // some code
</a>

hideMenuItem() {
    if(currentUser.permission == 'All') {
      return true;
    } else return false; 
}

This successfully hides the element on the UI, preventing the user from accessing a certain page by clicking on an anchor link. However, there is a loophole where the user can still access the page by directly entering the URL in their browser. How can I prevent this?

Any help would be appreciated. Thank you!

Answer №1

To achieve this functionality, it is essential to utilize Vue Router and set up validation within the beforeEach loop as outlined in the documentation on [Navigation Guards]: https://router.vuejs.org/guide/advanced/navigation-guards.html#global-before-guards

Here is an example of how you can implement it:

router.beforeEach(async (to, from, next) => {
  const currentUser = store.state.currentUser
  if (currentUser.permission !== 'All') {
    next(loginPage)
  } else {
    next()
  }
})

Answer №2

To implement this logic for a specific page, consider using Navigation guards. You can find more information about Navigation Guards here.

When setting up routes in your routes file, include metadata to control access:

{
    path:'/yourPath',
    meta:{guest:false},
    component:YourComponent
}

Here's an example of redirecting users to the /login page if they are not authenticated:

// INCORRECT
router.beforeEach((to, from, next) => {
  if (to.name !== 'Login' && !isAuthenticated) next({ name: 'Login' })
  // calling `next` twice when user is unauthenticated
  next()
})
// CORRECT
router.beforeEach((to, from, next) => {
  if (to.name !== 'Login' && !isAuthenticated) next({ name: 'Login' })
  else next()
})

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

Error: Unable to access unknown properties (reading 'extend')

Struggling to integrate the Vuetify library into my current Vue 3 project, encountering complications. An error message popped up post-compilation: vuetify.js?ce5b:42021 Uncaught TypeError: Cannot read properties of undefined (reading 'extend') ...

Incorporate personalized design elements within the popup component of Material-UI's DataGrid Toolbar

I am in the process of customizing a Data Grid Toolbar component by making adjustments to the existing Grid Toolbar components sourced from Material-UI. For reference, you can view the official example of the Grid Toolbar components here. Upon clicking o ...

Tips for customizing the appearance of the span tag within the option text of an HTML select

Unique Link In my current situation, I am facing an issue where the asterisk in the first option of my HTML select element should be displayed in red color. Despite my efforts to style it, the asterisk always appears in the default black color. I have pr ...

The response code in the API remains 200 despite setting the status code to 204 in NestJS

I have developed an API that needs to return a 204 - No Content Response import { Controller, Get, Header, HttpStatus, Req, Res } from '@nestjs/common'; import { Response } from 'express'; @Get("mediation-get-api") @Head ...

Having trouble with Node.js GET request functionality not functioning properly

I've been encountering difficulties with loading a page using Node.js. While my Node.js Application code functions properly when attempting to load other resources such as www.google.com, it seems to encounter issues specific to the domain name www.eg ...

How can I insert an HTML/PHP code snippet into a <ul> list using JavaScript?

My upload.php file saves images into an uploads/ folder within my main directory. I am looking to dynamically add a new li tag to my index file each time an image successfully uploads. Here is a snippet from index.php: <ul> <li><im ...

Creating a Like button using react.js

How can I make only the selected button change, instead of all at the same time when clicked? I have implemented a function that includes a Boolean state and toggles it const [like, setLike] = useState(false); const handleLike=()=> { setLike(! ...

What is the best way to choose a specific row with Enzyme?

We have chosen Jest for doing UI Test-Driven Development on our React application. Our component rendering structure looks like this: <Div> <Row> </Row> <ROW> <Row> <ROW> <Link> <Link> ...

The .ogv video file type does not seem to be functioning properly within the HTML5 video tag on Firefox

Hello, I'm encountering some issues with playing the .ogv file in Firefox. If you could take a look at the link , that would be greatly appreciated. I believe my HTML5 video tag syntax is correct as it's working fine on other browsers. Thank you ...

Put an end to the endless game of defining TypeScript between Aurelia CLI and Visual Studio 2017 builds

I am encountering TypeScript errors in my Visual Studio build for an Aurelia project within a .NET Core project. The errors include 'Build:Cannot find name 'RequestInit'', 'Build:Cannot find name 'Request'', and &apo ...

Using JavaScript's Regex to match sentences, while ensuring any full stops within quotes are ignored

Here is the regular expression: (?:(?:Jr|Master|Mr|Ms|Mrs|Dr|Capt|Col|Sgt|Sr|Prof|Rep|Mt|Mount|St|Etc|Eg)\.\s+|["'“(\[]?)(?:\b(?:(?!(?:\S{1,})[.?!]+["']?\s+["']?[A-Z]).)*)(?:(?:(?:Jr|Master|Mr|M ...

An HTML table featuring rows and columns that can be adjusted in size separately from the content within each cell

Looking to create an HTML table where the columns and rows can be sized independently of the cell content? If a row or column isn't large enough to display all the content, it should simply overflow behind the cell. A solution was found that worked in ...

Handling events for components that receive props from various components in a list

In my code, I have a component called PrivateReview which includes event handlers for updating its content. export default function PrivateReview(props) { const classes = useStyles(); const removeReviewAndReload = async () => { await ...

The functionality of displaying and hiding elements in HTML using jQuery is not functioning as expected

When I implemented the .toggle() functionality in jQuery on the content, I encountered a problem where clicking on the "read more" button caused the text link to disappear and the first paragraph to become invisible. Below is the jQuery code snippet: $( ...

The impact is felt across every button in CSS

Why is this happening? When I hover over a button, all buttons apply the effect, which should not be the case. I only want the effect to be applied to the button that I am hovering over. .buttons{ font-family: arial; text-decoration: none; padding ...

Does Jquery AJAX send back raw data or HTML ready for use?

I'm currently developing a mobile app using Jquery Mobile. In order to populate the app with data, I need to make requests to an API and display the information within the app. At this point, I have two possible options: The API returns JSON data ...

The Javascript regex allows for the presence of positive and negative numbers, with the option of a single minus symbol

oninput="this.value = this.value.replace(/[^-0-9.]/g, '') This code snippet is utilized in my current project. However, there seems to be an issue where the input can contain more than one minus sign, as shown here: ---23 To address this p ...

What could be causing the significant gap at the bottom of my Flexbox?

Whenever I resize the page to fit a mobile device, there is always a large gap at the bottom. I want the content to stack normally when it shrinks, without leaving a huge gap at the bottom. There is no gap at the bottom when viewed on desktop, but as soo ...

How to address hover problems in D3.js when dealing with Path elements and updating tooltip information after brushing the focus

Seeking assistance with a Multi Series, Focus + Context D3 chart and hoping to address my main queries all at once. The questions that need resolving are: How can I prevent the tooltips I've generated from being affected by the hair-line (which t ...

Show content based on information from an array using JavaScript

I am currently working on developing a user-friendly step-by-step form using AngularJS and UI-router to navigate through different sections. The data collected from each form is stored in a JavaScript array, and I am trying to dynamically show or hide a di ...