Implementation of login and exit module

1. When a user logs in, the background will return a unique identifier token or JSSessionID to the front end (this paper takes session as an example, and the token is roughly the same). The front end will store the identifier in cookies and redirect the route to the home page.

2. User access: When a user accesses any page, the user obtains the user login id from the global hook function. If the user exists, the route will continue to jump; if not, the route will be directed to the login page.

3. Login is invalid. The background will generally set the user login is invalid. If the user does not perform any operation within a period of time, the session will expire.

4. When the user logs out, clear the cookies and redirect the route to the login page to avoid route bugs and refresh the page.

import router from './router'
import store from './store'
import { Message } from 'element-ui'
import { getToken } from '@/utils/auth'
const whiteList = ['/login'.'/download'] // Not redirects the whitelist router. BeforeEach ((to, from, next) => {if (getToken()) {
    if (to.path === '/login') {
      next({ path: '/'})}else {
      if (store.getters.menu.length === 0) {
        store.dispatch('GetUserInfo'). Then (res = > {/ / pull user information next ()}). The catch (() = > {Message. Error ('Authentication failed, please log in again')
          store.dispatch('LogOut').then(() => {
            next({ path: '/login' })
            location.reload()
          })
        })
      } else {
        next()
      }
    }
  } else {
    if(whiteList.indexOf(to.path) ! == -1) { next() }else {
      next('/login')
      NProgress.done()
    }
  }
})
router.afterEach(() => {})
Copy the code