N
N
nvdfxx2018-10-31 15:56:07
firebase
nvdfxx, 2018-10-31 15:56:07

How to fix vue-router protection?

In the application, on some routes, there is a beforeEnter with an authentication check that redirects to the login page if the user is not logged in. If the user logs in, everything works fine, but when the page is reloaded, it still redirects to the login page. Whether who faced it?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
S
shmatuan, 2018-10-31
@shmatuan

{
      path: '/login',
      name: 'Login',
      component: Login,
      meta: { requiresAuth: false }
    },    
//---------------
router.beforeEach((to, from, next) => {
  if(!to.matched[0]){
    router.push({ name: 'Login' });
  }else if(to.meta.requiresAuth){		
      S.currentUser ? next() : router.push({ name: 'Login' })
  }
  }else{
    next();
  }
});

2
2perca, 2018-11-01
@2perca

the router looks like this:
beforeEach like this:

router.beforeEach((to, from, next) => {
  if (to.matched.some(record => record.meta.requiresAuth)) {
    if (!store.state.account.access) {
      next({ name: 'Signin' })
    } else {
      next()
    }
  } else {
    next()
  }
})

in store.state.account.access true/false, but string types can also be handled (guest/user/admin/etc.)

A
alex_kulkoff, 2018-11-12
@alex_kulkoff

Just initialize the application itself in main.js after changing auth:

fb.auth().onAuthStateChanged(user => {
  if (!app) {
    app = new Vue({
      el: '#app',
      store,
      router,
      components: { App },
      template: '<App/>',
      created () {
        if (user) {
        }
      }
    })
  }
})

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question