Skip to content

Commit

Permalink
Merge pull request #44 from CoderSwarup/userduplication
Browse files Browse the repository at this point in the history
fix #40 Users Can Join Room with Duplicate Name
  • Loading branch information
urstrulynishkarsh committed May 12, 2024
2 parents aa9c767 + b5e29c3 commit 264fde3
Show file tree
Hide file tree
Showing 4 changed files with 99 additions and 95 deletions.
112 changes: 56 additions & 56 deletions server/Utils/Users.js
Original file line number Diff line number Diff line change
@@ -1,62 +1,62 @@
// first we create an empty array of users
const users=[];

// first we create an empty array of users
const users = [];

// add user into the users array
const addUser=({id,username,room})=>{

// clean the data
username=username.trim().toLowerCase();
room=room.trim().toLowerCase();

// Validate the data
if (!username || !room) {
return {
error: 'Username and room are required!'
}
}
// check for existing User
const existingUser=users.find((user)=>{
return user.room===room && user.username===username;
})

// validate
if(existingUser)
{
return{
error:'UserName is in Used'
}
}

// push into the array
const user={id,username,room};
users.push(user);
return {user}

}

// remove user by id
const removeUser=(id)=>{
const index=users.findIndex((user)=>user.id===id)

if(index!==-1)
{
return users.splice(index,1)[0]
}
}

// getuser by id
const getUser=(id)=>{
return users.find((user)=>user.id===id)
}
const addUser = ({ id, username, room }) => {
// clean the data
username = username.trim().toLowerCase();
room = room.trim().toLowerCase();

// Validate the data
if (!username || !room) {
return {
status: false,
error: "Username and room are required!",
user: {},
};
}

// check for existing User

const existingUser = users?.find((user) => {
if (user?.room === room && user?.username === username) return true;
else return false;
});

// validate
if (existingUser) {
return {
status: false,
error: "UserName is in Used",
user: {},
};
}

// push into the array
const user = { id, username, room };
users.push(user);
return { status: true, error: "", user };
};

// remove user by id
const removeUser = (id) => {
const index = users.findIndex((user) => user.id === id);

if (index !== -1) {
return users.splice(index, 1)[0];
}
};

// getuser by id
const getUser = (id) => {
return users.find((user) => user.id === id);
};

// getUsersInRoom by room

const getUsersInRoom=(room)=>{
room=room.trim().toLowerCase();
return users.filter((user)=>user.room===room)
}

module.exports={addUser,removeUser,getUser,getUsersInRoom};

const getUsersInRoom = (room) => {
room = room.trim().toLowerCase();
return users.filter((user) => user.room === room);
};

module.exports = { addUser, removeUser, getUser, getUsersInRoom };
15 changes: 10 additions & 5 deletions server/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -52,12 +52,14 @@ io.on("connection", (socket) => {

// method ,options,callback
socket.on("join", (options, callback) => {
const { error, user } = addUser({ id: socket.id, ...options });
const { status, error, user } = addUser({ id: socket.id, ...options });

if (error) {
return callback(error);
if (!status) {
return callback({
status,
error,
});
}

socket.join(user.room);

socket.emit("message", generateMessage(`${user.username}`, "Welcome!"));
Expand All @@ -72,7 +74,10 @@ io.on("connection", (socket) => {
users: getUsersInRoom(user.room),
});

callback();
callback({
status,
error,
});
});

socket.on("sendMessage", (message, callback) => {
Expand Down
46 changes: 24 additions & 22 deletions src/Components/ChatPage.jsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import React, { useEffect, useRef, useState } from "react";
import React, { useEffect, useMemo, useRef, useState } from "react";
import { io } from "socket.io-client";
import { useLocation } from "react-router";
import MessageTemplate from "./MessageTemplate";
Expand All @@ -17,12 +17,13 @@ import {
} from "react-icons/ai";
import MobileMenu from "./MobileMenu";

// const socket = io('ws://localhost:8080/', { transports: ['websocket'] });

// wss://reactchat-production-f378.up.railway.app/
// dev mode http://localhost:5000
const socket = io("wss://reactchat-production-f378.up.railway.app/", {
transports: ["websocket"],
});
// const socket = io('ws://localhost:8080/', { transports: ['websocket'] });

const ChatPage = ({ darkMode, setDarkMode }) => {
const location = useLocation();
Expand Down Expand Up @@ -53,26 +54,6 @@ const ChatPage = ({ darkMode, setDarkMode }) => {
ignoreQueryPrefix: true,
});

socket.emit("join", { username, room }, (error) => {
if (error) {
// Display popup if the user is already in a room
// Swal.fire({
// title: 'Already in Room',
// text: 'You are already in a room. Redirecting to home page...',
// icon: 'info',
// showConfirmButton: false,
// timer: 2000, // Adjust the timer as needed
// willClose: () => {
// navigate('/'); // Redirect to home page
// }
// });
// console.log("new part")
} else {
setHasError(false);
toast.success(`${username} joined the room!`);
}
});

// useEffect(() => {
// socket.on('disconnect', () => {
// console.log('Disconnected from the server');
Expand All @@ -84,6 +65,27 @@ const ChatPage = ({ darkMode, setDarkMode }) => {
// };
// }, []);

useEffect(() => {
socket.emit("join", { username, room }, (data) => {
if (!data.status) {
// Display popup if the user is already in a room
Swal.fire({
title: "Already in Room",
text: "You are already in a room. Redirecting to home page...",
icon: "info",
showConfirmButton: false,
timer: 2000, // Adjust the timer as needed
willClose: () => {
navigate("/"); // Redirect to home page
},
});
// console.log("new part")
} else {
setHasError(false);
toast.success(`${username} joined the room!`);
}
});
}, []);
useEffect(() => {
socket.on("message", (message) => {
setMessages((prevMessages) => [
Expand Down
21 changes: 9 additions & 12 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@ import { Toaster } from "react-hot-toast";
import Loader from "./Components/Loader";
import { DarkModeToggle } from "dark-mode-toggle";


const RootComponent = () => {
const [isLoading, setIsLoading] = useState(true);

Expand All @@ -30,22 +29,20 @@ const RootComponent = () => {
}
}, []);


return (
<React.StrictMode>
<>
{isLoading ? (
<div >
<Loader/>
<div>
<Loader />
</div>
) : (

<BrowserRouter>
<App />
<Toaster />
<ToastContainer />
</BrowserRouter>
<BrowserRouter>
<App />
<Toaster />
<ToastContainer />
</BrowserRouter>
)}
</React.StrictMode>
</>
);
};

Expand Down

0 comments on commit 264fde3

Please sign in to comment.