view 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 source

import Vue from "vue";
import Router from "vue-router";
import Login from "./views/Login.vue";
import Main from "./views/Main.vue";
import store from "./store";

Vue.use(Router);

const router = new Router({
  routes: [
    {
      path: "/login",
      name: "login",
      component: Login
    },
    {
      path: "/",
      name: "mainview",
      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();
      }
    },
    {
      path: "*",
      component: Login
    }
  ]
});

router.beforeEach((to, from, next) => {
  const requiresAuth = to.matched.some(record => record.meta.requiresAuth);
  const currentUser = localStorage.getItem("token") != null;
  const userIsAuthenticated = requiresAuth && !currentUser;
  if (userIsAuthenticated) {
    next("/login");
  } else if (!userIsAuthenticated) {
    next();
  } else {
    next();
  }
});

export default router;