11import Vue from 'vue'
22import Router from 'vue-router'
33import Home from './views/Home.vue'
4+ import { AmplifyEventBus } from 'aws-amplify-vue'
5+ import { getUser } from '@/utils/auth.js'
46
57Vue . use ( Router )
68
7- export default new Router ( {
9+ const router = new Router ( {
810 mode : 'history' ,
911 base : process . env . BASE_URL ,
1012 routes : [
1113 {
1214 path : '/' ,
1315 name : 'home' ,
14- component : Home
16+ component : Home ,
17+ meta : { requiresAuth : true } ,
1518 } ,
1619 {
1720 path : '/about' ,
@@ -24,17 +27,69 @@ export default new Router({
2427 {
2528 path : '/signUp' ,
2629 name : 'signUp' ,
27- component : ( ) => import ( /* webpackChunkName: "about" */ './views/SignUp.vue' )
30+ component : ( ) => import ( /* webpackChunkName: "about" */ './views/SignUp.vue' ) ,
31+ meta : { requiresAuth : false } ,
2832 } ,
2933 {
3034 path : '/signUpConfirm' ,
3135 name : 'signUpConfirm' ,
32- component : ( ) => import ( /* webpackChunkName: "about" */ './views/SignUpConfirm.vue' )
36+ component : ( ) => import ( /* webpackChunkName: "about" */ './views/SignUpConfirm.vue' ) ,
37+ meta : { requiresAuth : false } ,
3338 } ,
3439 {
3540 path : '/signIn' ,
3641 name : 'signIn' ,
37- component : ( ) => import ( /* webpackChunkName: "about" */ './views/SignIn.vue' )
42+ component : ( ) => import ( /* webpackChunkName: "about" */ './views/SignIn.vue' ) ,
43+ meta : { requiresAuth : false } ,
3844 } ,
3945 ]
4046} )
47+
48+ getUser ( ) . then ( ( user ) => {
49+ if ( user ) {
50+ router . push ( { path : '/' } )
51+ }
52+ } )
53+
54+ AmplifyEventBus . $on ( 'authState' , async ( state ) => {
55+ const pushPathes = {
56+ signedOut : ( ) => {
57+ router . push ( { path : '/signIn' } )
58+ } ,
59+ signUp : ( ) => {
60+ router . push ( { path : '/signUp' } )
61+ } ,
62+ confirmSignUp : ( ) => {
63+ router . push ( { path : '/signUpConfirm' } )
64+ } ,
65+ signIn : ( ) => {
66+ router . push ( { path : '/signIn' } )
67+ } ,
68+ signedIn : ( ) => {
69+ router . push ( { path : '/' } )
70+ }
71+ }
72+ if ( typeof pushPathes [ state ] === 'function' ) {
73+ pushPathes [ state ] ( )
74+ }
75+ } )
76+
77+ router . beforeResolve ( async ( to , from , next ) => {
78+ const user = await getUser ( )
79+ if ( ! user ) {
80+ if ( to . matched . some ( ( record ) => record . meta . requiresAuth ) ) {
81+ return next ( {
82+ path : '/signIn' ,
83+ } )
84+ }
85+ } else {
86+ if ( to . matched . some ( ( record ) => typeof ( record . meta . requiresAuth ) === "boolean" && ! record . meta . requiresAuth ) ) {
87+ return next ( {
88+ path : '/' ,
89+ } )
90+ }
91+ }
92+ return next ( )
93+ } )
94+
95+ export default router
0 commit comments