Skip to content

Commit

Permalink
added token verification to matchmaking and game setup before sending…
Browse files Browse the repository at this point in the history
… token to game server
  • Loading branch information
Otto Andelin committed Aug 24, 2024
1 parent 58febf1 commit 7a57a5b
Show file tree
Hide file tree
Showing 7 changed files with 119 additions and 74 deletions.
117 changes: 63 additions & 54 deletions Frontend/src/js/modals/playonline.js
Original file line number Diff line number Diff line change
Expand Up @@ -35,13 +35,15 @@ export function openWaitingLobby() {
}

function connectToWebSockets() {
// const userData = JSON.parse(sessionStorage.getItem('userData'));
// if (!userData || !userData.token) {
// console.error('User data or token is missing');
// return;
// }
const token = handleTokenVerification()
const onlineStatusSocket = new WebSocket(`/ws/online/?token=${token}`);
const userData = JSON.parse(sessionStorage.getItem('userData'));
if (!userData || !userData.token) {
console.error('User data or token is missing');
return;
}
handleTokenVerification()
.then(validToken => {
userData.token = validToken;
const onlineStatusSocket = new WebSocket(`/ws/online/?token=${userData.token}`);

let gameRoomSocket;

Expand Down Expand Up @@ -74,60 +76,62 @@ function connectToWebSockets() {
onlineStatusSocket.onerror = function(error) {
console.error('Error in online status WebSocket:', error);
};
const anotherToken = handleTokenVerification()

function connectToGameRoom(roomName) {
gameRoomSocket = new WebSocket(`/ws/game/room/${roomName}/?token=${anotherToken}`);

gameRoomSocket.onopen = function() {
console.log(`Connected to game room ${roomName} WebSocket`);
gameRoomSocket.send(JSON.stringify({ type: 'join', username: userData.username }));
};

gameRoomSocket.onmessage = function(event) {
const data = JSON.parse(event.data);
console.log(data)
if (data.type === 'starting_game') {
// lobbyContent.innerHTML =
// `<div class="d-flex justify-content-center">
// <div class="spinner-border" style="width: 4rem; height: 4rem;" role="status">
// <span class="visually-hidden">Starting game..</span>
// </div>
// </div>`;
waitingLobbyModalLabel.textContent = "Starting game..";

let config = {
isRemote: true,
gameId: data.message.game_id,
playerIds: [data.message.player1_id, data.message.player2_id],
player1Alias: data.message.player1_username,
player2Alias: data.message.player2_username,
isLocalTournament: false,
handleTokenVerification()
.then(validToken => {
userData.token = validToken;
gameRoomSocket = new WebSocket(`/ws/game/room/${roomName}/?token=${userData.token}`);

gameRoomSocket.onopen = function() {
console.log(`Connected to game room ${roomName} WebSocket`);
gameRoomSocket.send(JSON.stringify({ type: 'join', username: userData.username }));
};

if (onlineStatusSocket.readyState === WebSocket.OPEN) {
onlineStatusSocket.close();
}
gameRoomSocket.onmessage = function(event) {
const data = JSON.parse(event.data);
console.log(data)
if (data.type === 'starting_game') {
// lobbyContent.innerHTML =
// `<div class="d-flex justify-content-center">
// <div class="spinner-border" style="width: 4rem; height: 4rem;" role="status">
// <span class="visually-hidden">Starting game..</span>
// </div>
// </div>`;
waitingLobbyModalLabel.textContent = "Starting game..";

let config = {
isRemote: true,
gameId: data.message.game_id,
playerIds: [data.message.player1_id, data.message.player2_id],
player1Alias: data.message.player1_username,
player2Alias: data.message.player2_username,
isLocalTournament: false,
};

if (onlineStatusSocket.readyState === WebSocket.OPEN) {
onlineStatusSocket.close();
}

if (gameRoomSocket && gameRoomSocket.readyState === WebSocket.OPEN) {
gameRoomSocket.close();
}

// pongModal.show();
waitingLobbyModal.hide();
startGame('pongGameContainer', config, handleGameEnd);
}
};

if (gameRoomSocket && gameRoomSocket.readyState === WebSocket.OPEN) {
gameRoomSocket.close();
}
gameRoomSocket.onclose = function(event) {
console.log(`Game room ${roomName} WebSocket closed:`, event);
};

// pongModal.show();
waitingLobbyModal.hide();
startGame('pongGameContainer', config, handleGameEnd);
gameRoomSocket.onerror = function(error) {
console.error(`Error in game room ${roomName} WebSocket:`, error);
};
}
};

gameRoomSocket.onclose = function(event) {
console.log(`Game room ${roomName} WebSocket closed:`, event);
};

gameRoomSocket.onerror = function(error) {
console.error(`Error in game room ${roomName} WebSocket:`, error);
};
}

)}
waitingLobbyModalElement.addEventListener('hide.bs.modal', function () {
console.log('Modal is closing. Disconnecting WebSockets.');
if (onlineStatusSocket.readyState === WebSocket.OPEN) {
Expand All @@ -138,6 +142,11 @@ function connectToWebSockets() {
gameRoomSocket.close();
}
});
})
.catch(error => {
console.error('Error verifying token:', error);
});

}

function handleGameEnd(data) {
Expand Down
31 changes: 22 additions & 9 deletions Frontend/src/js/pong/classes/GameSession.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import { endGame } from '../pong.js';
import { globalState } from '../globalState.js';
import { sendQuit } from '../eventhandlers.js';
import { cleanupEventHandlers } from '../eventhandlers.js';
import { handleTokenVerification } from '../../tokenHandler.js';

class GameSession {
constructor() {
Expand Down Expand Up @@ -75,19 +76,31 @@ class GameSession {
console.log('Game Session Initialized');
console.log('Game Init Data:', gameInitData);

if (isRemote === false) {
if (isRemote === true) {
const userData = JSON.parse(sessionStorage.getItem('userData'));
if (!userData || !userData.token) {
console.error('User data or token is missing');
return;
}
handleTokenVerification()
.then(validToken => {
userData.token = validToken;
gameInitData['token'] = userData.token;
gameInitData['type'] = 'join_game';
this.socket.emit('join_game', gameInitData);
})
.catch(error => {
console.error('Error verifying token:', error);
});
}
else {
gameInitData['type'] = 'start_game';
this.socket.emit('start_game', gameInitData);
}
else {
const userData = JSON.parse(sessionStorage.getItem('userData'));
gameInitData['token'] = userData.token;
gameInitData['type'] = 'join_game';
this.socket.emit('join_game', gameInitData);
}
initializeEventHandlers(this);

initializeEventHandlers(this);
}

}

sendMovement(data) {
this.socket.emit('move_paddle', data);
Expand Down
22 changes: 18 additions & 4 deletions Frontend/src/js/pong/eventhandlers.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import socket from './socket';
import GameSession from './classes/GameSession';
import { cleanUpGame, endGame } from './pong.js';

let isConnected = false
// Initialize event handlers for the game
// This function should be called once when the game is loaded
// It sets up event listeners for the game
Expand All @@ -14,12 +15,14 @@ export const initializeEventHandlers = (gameSession) => {

// Event handler for the socket connection
socket.on('connect', () => {
isConnected = true
console.log('Connected to server');
});

// Event handler for the socket disconnection
socket.on('disconnect', () => {
console.log('Disconnected from server');
socket.on('disconnect', (reason) => {
isConnected = false
console.log(`Disconnected from server: ${reason}`);
});

// Event handler for the game start message
Expand All @@ -35,7 +38,13 @@ export const initializeEventHandlers = (gameSession) => {
}
}
});

socket.on('connect_error', (error) => {
console.error('Connection error:', error);
});

socket.on('reconnect_error', (error) => {
console.error('Reconnection error:', error);
});
// Event handler for the game state message
// This message is sent by the server when the game state is updated
// The game session object is responsible for updating the game state
Expand Down Expand Up @@ -103,7 +112,12 @@ export const initializeEventHandlers = (gameSession) => {

// Emit events to the server
export const sendMovement = (data) => {
socket.emit('move_paddle', data);
if (isConnected) {
socket.emit('move_paddle', data);
}
else {
console.log("cannot send anthing, not connected")
}
};

// Send quit game message to the server
Expand Down
5 changes: 4 additions & 1 deletion Frontend/src/js/pong/socket.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,10 @@
import { io } from 'socket.io-client';

// Use the proxy path for local development
const socket = io('/', {path: '/game-server/socket.io',});
const socket = io('/', {path: '/game-server/socket.io',
pingInterval: 10000, // 10 seconds between pings
pingTimeout: 5000 // 5 seconds to wait for pong before disconnecting
});
// const socket = io();

// socket.on('connect', () => {
Expand Down
6 changes: 3 additions & 3 deletions Game_server/game_logic/entities/gamestate.py
Original file line number Diff line number Diff line change
Expand Up @@ -187,9 +187,9 @@ def check_goal(self) -> None:
# and gives it a random direction
def reset_ball(self):
if self.ball.x < 0:
self.ball.direction = random.randrange(140, 220) #random direction towards player 1
elif self.ball.x > FIELD_DEPTH:
self.ball.direction = random.randrange(-40, 40) #random direction towards player 2
elif self.ball.x > FIELD_DEPTH:
self.ball.direction = random.randrange(140, 220) #random direction towards player 1
else:
if random.random() >= .5:
self.ball.direction = random.randrange(-12, 12)
Expand All @@ -201,4 +201,4 @@ def reset_ball(self):
# is_game_over method
# returns True if the game is over, False otherwise
def is_game_over(self) -> bool:
return self.time_remaining <= 0 or self.player1.score >= 10 or self.player2.score >= 10
return self.time_remaining <= 0 or self.player1.score >= 10 or self.player2.score >= 10
8 changes: 6 additions & 2 deletions Game_server/server.py
Original file line number Diff line number Diff line change
Expand Up @@ -143,7 +143,7 @@ async def send_game_state_to_client(self):
},
'bounce' : self.game_state.bounce,
'hitpos' : self.game_state.hitpos,
},
}
for sid in self.sids:
await sio.emit('send_game_state', game_state_data, room=sid)

Expand Down Expand Up @@ -296,7 +296,8 @@ async def disconnect(sid):
if not game_instance.sids:
logging.info(f"No players left in game {game_id}, ending game session")
await game_instance.end_game()
del active_games[game_id] # Clean up properly
# if active_games[game_id]:
# del active_games[game_id] # Clean up properly
logging.info(f"Game {game_id} terminated and removed from active_games")
else:
logging.info(f"Game {game_id} not found in active_games during disconnect")
Expand Down Expand Up @@ -385,7 +386,10 @@ async def join_game(sid, data):
player1_id = data.get('player1_id')
player2_id = data.get('player2_id')
is_remote = data.get('is_remote')
token = data.get('token')

if token:
logging.info(f"received a token {token}")
couple = coupled_request(game_id, player1_id, player2_id)
if couple is not None:
if player1_id == local_player_id:
Expand Down
4 changes: 3 additions & 1 deletion Game_server/server_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,9 @@
async_mode='asgi',
cors_allowed_origins="*", # Specify allowed origins
logger=False, # Disable Socket.IO logging
engineio_logger=False # Disable engineio logging
engineio_logger=False, # Disable engineio logging
ping_interval=10,
ping_timeout=5
)
# Create an ASGI application using the Socket.IO server
# This application can be run using an ASGI server such as Uvicorn
Expand Down

0 comments on commit 7a57a5b

Please sign in to comment.