Problem protecting when defining a requiresAuth in VueRouter firebase

0

I'm doing a little practice with Vue and Firebase , I have already managed to create users and configure Firebase but I have a problem when restricting routes with VueRouter , with what I have read it should be enough with the property requiresAuth to restrict it if there is no logged in user, but it does not work in this way:

{
  path: '/home',
  name: 'Home',
  component: Home,
  meta: { requiresAuth: true }
}

But the route is still accessible even though no user has logged in. Do you need any extra configuration?

My route file is this:

Vue.use(Router)

export default new Router({
routes: [
{
  path: '*',
  redirect: '/'
},
{
  path: '/',
  name: 'Index',
  component: Index
},
{
  path: '/register',
  name: 'Register',
  component: Register
},
{
  path: '/home',
  name: 'Home',
  component: Home,
  meta: { requiresAuth: true }
}
]
})

Router.beforeEach((to, from, next) => {
let usuarioActivo = firebase.auth().currentUser;
let requiresAuth = to.matched.some(record => record.meta.requiresAuth);

if (requiresAuth && !usuarioActivo) next('index')
else if (!requiresAuth && usuarioActivo) next('home')
else next()
})

By adding the beforeEach and asking if the route requires authorization, I'm getting this error:

    
asked by DVertel 20.01.2018 в 05:15
source

2 answers

0

You receive the error because you are calling the beforeEach method on the Router component, when you should do it on instance returned by new Router() .

Solution:

  • You must create a router instance. For example, let router = new Router(...)

  • About variable router is that you should call the method beforeEach

Example:

Vue.use(Router)

let router = new Router({
  routes: [{
    path: '*',
    redirect: '/'
  }, {
    path: '/',
    name: 'Index',
    component: Index
  }, {
    path: '/register',
    name: 'Register',
    component: Register
  }, {
    path: '/home',
    name: 'Home',
    component: Home,
    meta: {
      requiresAuth: true
    }
  }]
})

router.beforeEach((to, from, next) => {
  let usuarioActivo = firebase.auth().currentUser;
  let requiresAuth = to.matched.some(record => record.meta.requiresAuth);

  if (requiresAuth && !usuarioActivo) next('index')
  else if (!requiresAuth && usuarioActivo) next('home')
  else next()
})

export default router
    
answered by 20.01.2018 в 17:33
0

The error is quite clear. There is no function beforeEach in Router . You must access the method from the object created with new Router()

You can do:

const router = new Router(...)
router.beforeEach(...)
export default router

Nothing prevents you from doing this:

const router = new Router(...)
export default router
router.beforeEach(...)

Or you can also do (The best option in my opinion):

export default router = new Router(...)
router.beforeEach(...)

Referencia de interés

    
answered by 20.01.2018 в 17:34