-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
75 lines (62 loc) · 1.93 KB
/
index.js
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
72
73
74
75
import Vue from 'vue';
const defaults = {
routes: {
guest: '/public',
auth: '/account',
},
};
function getRouteByMetaKey(route, key) {
const matched = [route, ...route.matched];
return matched.find((r) => r.meta.auth && typeof r.meta.auth[key] !== 'undefined');
}
function getMetaValue(route, key) {
const metaRoute = getRouteByMetaKey(route, key);
return metaRoute ? metaRoute.meta.auth[key] : null;
}
function verify(route, context, defaultGuard) {
const routeGuard = getMetaValue(route, 'guard');
return routeGuard ? routeGuard(context) : defaultGuard(context);
}
function getRouteTo(route, context) {
const redirect = getMetaValue(route, 'redirect');
return typeof redirect === 'function' ? redirect(context) : redirect;
}
export function middleware({
router,
guard = () => false,
routes = {},
context,
}) {
return (to, from, next) => {
const ctx = { to, from, ...Vue.prototype, ...context };
const closureRoute = getRouteByMetaKey(to, 'access');
const access = getMetaValue(to, 'access');
const redirectRoutes = { ...defaults.routes, ...routes };
const routeToCache = getRouteTo(to, ctx);
const verifyCache = verify(to, ctx, guard);
const actions = [
{
condition: closureRoute && typeof access === 'string' && access !== verifyCache,
callback: () => router.replace(routeToCache || redirectRoutes[access]),
},
{
condition: closureRoute && access && !verifyCache,
callback: () => router.replace(routeToCache || redirectRoutes.guest),
},
{
condition: closureRoute && !access && verifyCache,
callback: () => router.replace(routeToCache || redirectRoutes.auth),
},
{
condition: true,
callback: () => next(),
},
];
actions.find((action) => action.condition).callback();
};
}
export default {
install(_Vue, options) {
options.router.beforeEach(middleware(options));
},
};