refactor router to resume live games
[vchess.git] / client / src / router.js
index 82f0100..6814895 100644 (file)
@@ -8,7 +8,10 @@ function loadView(view) {
        return () => import(/* webpackChunkName: "view-[request]" */ `@/views/${view}.vue`)
 }
 
-export default new Router({
+import { ajax } from "@/utils/ajax";
+import { store } from "@/store";
+
+const router = new Router({
   routes: [
     {
       path: "/",
@@ -25,6 +28,31 @@ export default new Router({
       name: "rules",
       component: loadView("Rules"),
     },
+    {
+      path: "/authenticate/:token",
+      name: "authenticate",
+      beforeEnter: (to, from, next) => {
+        ajax(
+          "/authenticate",
+          "GET",
+          {token: to.params["token"]},
+          (res) => {
+            if (!res.errmsg) //if not already logged in
+            {
+              store.state.user.id = res.id;
+              store.state.user.name = res.name;
+              store.state.user.email = res.email;
+              store.state.user.notify = res.notify;
+              localStorage["myname"] = res.name;
+              localStorage["myid"] = res.id;
+            }
+            next();
+          }
+        );
+      },
+      component: Hall,
+      //redirect: "/", //problem: redirection before end of AJAX request
+    },
 //    {
 //      path: "/about",
 //      name: "about",
@@ -39,3 +67,11 @@ export default new Router({
     // TODO: gameRef, problemId: https://router.vuejs.org/guide/essentials/dynamic-matching.html
   ]
 });
+
+router.beforeEach((to, from, next) => {
+  window.scrollTo(0, 0); //TODO: check if a live game is running; if yes, call next('/game')
+  //https://router.vuejs.org/guide/advanced/navigation-guards.html#global-before-guards
+  next();
+});
+
+export default router;