Mercurial > gemma
diff 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 |
line wrap: on
line diff
--- a/client/src/router.js Tue Jul 03 17:46:06 2018 +0200 +++ b/client/src/router.js Wed Jul 04 17:21:10 2018 +0200 @@ -19,6 +19,23 @@ component: Main, meta: { requiresAuth: true + }, + beforeEnter: (to, from, next) => { + const expiresFromPastSession = localStorage.getItem("expires"); + const pastSessionStillActive = () => { + if (!expiresFromPastSession) return false; + const now = new Date(); + const sessionEnd = new Date(expiresFromPastSession * 1000); + const stillActive = now < sessionEnd; + return stillActive; + }; + if (pastSessionStillActive()) { + store.commit("user/set_user", localStorage.getItem("user")); + store.commit("user/set_expires", expiresFromPastSession); + store.commit("user/set_roles", localStorage.getItem("roles")); + store.commit("user/authenticate", true); + } + next(); } }, { @@ -30,10 +47,11 @@ router.beforeEach((to, from, next) => { const requiresAuth = to.matched.some(record => record.meta.requiresAuth); - const currentUser = store.getters["user/authenticated"]; - if (requiresAuth && !currentUser) { + const currentUser = localStorage.getItem("token") != null; + const userIsAuthenticated = requiresAuth && !currentUser; + if (userIsAuthenticated) { next("/login"); - } else if (requiresAuth && currentUser) { + } else if (!userIsAuthenticated) { next(); } else { next();