1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
|
import { watch } from 'vue';
import { useSession } from '@vnuge/vnlib.browser';
import { useSessionStorage, get, set } from '@vueuse/core';
import { includes, map, toLower } from 'lodash-es';
import { type Router } from 'vue-router';
import { createRouter, createWebHistory } from 'vue-router/auto'
import { routes } from 'vue-router/auto-routes'
export default createRouter({
history: createWebHistory(import.meta.env.BASE_URL),
routes
})
/**
* Enables page guards for protected routes and configures a
* last page store.
*/
export const guardRoutes = (router: Router, protectedRoutes: string[]) => {
const { loggedIn } = useSession()
const lastPageStore = useSessionStorage('lastPageStore', undefined)
const { beforeEach, currentRoute, afterEach, push } = router
//Convert routes to lowercase
protectedRoutes = map(protectedRoutes, toLower);
//Setup nav guards
beforeEach((to, from) => {
if (!to.name) {
return true;
}
if (!get(loggedIn)) {
if (includes(protectedRoutes, toLower(to.name as string))) {
//Set last page as from page
set(lastPageStore, from.fullPath)
return { name: 'Login' }
}
}
else {
/**
* If the user is going back to the login page, are logged in,
* and have a previous page to go back to, redirect to the last page
* instead of the login page
*/
const lastPath = get(lastPageStore);
if (to.name === 'Login' && lastPath) {
set(lastPageStore, undefined) //Clear the last page
return lastPath ? { path: lastPath } : true;
}
}
//Allow
return true;
})
//scroll window back to top
afterEach(() => window.scrollTo(0, 0))
watch(loggedIn, (li) => {
//If the user gets logged out, redirect to login
if (li === false && currentRoute.value.name !== 'Login') {
push({ name: 'Login' })
}
})
}
|