Fix things. Now on (live) game start + play
authorBenjamin Auder <benjamin.auder@somewhere>
Thu, 28 Mar 2019 10:19:18 +0000 (11:19 +0100)
committerBenjamin Auder <benjamin.auder@somewhere>
Thu, 28 Mar 2019 10:19:18 +0000 (11:19 +0100)
client/src/components/UpsertUser.vue
client/src/parameters.js.dist
client/src/router.js
client/src/store.js
client/src/utils/ajax.js
client/src/views/Hall.vue
server/routes/users.js
server/sockets.js
server/utils/access.js

index 8d0b736..2b72ac2 100644 (file)
@@ -149,6 +149,8 @@ export default {
           this.user.name = "";
           this.user.email = "";
           this.user.notify = false;
+          delete localStorage["myid"];
+          delete localStorage["myname"];
         }
       );
     },
index 34b57e6..d24b1bd 100644 (file)
@@ -5,6 +5,9 @@ const Parameters =
 
        // URL of the server (leave blank for 1-server case)
        serverUrl: "http://localhost:3000",
+
+  // true if the server is at a different address
+  cors: false,
 };
 
 export default Parameters;
index 0f03849..ae298a7 100644 (file)
@@ -37,11 +37,15 @@ export default new Router({
           "GET",
           {token: to.params["token"]},
           (res) => {
-            store.state.user.id = res.id;
-            store.state.user.name = res.name;
-            store.state.user.email = res.email;
-            store.state.user.notify = res.notify;
-            // NOTE: mysid isn't cleared (required for potential game continuation)
+            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();
           }
         );
index 935005a..9d1c6e6 100644 (file)
@@ -14,22 +14,29 @@ export const store =
   },
   initialize() {
     ajax("/variants", "GET", res => { this.state.variants = res.variantArray; });
+    let mysid = localStorage["mysid"];
+    if (!mysid)
+    {
+      mysid = getRandString();
+      localStorage["mysid"] = mysid; //done only once (unless user clear browser data)
+    }
     this.state.user = {
-      id: 0, //unknown yet
-      name: "", //"anonymous"
+      id: localStorage["myid"] || 0,
+      name: localStorage["myname"] || "", //"" for "anonymous"
       email: "", //unknown yet
       notify: false, //email notifications
-      sid: localStorage["mysid"] || getRandString(),
+      sid: mysid,
     };
-    ajax("/whoami", "GET", res => {
-      if (res.id > 0)
-      {
-        this.state.user.id = res.id;
-        this.state.user.name = res.name;
+    if (this.state.user.id > 0)
+    {
+      fetch(params.serverUrl + "/whoami", {
+        method: "GET",
+        credentials: params.cors ? "include" : "omit",
+      }).then((res) => {
         this.state.user.email = res.email;
         this.state.user.notify = res.notify;
-      }
-    });
+      });
+    }
     this.state.conn = new WebSocket(params.socketUrl + "/?sid=" + this.state.user.sid);
     // Settings initialized with values from localStorage
     this.state.settings = {
index 1d181fa..c0ebbff 100644 (file)
@@ -48,7 +48,8 @@ export function ajax(url, method, data, success, error)
        xhr.open(method, params.serverUrl + url, true);
        xhr.setRequestHeader('X-Requested-With', "XMLHttpRequest");
        // Next line to allow cross-domain cookies in dev mode (TODO: if...)
-  xhr.withCredentials = true;
+  if (params.cors)
+    xhr.withCredentials = true;
   if (["POST","PUT"].includes(method))
        {
                xhr.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
index 9b5265a..0fd8322 100644 (file)
@@ -101,7 +101,7 @@ export default {
         fen: "",
         vid: 0,
         nbPlayers: 0,
-        to: ["", "", ""], //name of challenged players
+        to: ["", "", ""], //name(s) of challenged player(s)
         timeControl: "", //"2m+2s" ...etc
       },
     };
@@ -122,37 +122,32 @@ export default {
       return playerList;
     },
   },
-  watch: {
-    // Watch event "user infos retrieved" (through /whoami)
-    "st.user.id": function(newId) {
-      if (newId > 0) //should always be the case
-      {
-      // Ask server for current corr games (all but mines)
-  //    ajax(
-  //      "/games",
-  //      "GET",
-  //      {excluded: this.st.user.id},
-  //      response => {
-  //        this.games = this.games.concat(response.games);
-  //      }
-  //    );
-      // Also ask for corr challenges (open + sent to me)
-        ajax(
-          "/challenges",
-          "GET",
-          {uid: this.st.user.id},
-          response => {
-            console.log(response.challenges);
-            // TODO: post-treatment on challenges ?
-            this.challenges = this.challenges.concat(response.challenges);
-          }
-        );
-      }
-    },
-  },
   created: function() {
     // Always add myself to players' list
     this.players.push(this.st.user);
+    if (this.st.user.id > 0)
+    {
+    // Ask server for current corr games (all but mines)
+//    ajax(
+//      "/games",
+//      "GET",
+//      {excluded: this.st.user.id},
+//      response => {
+//        this.games = this.games.concat(response.games);
+//      }
+//    );
+    // Also ask for corr challenges (open + sent to me)
+      ajax(
+        "/challenges",
+        "GET",
+        {uid: this.st.user.id},
+        response => {
+          console.log(response.challenges);
+          // TODO: post-treatment on challenges ?
+          this.challenges = this.challenges.concat(response.challenges);
+        }
+      );
+    }
     // 0.1] Ask server for room composition:
     const socketOpenListener = () => {
       this.st.conn.send(JSON.stringify({code:"pollclients"}));
@@ -395,7 +390,6 @@ export default {
         }
         case "deletechallenge":
         {
-          console.log("receive delete");
           ArrayFun.remove(this.challenges, c => c.id == data.cid);
           break;
         }
@@ -435,7 +429,7 @@ export default {
       if (!!error)
         return alert(error);
       const ctype = this.classifyObject(this.newchallenge);
-      const cto = this.newchallenge.to.slice(0, this.newchallenge.nbPlayers);
+      const cto = this.newchallenge.to.slice(0, this.newchallenge.nbPlayers - 1);
       // NOTE: "from" information is not required here
       let chall =
       {
@@ -496,9 +490,10 @@ export default {
 // *  - prepare and start new game (if challenge is full after acceptation)
 // *    --> include challenge ID (so that opponents can delete the challenge too)
     clickChallenge: function(c) {
-      
+
+      console.log("click challenge");
       console.log(c);
-      
+
       if (!!c.accepted)
       {
         this.st.conn.send(JSON.stringify({code: "withdrawchallenge",
@@ -516,7 +511,6 @@ export default {
       else if (c.from.sid == this.st.user.sid
         || (this.st.user.id > 0 && c.from.id == this.st.user.id))
       {
-        console.log("send delete");
         // It's my challenge: cancel it
         this.sendSomethingTo(c.to, "deletechallenge", {cid:c.id});
         ArrayFun.remove(this.challenges, ch => ch.id == c.id);
@@ -599,7 +593,6 @@ export default {
       localStorage["increment"] = tc.increment;
       localStorage["started"] = JSON.stringify(
         [...Array(gameInfo.players.length)].fill(false));
-      localStorage["mysid"] = this.st.user.sid;
       localStorage["vname"] = this.getVname(gameInfo.vid);
       localStorage["fenInit"] = gameInfo.fen;
       localStorage["players"] = JSON.stringify(gameInfo.players);
index d633d81..b657920 100644 (file)
@@ -81,7 +81,7 @@ router.get('/sendtoken', access.unlogged, access.ajax, (req,res) => {
 router.get('/authenticate', access.unlogged, access.ajax, (req,res) => {
   UserModel.getOne("loginToken", req.query.token, (err,user) => {
                access.checkRequest(res, err, user, "Invalid token", () => {
-                       // If token older than params.tokenExpire, do nothing
+      // If token older than params.tokenExpire, do nothing
                        if (Date.now() > user.loginTime + params.token.expire)
                                return res.json({errmsg: "Token expired"});
                        // Generate session token (if not exists) + destroy login token
index e94f623..127b7fa 100644 (file)
@@ -83,6 +83,10 @@ module.exports = function(wss) {
           clients[obj.target].send(
             JSON.stringify({code:"refusechallenge", cid:obj.cid, from:sid}));
           break;
+        case "deletechallenge":
+          clients[obj.target].send(
+            JSON.stringify({code:"deletechallenge", cid:obj.cid, from:sid}));
+          break;
         case "newgame":
           clients[obj.target].send(JSON.stringify(
             {code:"newgame", gameInfo:obj.gameInfo, cid:obj.cid}));
index 20f3f79..a7eb92a 100644 (file)
@@ -6,7 +6,7 @@ module.exports =
        logged: function(req, res, next) {
                const callback = () => {
                        if (!loggedIn)
-                               return res.redirect("/");
+                               return res.json({errmsg: "Not logged in"});
                        next();
                };
                let loggedIn = undefined;
@@ -42,7 +42,7 @@ module.exports =
                // Just a quick heuristic, which should be enough
                const loggedIn = !!req.cookies.token;
                if (loggedIn)
-                       return res.redirect("/");
+                       return res.json({errmsg: "Already logged in"});
                next();
        },