forked from CodeForPoznan/pah-fm
/
index.js
98 lines (85 loc) · 2.31 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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
import Vue from 'vue';
import Router from 'vue-router';
import HomeView from '../views/HomeView.vue';
import LoginView from '../views/LoginView.vue';
import DriveFormView from '../views/DriveFormView.vue';
import DrivesView from '../views/DrivesView.vue';
import SuccessfulLogoutView from '../views/SuccessfulLogoutView.vue';
import { getItem } from '../services/localStore';
import store from '../store';
import * as mutations from '../store/mutations';
import { tokenKey, deleteToken } from '../services/api/auth';
Vue.use(Router);
export const loginRoute = {
path: '/login',
name: 'Login',
component: LoginView,
};
export const driveCreateRoute = {
path: '/drive',
name: 'Drive',
component: DriveFormView,
};
export const driveListRoute = {
path: '/drives',
name: 'Drives',
component: DrivesView,
};
export const homeRoute = {
path: '/',
name: 'Home',
component: HomeView,
};
export const logoutRoute = {
path: '/logout',
name: 'Logout',
};
export const successfulLogoutRoute = {
path: '/logout_success',
name: 'SuccesfulLogout',
component: SuccessfulLogoutView,
};
export const pageNotFoundRoute = {
path: '*',
name: 'PageNotFound',
component: HomeView,
props: { pageNotFound: true },
};
const router = new Router({
mode: 'history',
routes: [
loginRoute,
driveCreateRoute,
driveListRoute,
homeRoute,
pageNotFoundRoute,
logoutRoute,
successfulLogoutRoute,
],
});
const openRoutes = [loginRoute.name, successfulLogoutRoute.name];
router.beforeEach((to, _from, next) => {
const userLoggedIn = getItem(tokenKey);
// 404 if not route matches
if (to.name === pageNotFoundRoute.name) {
return next({ path: homeRoute.path });
}
if (to.name === logoutRoute.name) {
store.commit(mutations.SET_USER, null);
deleteToken();
return next(successfulLogoutRoute.path);
}
if (openRoutes.includes(to.name)) {
return next();
}
// Redirect to login if user tries to access closed route without token
if (!userLoggedIn && !openRoutes.includes(to.name)) {
return next({ path: loginRoute.path });
}
// Redirect home if logged-in user tries to access login route
if (userLoggedIn && (to.name === loginRoute.name || to.name === successfulLogoutRoute.name)) {
return next({ path: homeRoute.path });
}
return next();
});
export default router;