import Vue from 'vue'
import router from '@/router'
import store from '@/store'
import {
getFirstGrantedRouteFromVueRoutes,
isVueRouteGranted,
} from '@/services/rights-service.js'
/**
* Router helpers
* @namespace Plugins
* @category Plugins
* @module router-plugin
* @name $routerPlugin
*/
Vue.use({
install() {
Vue.$routerPlugin =
Vue.prototype.$routerPlugin =
window._rp =
{
/**
* @function routeToDefaultRoute
* @description Default route is take from an env variable. If not found, will try to route to the first route available (with enough rigths)
*/
routeToDefaultRoute() {
let defaultRouteName = Vue.$env.getEnvValue(
'VUE_APP_ROUTER_DEFAULT_ROUTE'
)
? Vue.$env.getEnvValue('VUE_APP_ROUTER_DEFAULT_ROUTE')
: 'app_quickmenu_screen'
let defaultRouteItem = router.options.routes.find(
(r) => r.name == defaultRouteName
)
console.log('routeToDefaultRoute', {
defaultRouteName,
defaultRouteItem,
})
//If default route is unavailable (invalid/no-access), fallback to first granted route
try {
if (
!defaultRouteItem ||
(!!defaultRouteItem && !isVueRouteGranted(defaultRouteItem))
) {
defaultRouteName = getFirstGrantedRouteFromVueRoutes(
router.options.routes
).name
}
} catch (err) {
console.warn(err.stack || err)
defaultRouteItem = 'login_screen' //Case: use doesn't have rights to any available route/module?
}
console.info(
'router-plugin: Redirecting to default route',
defaultRouteName
)
router.push({
name: defaultRouteName,
})
},
/**
* It will try to route to the first route available (with enough rigths)
*/
routeToFirstGrantedModule() {
let name = getFirstGrantedRouteFromVueRoutes(
router.options.routes
).name
console.log('routeToFirstGrantedModule', {
name,
})
router.push({
name: name,
})
},
/**
* * @todo Reset layout if dynamic?
*/
async logoutFromApplication() {
Vue.$log.debug('logoutFromApplication')
this.hidePersistentFeatures()
await store.dispatch('auth/logout')
router.push({
name: 'login_screen',
})
},
routeToLoginAs() {
this.hidePersistentFeatures()
router.push({
name: 'login_as',
})
},
/**
* Will hide Dashboard/Settings view
*/
hidePersistentFeatures() {
store.dispatch('app/setCurrentFloatingModule', '')
},
async loginAsUsingToken(token, clientId, fullRefresh = false) {
if (fullRefresh) {
window.location.href = `${window.location.origin}/#/login?_token=${token}`
window.location.reload()
return
}
this.willBeDestroyed = true
let isLoginAsSuccess = await store.dispatch('auth/loginAs', {
token,
clientId,
})
if (isLoginAsSuccess) {
this.routeToDefaultRoute()
} else {
this.logoutFromApplication()
}
},
}
},
})
Source