@@ -18,37 +18,39 @@ router.beforeEach((to, from, next) => {
1818 NProgress . start ( )
1919
2020 // Jump to target path directly If target path has been included by white list
21+ // or common routes
22+ // if (WHITELIST.includes(to.path) || !to.meta.roles) {
2123 if ( WHITELIST . includes ( to . path ) ) {
22- next ( )
23- return
24+ return next ( )
2425 }
2526
26- // fetching user private routes
27- if ( getTokenFromLocal ( ) ) { // User has been logged in
28- if (
29- ! store . state . login . dynamicRoutes . length ||
30- ! store . state . login . dynamicRoutes [ 0 ] . component
31- ) {
32- store . dispatch ( 'login/fetchDynamicRoutes' )
33- . then ( routes => store . dispatch ( 'login/createGlobalRoutes' , routes ) )
34- . catch ( e => {
35- MessageBox ( {
36- title : 'Error' ,
37- message : 'We got a error when fetching user access.' ,
38- type : 'error' ,
39- showClose : false
40- } )
41- . then ( ( ) => store . dispatch ( 'login/userLogout' ) )
42- . then ( ( ) => next ( {
43- path : `/login?redirect=${ to . path } ` ,
44- replace : true
45- } ) )
46- NProgress . done ( )
47- console . error ( e )
48- } )
27+ // ! State: User has been logged in.
28+ if ( getTokenFromLocal ( ) ) {
29+ // 1. fetch rolesMap if necessary (when rolesMap stored by back-end)
30+
31+ // 2. confirm route access by user role
32+ if ( ! store . getters [ 'login/role' ] ) {
33+ // 2.1 No roles: fetch user role
34+ return store . dispatch (
35+ 'login/fetchUserAccess' ,
36+ store . getters [ 'login/username' ]
37+ )
38+ . catch ( e => errorHandler ( e , next , to . path ) )
39+ . finally ( ( ) => next ( ) )
40+ }
41+
42+ // 2.2 filter route
43+ if ( ! to . meta . roles ||
44+ to . meta . roles . includes ( store . getters [ 'login/role' ] [ 0 ] ) ) {
45+ next ( )
46+ } else {
47+ next ( {
48+ path : `/403?redirect=${ to . path } ` ,
49+ replace : true
50+ } )
4951 }
50- next ( )
5152 } else {
53+ // ! State: user logout
5254 next ( {
5355 path : `/login?redirect=${ to . path } ` ,
5456 replace : true
@@ -61,3 +63,19 @@ router.afterEach((to, from) => {
6163} )
6264
6365export default router
66+
67+ function errorHandler ( e , next , redirectPath ) {
68+ MessageBox ( {
69+ title : 'Error' ,
70+ message : 'We got a error when fetching user access.' ,
71+ type : 'error' ,
72+ showClose : false
73+ } )
74+ . then ( ( ) => store . dispatch ( 'login/userLogout' ) )
75+ . then ( ( ) => next ( {
76+ path : `/login?redirect=${ redirectPath } ` ,
77+ replace : true
78+ } ) )
79+ NProgress . done ( )
80+ console . error ( e )
81+ }
0 commit comments