Skip to content
This repository was archived by the owner on Apr 9, 2022. It is now read-only.

Commit 57b0051

Browse files
committed
initialize from storage
1 parent 622e1ca commit 57b0051

File tree

2 files changed

+35
-20
lines changed

2 files changed

+35
-20
lines changed

client/src/router/index.js

Lines changed: 25 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -12,20 +12,26 @@ import VerifyEmail from '../views/VerifyEmail';
1212

1313
import store from '../store';
1414

15-
const redirectUnauthorizedToLogin = (to, from, next) => {
16-
if (!store.getters['auth/isAuthenticated']) {
17-
next('/login');
18-
} else {
19-
next();
20-
}
15+
const requireAuthenticated = (to, from, next) => {
16+
store.dispatch('auth/initialize')
17+
.then(() => {
18+
if (!store.getters['auth/isAuthenticated']) {
19+
next('/login');
20+
} else {
21+
next();
22+
}
23+
});
2124
};
2225

23-
const redirectAuthorizedToHome = (to, from, next) => {
24-
if (store.getters['auth/isAuthenticated']) {
25-
next('/home');
26-
} else {
27-
next();
28-
}
26+
const requireUnauthenticated = (to, from, next) => {
27+
store.dispatch('auth/initialize')
28+
.then(() => {
29+
if (store.getters['auth/isAuthenticated']) {
30+
next('/home');
31+
} else {
32+
next();
33+
}
34+
});
2935
};
3036

3137
const redirectLogout = (to, from, next) => {
@@ -38,19 +44,19 @@ Vue.use(Router);
3844
export default new Router({
3945
saveScrollPosition: true,
4046
routes: [
41-
{
42-
path: '/about',
43-
component: About,
44-
beforeEnter: redirectUnauthorizedToLogin,
45-
},
4647
{
4748
path: '/',
4849
redirect: '/home',
4950
},
51+
{
52+
path: '/about',
53+
component: About,
54+
beforeEnter: requireAuthenticated,
55+
},
5056
{
5157
path: '/home',
5258
component: Home,
53-
beforeEnter: redirectUnauthorizedToLogin,
59+
beforeEnter: requireAuthenticated,
5460
},
5561
{
5662
path: '/password_reset',
@@ -71,7 +77,7 @@ export default new Router({
7177
{
7278
path: '/login',
7379
component: Login,
74-
beforeEnter: redirectAuthorizedToHome,
80+
beforeEnter: requireUnauthenticated,
7581
},
7682
{
7783
path: '/logout',

client/src/store/auth.js

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@ const TOKEN_STORAGE_KEY = 'TOKEN_STORAGE_KEY';
1414
const initialState = {
1515
authenticating: false,
1616
error: false,
17-
token: localStorage.getItem(TOKEN_STORAGE_KEY),
17+
token: null,
1818
};
1919

2020
const getters = {
@@ -34,6 +34,15 @@ const actions = {
3434
.then(() => commit(LOGOUT))
3535
.finally(() => commit(REMOVE_TOKEN));
3636
},
37+
initialize({ commit }) {
38+
const token = localStorage.getItem(TOKEN_STORAGE_KEY);
39+
40+
if (token) {
41+
commit(SET_TOKEN, token);
42+
} else {
43+
commit(REMOVE_TOKEN);
44+
}
45+
},
3746
};
3847

3948
const mutations = {

0 commit comments

Comments
 (0)