Skip to content

Commit

Permalink
Refactor room ID extraction and add validation
Browse files Browse the repository at this point in the history
  • Loading branch information
Kratospidey committed Feb 27, 2024
1 parent 1215a8f commit ba7cd1e
Show file tree
Hide file tree
Showing 5 changed files with 65 additions and 24 deletions.
26 changes: 20 additions & 6 deletions public/chat.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,23 @@ const messageForm = document.getElementById("messageForm");
const messageInput = document.getElementById("messageInput");

// Extract the server ID from the URL
const urlPath = window.location.pathname.split("/");
const roomId = urlPath[urlPath.length - 1];
// Extract the pathname from the current URL in the address bar
const path = window.location.pathname;

// Define a regex pattern to match '/server/' followed by one or more digits
const roomIDPattern = /^\/server\/(\d+)$/;

// Use the match method to test if the path matches the regex pattern
const match = path.match(roomIDPattern);

let roomId;

if (match) {
// If the pattern matches, 'match[1]' will contain the room ID
roomId = match[1];
// Emit the joinRoom event for this room ID
socket.emit("joinRoom", roomId);
}

let isEmojiSelectionMode = false; // Step 1: Introduce the flag

Expand All @@ -17,9 +32,6 @@ function scrollToBottom() {
}, 3000); // Adjust the delay as needed
}

// Join the chat room
socket.emit("joinRoom", roomId);

// Function to create and append message element
function appendMessage({
userId,
Expand Down Expand Up @@ -133,7 +145,9 @@ function fetchAndDisplayMessages(roomId) {
}

// Call this function when the user enters a chat room
fetchAndDisplayMessages(roomId);
if (match) {
fetchAndDisplayMessages(roomId);
}

let typingTimeout;
const TYPING_TIMER_LENGTH = 2000; // Set the typing timeout to 2 seconds
Expand Down
15 changes: 8 additions & 7 deletions public/styles.css
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,8 @@ input[type="text"] {
}

.login,
.signup {
.signup,
.onboarding {
display: flex;
flex-direction: column;
width: auto;
Expand Down Expand Up @@ -136,8 +137,8 @@ input[type="text"] {
align-items: center;
justify-content: flex-start;
overflow-y: auto; /* Enable vertical scrolling */
gap: 40px;
padding: 10px;
gap: 20px;
padding: 20px;
height: 60%;
margin-bottom: 20px;

Expand Down Expand Up @@ -236,8 +237,8 @@ input[type="text"] {

/* Styling for server avatars */
.server-avatar {
width: 80px; /* Set your desired size */
height: 80px; /* Maintain aspect ratio */
width: 65px; /* Set your desired size */
height: 65px; /* Maintain aspect ratio */
border-radius: 50%; /* Circular avatars */
border: 3px solid #a0a0a0; /* Border to match the skeuomorphic style */
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2); /* Soft shadow for depth */
Expand Down Expand Up @@ -364,7 +365,7 @@ pre {
}

.app-bg {
background-color: #65788b; /* A base color that complements the chat interface */
background-color: #3f453f; /* A base color that complements the chat interface */

/* Layered gradients for a deep inset material effect */
background-image: radial-gradient(
Expand Down Expand Up @@ -518,7 +519,7 @@ pre {
overflow-y: auto; /* Enable scrolling for the member list */
display: flex;
flex-direction: column;
gap: 20px;
gap: 25px;
margin-bottom: auto; /* Space above the server code */
}

Expand Down
34 changes: 28 additions & 6 deletions server.js
Original file line number Diff line number Diff line change
Expand Up @@ -1079,21 +1079,21 @@ server.listen(PORT, () => {
console.log(`Server running on port ${PORT}`);
});

io.on("connection", (socket) => {
io.on("connection", async (socket) => {
const cookieString = socket.request.headers.cookie;
const cookies = parseCookies(cookieString); // You'll need a function to parse the cookie string
// console.log(cookies);
const token = cookies.token; // Replace 'token' with the name of your cookie
// console.log("Headers:", socket.request.headers);

// Verify the token. The implementation depends on your authentication system
authenticateSocketToken(token)
.then((decoded) => {
// console.log("Authenticated user:", decoded.userId);
socket.emit("userId", { userId: decoded.userId });
// console.log(`server side id: ${decoded.userId}`);

// Server-side
socket.on("joinRoom", async (roomId) => {
if (!isValidRoomId(roomId)) {
return; // Stop processing this event
}

const cookieString = socket.request.headers.cookie;
const cookies = parseCookies(cookieString);
const token = cookies.token;
Expand Down Expand Up @@ -1151,6 +1151,9 @@ io.on("connection", (socket) => {
});

socket.on("sendMessage", async (data) => {
if (!isValidRoomId(roomId) || !isSocketInRoom(socket, roomId)) {
return; // Stop processing this event
}
const { message, roomId } = data;
const userId = decoded.userId; // Assuming this is obtained from token authentication

Expand Down Expand Up @@ -1180,6 +1183,10 @@ io.on("connection", (socket) => {
}
});
socket.on("typing", async (data) => {
if (!isValidRoomId(roomId) || !isSocketInRoom(socket, roomId)) {
return; // Stop processing this event
}

const { roomId, typing } = data;

// Broadcast the typing event to all other users in the room
Expand All @@ -1188,6 +1195,10 @@ io.on("connection", (socket) => {
socket.to(roomId).emit("typing", { username: username, typing });
});
socket.on("sendImage", async (data) => {
if (!isValidRoomId(roomId) || !isSocketInRoom(socket, roomId)) {
return; // Stop processing this event
}

const { imageUrl, roomId } = data;
const userId = decoded.userId; // Assuming this is obtained from token authentication

Expand Down Expand Up @@ -1255,6 +1266,17 @@ function authenticateSocketToken(token) {
});
}

// Utility function to validate room ID format
const isValidRoomId = (roomId) => {
const roomIDPattern = /^\/server\/(\d+)$/;
return roomIDPattern.test(roomId);
};

// Utility function to check if the socket is in the specified room
const isSocketInRoom = (socket, roomId) => {
return socket.rooms.has(roomId);
};

function parseCookies(cookieString) {
const list = {};
cookieString?.split(";").forEach((cookie) => {
Expand Down
12 changes: 7 additions & 5 deletions views/onboarding.ejs
Original file line number Diff line number Diff line change
Expand Up @@ -28,10 +28,10 @@
<body>
<div class="wrapper">
<div class="specific-w-300 onboarding">
<h2 class="display-3 text-white" id="card-heading">Onboarding</h2>

<h3 class="display-5 text-white" id="card-heading">Onboarding</h3>
<hr style="color: white; font-weight: bold" />
<!-- Create New Server Form -->
<h4 class="text-white">Create a New Server</h4>
<h5 class="text-white">Create a New Server</h5>
<form
id="createServerForm"
action="/create-server"
Expand Down Expand Up @@ -64,9 +64,11 @@
Create Server
</button>
</form>

<hr style="color: white; font-weight: bold" />
<!-- Join Existing Server Form -->
<h4 class="text-white mt-5">Join an Existing Server</h4>
<h5 class="text-white mt-1">
Join an Existing Server
</h5>
<form
id="joinServerForm"
action="/join-server"
Expand Down
2 changes: 2 additions & 0 deletions views/partials/header.ejs
Original file line number Diff line number Diff line change
Expand Up @@ -514,6 +514,8 @@
// Function to fetch server members and populate the dropdown
async function populateMemberDropdown(serverId) {
if (!serverId) return; // Exit if no serverId is provided
const response = await fetch(`/api/server/${serverId}/members`);
const members = await response.json();
// Clear existing options
Expand Down

0 comments on commit ba7cd1e

Please sign in to comment.