Skip to content

Commit

Permalink
feat(router): guard for detecting login state
Browse files Browse the repository at this point in the history
  • Loading branch information
lbwa committed Mar 7, 2020
1 parent 3b73127 commit 8bfacf7
Show file tree
Hide file tree
Showing 3 changed files with 22 additions and 3 deletions.
14 changes: 14 additions & 0 deletions src/router/guards.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import { NavigationGuard } from 'vue-router'
import store from '@/store'

const WHITE_LIST = ['Login']

export const onLogin: NavigationGuard = function(to, from, next) {
if (store.getters['user/hasLogin'] || WHITE_LIST.includes(to.name || '')) {
return next()
}
return next({
name: 'Login',
replace: true
})
}
9 changes: 6 additions & 3 deletions src/router/index.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import Vue from 'vue'
import VueRouter from 'vue-router'
import { onLogin } from './guards'

Vue.use(VueRouter)

Expand All @@ -12,13 +13,13 @@ export const routes = [
},
{
path: '/#',
name: '/#',
name: 'Login',
component: () =>
import(/* webpackChunkName: 'login' */ '../views/#/index.vue')
},
{
path: '/forbidden',
name: 'ErrorForbidden',
name: 'ForbiddenError',
component: () =>
import(
/* webpackChunkName: 'error-forbidden' */ '../views/Error/index.vue'
Expand All @@ -30,7 +31,7 @@ export const routes = [
},
{
path: '*',
name: 'ErrorNotFound',
name: 'NotFoundError',
component: () =>
import(
/* webpackChunkName: 'error-not-found' */ '../views/Error/index.vue'
Expand All @@ -47,4 +48,6 @@ const router = new VueRouter({
routes
})

router.beforeEach(onLogin)

export default router
2 changes: 2 additions & 0 deletions src/shared/utils.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
export const errorLog = console.error

export function isDef<T>(val: T): val is NonNullable<T> {
return val !== null && val !== undefined
}

0 comments on commit 8bfacf7

Please # to comment.