@@ -4,19 +4,22 @@ import router from '@/router';
44/**
55 * Sync loopback token with current state
66*/
7- export function syncToken ( { commit} ) {
7+ export function syncToken ( { commit, dispatch } ) {
88 if ( loopback . token ) {
99 commit ( 'setAccessToken' , loopback . token ) ;
10+ return dispatch (
11+ 'loadAccount' ,
12+ loopback . token . userId ,
13+ ) . catch ( ( err ) => {
14+ commit ( 'setAccessToken' , null ) ;
15+ return err ;
16+ } ) ;
1017 }
18+ return Promise . resolve ( ) ;
1119}
1220
13- /**
14- * Sync router for auth
15- */
16- export function syncRouter ( { state, dispatch} , myRouter ) {
17- dispatch ( 'syncToken' ) ;
18-
19- myRouter . beforeEach ( ( to , from , next ) => {
21+ function evaluateRoute ( state , to , from , next ) {
22+ return ( sessionError ) => {
2023 if ( to . matched . some ( record => record . meta . requiresAuth ) ) {
2124 // this route requires auth, check if logged in
2225 // if not, redirect to login page (except when it's profile route and
@@ -26,14 +29,27 @@ export function syncRouter({state, dispatch}, myRouter) {
2629 } else if ( ! state . access_token ) {
2730 next ( {
2831 name : 'login' ,
32+ params : {
33+ sessionError,
34+ } ,
2935 } ) ;
3036 } else {
31- dispatch ( 'loadAccount' , state . access_token . userId )
32- . then ( next ) ;
37+ next ( ) ;
3338 }
3439 } else {
3540 next ( ) ; // make sure to always call next()!
3641 }
42+ } ;
43+ }
44+
45+ /**
46+ * Sync router for auth
47+ */
48+ export function syncRouter ( { state, dispatch} , myRouter ) {
49+ myRouter . beforeEach ( ( to , from , next ) => {
50+ dispatch ( 'syncToken' ) . then (
51+ evaluateRoute ( state , to , from , next )
52+ ) ;
3753 } ) ;
3854}
3955
@@ -60,7 +76,6 @@ export function signIn({commit, dispatch, state}, {email, password}) {
6076 loopback . removeToken ( ) ;
6177 }
6278
63- router . push ( { name : 'dashboard' } ) ;
6479 return dispatch ( 'loadAccount' , state . access_token . userId ) ;
6580 } ) ;
6681}
@@ -94,9 +109,9 @@ export function loadAccount({commit}, userId) {
94109 return loopback
95110 . get ( `/Accounts/${ userId } ` )
96111 . then ( acc => commit ( 'setAccount' , acc ) )
97- . catch ( ( ) => {
112+ . catch ( ( err ) => {
98113 loopback . removeToken ( ) ;
99- router . push ( { name : 'login' } ) ;
114+ return Promise . reject ( err ) ;
100115 } ) ;
101116}
102117
0 commit comments