Redirect to Login page when logging off

pull/9/head
johnniang 2019-04-29 21:31:10 +08:00
parent 26037bef9b
commit 79ed569307
4 changed files with 58 additions and 0 deletions

View File

@ -221,6 +221,7 @@ export const constantRouterMap = [
},
{
path: '/login',
name: 'Login',
meta: { title: '登录' },
component: () => import('@/views/user/Login')
},

View File

@ -17,6 +17,13 @@ router.beforeEach((to, from, next) => {
if (to.meta.title) {
document.title = to.meta.title + ' | Halo Dashboard'
}
if (to.name !== 'Login' && !store.getters.token) {
Vue.$log.debug('Redirectint to Login page')
next({ name: 'Login' })
return
}
next()
})

View File

@ -26,6 +26,10 @@ const user = {
},
SET_INFO: (state, info) => {
state.info = info
},
CLEAR_TOKEN: state => {
Vue.ls.remove(ACCESS_TOKEN)
state.token = null
}
},
actions: {
@ -44,6 +48,41 @@ const user = {
reject(error)
})
})
},
logout({ commit }) {
return new Promise(resolve => {
commit('CLEAR_TOKEN')
adminApi
.logout()
.then(response => {
resolve()
})
.catch(() => {
resolve()
})
})
},
refreshToken({ commit }, refreshToken) {
return new Promise((resolve, reject) => {
adminApi
.refreshToken(refreshToken)
.then(response => {
const token = response.data.data
Vue.$log.debug('Got token', token)
commit('SET_TOKEN', token)
resolve(response)
})
.catch(error => {
const data = error.response.data
Vue.$log.debug('Refresh error data', data)
if (data && data.status === 400 && data.data === refreshToken) {
// The refresh token expired
commit('CLEAR_TOKEN')
}
reject(error)
})
})
}
}
}

View File

@ -4,6 +4,7 @@ import 'nprogress/nprogress.css'
import Vue from 'vue'
import { message } from 'ant-design-vue'
import store from '@/store'
import router from '@/router'
const service = axios.create({
baseURL: process.env.NODE_ENV === 'production' ? '' : 'http://localhost:8090',
@ -55,6 +56,16 @@ service.interceptors.response.use(
// TODO handle 400 status error
} else if (data.status === 401) {
// TODO handle 401 status error
if (store.getters.token && store.getters.token.access_token === data.data) {
// Token expired
// TODO Refresh token
store.dispatch('refreshToken', store.getters.token.refresh_token).then(response => {
Vue.$log.debug('Refresh token successfully')
})
} else {
// Login
router.push({ name: 'Login' })
}
} else if (data.status === 403) {
// TODO handle 403 status error
} else if (data.status === 404) {