comparison client/src/router.js @ 160:061209505028

feat: Login and logout with session restoration implemented Login information stored in local storage for restoration after browser restart. If a non expired session is found, it is restored before entering the main area. Username and logout are located in the lower sidebar.
author Thomas Junk <thomas.junk@intevation.de>
date Wed, 04 Jul 2018 17:21:10 +0200
parents 7ba0a77fd679
children 9908260d1e6a
comparison
equal deleted inserted replaced
159:3d9341f6da4e 160:061209505028
17 path: "/", 17 path: "/",
18 name: "mainview", 18 name: "mainview",
19 component: Main, 19 component: Main,
20 meta: { 20 meta: {
21 requiresAuth: true 21 requiresAuth: true
22 },
23 beforeEnter: (to, from, next) => {
24 const expiresFromPastSession = localStorage.getItem("expires");
25 const pastSessionStillActive = () => {
26 if (!expiresFromPastSession) return false;
27 const now = new Date();
28 const sessionEnd = new Date(expiresFromPastSession * 1000);
29 const stillActive = now < sessionEnd;
30 return stillActive;
31 };
32 if (pastSessionStillActive()) {
33 store.commit("user/set_user", localStorage.getItem("user"));
34 store.commit("user/set_expires", expiresFromPastSession);
35 store.commit("user/set_roles", localStorage.getItem("roles"));
36 store.commit("user/authenticate", true);
37 }
38 next();
22 } 39 }
23 }, 40 },
24 { 41 {
25 path: "*", 42 path: "*",
26 component: Login 43 component: Login
28 ] 45 ]
29 }); 46 });
30 47
31 router.beforeEach((to, from, next) => { 48 router.beforeEach((to, from, next) => {
32 const requiresAuth = to.matched.some(record => record.meta.requiresAuth); 49 const requiresAuth = to.matched.some(record => record.meta.requiresAuth);
33 const currentUser = store.getters["user/authenticated"]; 50 const currentUser = localStorage.getItem("token") != null;
34 if (requiresAuth && !currentUser) { 51 const userIsAuthenticated = requiresAuth && !currentUser;
52 if (userIsAuthenticated) {
35 next("/login"); 53 next("/login");
36 } else if (requiresAuth && currentUser) { 54 } else if (!userIsAuthenticated) {
37 next(); 55 next();
38 } else { 56 } else {
39 next(); 57 next();
40 } 58 }
41 }); 59 });