Block access to Vue js routes if you are not logged in

Asked

Viewed 261 times

-1

I am unable to block routes are going through normal without authentication

I am developing a Dashboard and came to doubt how to prohibit access to routes if not logged in, with this, I thought of some solutions that would use localStorage, but, none is a right solution.

What would be the right way to do that? I saw that many people have this doubt, and I couldn’t find a solution to it.

  export default [

  {
    path: '/',
    // Relative to /src/views
    name: 'home',
    view: 'Dashboard',

  },
  {
    path: '/cliente-index',
    name: 'Clientes',
    view: 'Clientes',



  },
  {
    path: '/sistema-index',
    name: 'Sistemas',
    view: 'Sistemas',
    meta: { 
      requiresAuth: true
  }

  },
  {
    path: '/sistema-pastas/:id:descricao:path_padrao',
    name: 'sistema-pastas',
    view: 'Pastas',
     meta: { 
      requiresAuth: true
  }
  },
  {
    path: '/versao-index',
    name: 'Versões',
    view: 'Versao',
    meta: { 
      requiresAuth: true
  }
  },
  {
    path: '/usuario-index',
    name: 'Usuarios',
    view: 'Usuarios',
  },
  {
    path: '/login',
    name: '',
    view: 'Login',
    meta: { 
      guest: true
  }

  },
  {
    path: '/cliente-sistema/:id',
    name: 'Cliente Sistema',
    view: 'ClienteSistema',
  },  

]


router.beforeEach((to, from, next) => {
    if(to.matched.some(record => record.meta.requiresAuth)) {
        if (localStorage.getItem('jwt') == null) {
            next({
                path: '/login',
                params: { nextUrl: to.fullPath }
            })
        } else {
            let user = JSON.parse(localStorage.getItem('user'))
            if(to.matched.some(record => record.meta.is_admin)) {
                if(user.is_admin == 1){
                    next()
                }
                else{
                    next({ name: 'userboard'})
                }
            }else {
                next()
            }
        }
    } else if(to.matched.some(record => record.meta.guest)) {
        if(localStorage.getItem('jwt') == null){
            next()
        }
        else{
            next({ name: 'userboard'})
        }
    }else {
        next() 
    }
})
  • Is the problem in the above code? With the exception of saving Adm on localStorage, which I don’t recommend, the route blocking you made sense of. What I add is blockade via Interceptor with Axios and middleware in the back end. If you want I can answer with a route lock, with Interceptor and middleware example in the default back end (Node or php).

1 answer

0

You first need in your state to have a property to be set when the user enters the system after this you need to add sessionStorage in the store

inserir a descrição da imagem aqui

  • This would be very easy to hack, just edit the Storage using the developer tools

Browser other questions tagged

You are not signed in. Login or sign up in order to post.