Vue Router: prevent user from accessing the login route if it is already logged in

8

I'm configuring the routes of my application in Vue.js , initially everything is OK, after logging in the user is redirected to dashboard , now my question is how can I prevent the user from accessing the " /logi n" (again) route after he has already logged in and redirected him back to the previous route? (which it was before typing in the address bar " /login ")

By reading the Vue documentation, I know I can use navigation guards , and using the global router.beforeEach , which has three parameters: to , from and next , I know I can manipulate this behavior using from to return the user to the previous route if he accessed the " /login " while logged in. but I still could not get it redirected.

Here's my code example: router / beforeEach.js

import { checkUserToken } from 'src/utils/storageData'

const isAuthRoute = route => route.path.indexOf('/login') !== -1

const isLogged = () => !checkUserToken()

const needAuth = auth => auth === true

const beforeEach = (to, from, next) => {
  const auth = to.meta.requiresAuth

  // verifica se a rota requer autenticação
  if (needAuth(auth)) {
    // verifica se o usuário já está autenticado
    if (!isAuthRoute(to) && !isLogged()) {
      next('/login')
    } else {
      if (isLogged() && to.path === '/login') {
        from()
      }
      next()
    }
  } else {
    next()
  }
}

export default beforeEach

router / index.js:

import Vue from 'vue'

import VueRouter from 'vue-router'

import {routes} from './routes'

import beforeEach from './beforeEach'

Vue.use(VueRouter)

const router = Vue.router = new VueRouter({
  linkActiveClass: 'active',
  saveScrollPosition: true,
  mode: 'history',
  base: __dirname,
  routes
})

// pega as configurações do import acima
router.beforeEach(beforeEach)

export default router
    
asked by anonymous 17.02.2017 / 20:12

2 answers

1

In the '/ login' route you can set the beforeCreate by calling a goback () method, see link

beforeCreate () {
    if (isLogged()) {
      this.goBack()
    }
},
methods: {
    goBack () {
      window.history.length > 1
        ? this.$router.go(-1)
        : this.$router.push('/')
    }
  }
    
14.09.2018 / 03:07
0

Well, one solution I used is the following, I did a check to see if the user is logged in and if the route is "/ login", then I gave a next ('/') to home page. and this if outside the first if.

if (isLogged() && to.path === '/login') {
    next('/')
 }
    
20.02.2017 / 14:10