markWanka
markWanka

Reputation: 794

How to block a user from going to a given url?

In my vue app project, i create function which hides a menu item for specific users with too few permissions like below:

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

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

So, Ok, this hide my element on UI and current logged in user cannot go to page with url e.q. https://somelink.com/account/settings via clicking on anchor in UI, but when he write this url then he can be redirected to this page, and here i have a problem, how to block user going to this url via writing it in a browser?

thanks for any help!

Upvotes: 0

Views: 1177

Answers (2)

Filip Huhta
Filip Huhta

Reputation: 2388

You could use Navigation guards to apply that logic for the specific page Navigation Guards

Set up routes like this in your routes file:

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

Example from page to redirect user to /login page if not authenticated:

// BAD
    router.beforeEach((to, from, next) => {
      if (to.name !== 'Login' && !isAuthenticated) next({ name: 'Login' })
      // if the user is not authenticated, `next` is called twice
      next()
    })
// GOOD
router.beforeEach((to, from, next) => {
  if (to.name !== 'Login' && !isAuthenticated) next({ name: 'Login' })
  else next()
})

Upvotes: 1

Karen Etulain
Karen Etulain

Reputation: 141

You will need to use Vue Router and configure the validation on the beforeEach loop as indicated on the doc [Navigation Guards]: https://router.vuejs.org/guide/advanced/navigation-guards.html#global-before-guards

You will have something like this:

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

Upvotes: 2

Related Questions