V
V
Viktor2020-01-29 16:20:45
Vue.js
Viktor, 2020-01-29 16:20:45

How to properly set up routing protection in Vue?

There is such a route

{
      path: '/orders',
      name: 'Orders',
      component: Orders,
      beforeEnter: (from, to, next) => {
        if(store.getters.user) {
          next()
        } else {
          next('/login')    
        } 
      }

The logic is this if the user is registered, then he lets on the page, if not, then sends for registration.
Registration information is received in App.vue via firebase:
mounted() { //проверка при перезагрузке на зареген ли пользователь или нет
    firebase.auth().onAuthStateChanged(user => { //проверка при первой загрузке и перезагрузке на то зареген ли пользователь
      if (user) {
        this.$store.dispatch('autoLoginUser', user)
      }
    });

    this.$store.dispatch('fetchAds');
  }

The question is, I signed up and went to the /orders page. Being on this page, I rebooted and throws me to the login page although I am registered. It turns out that beforeEnter fulfills even before the registration data arrived in the store. How can this be corrected?
I looked at the documentation, it says that you need to do this:
router.beforeEach((to, from, next) => {
  if (!isAuthenticated) next('/login')
  else next()
})

However, when I did this, my application got stuck. What did you do wrong?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
E
eugenedrvnk, 2020-01-29
@eugenedrvnk

https://webdevblog.ru/use-middleware-vo-vue/

R
Roman Sertsov, 2020-01-30
@Arge-dev

Below is an example of a route guard with firebase:

router.beforeEach((to, from, next)=>{
  const currentUser = firebase.auth().currentUser;
  const requireAuth = to.matched.some(record => record.meta.auth);
  if(requireAuth && !currentUser){
    next({name:'signIn'})
  }else{
    next();
  }
});

requireAuth is a meta property on each route that indicates whether authorization is required to gain access to the route.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question