Browse Source

token to initialize a game is valid for 5 mins

romanmatiasko 10 years ago
parent
commit
639570d12b
3 changed files with 22 additions and 2 deletions
  1. 4 0
      public/javascripts/play.js
  2. 5 1
      public/javascripts/start.js
  3. 13 1
      server.js

+ 4 - 0
public/javascripts/play.js

@@ -283,6 +283,10 @@ $(function() {
     'increment': $increment
   });
 
+  $socket.on('token-invalid', function (data) {
+    showModal('Game link is invalid or has expired.');
+  });
+
   $socket.on('joined', function (data) {
     if (data.color === 'white') {
       $side = 'w';

+ 5 - 1
public/javascripts/start.js

@@ -15,6 +15,10 @@ $(function () {
     document.location = $URL + '/play/' + $token + '/' + $time + '/' + $increment;
   });
 
+  $socket.on('token-expired', function (data) {
+    $('#waiting').text('Game link has expired, generate a new one.');
+  });
+
   $('#play').click(function (ev) {
     var min = parseInt($('#minutes').val());
     var sec = parseInt($('#seconds').val());
@@ -22,7 +26,7 @@ $(function () {
       $time = min;
       $increment = sec;
       $socket.emit('start');
-      $('#waiting').slideDown(400); // show waiting for opponent message
+      $('#waiting').text('Generating game link').slideDown(400);
       ev.preventDefault();
     }
   });

+ 13 - 1
server.js

@@ -90,10 +90,19 @@ io.sockets.on('connection', function (socket) {
     var b = new Buffer(Math.random() + new Date().getTime() + socket.id);
     token = b.toString('base64').slice(12, 32);
 
+    //token is valid for 5 minutes
+    var timeout = setTimeout(function () {
+      if (games[token].players.length === 0) {
+        delete games[token];
+        socket.emit('token-expired');
+      }
+    }, 5 * 60 * 1000);
+
     games[token] = {
       'creator': socket,
       'players': [],
-      'interval': null
+      'interval': null,
+      'timeout': timeout
     };
 
     socket.emit('created', {
@@ -105,8 +114,11 @@ io.sockets.on('connection', function (socket) {
     var game, color, time = data.time;
 
     if (!(data.token in games)) {
+      socket.emit('token-invalid');
       return;
     }
+
+    clearTimeout(games[data.token].timeout);
     game = games[data.token];
 
     if (game.players.length >= 2) {