diff --git a/backend/socket.js b/backend/socket.js index 43a1663..4170bee 100644 --- a/backend/socket.js +++ b/backend/socket.js @@ -13,6 +13,7 @@ function initializeSocket(server) { }); io.use((socket, next) => { + // user auth const token = socket.handshake.auth.token; if(token) { jwt.verify(token, jwtSecret, (err, user) => { @@ -28,21 +29,21 @@ function initializeSocket(server) { } }); + // open main socket connection io.on('connection', (socket) => { if (!socket.user) { + console.log(socket.user); console.log('User not authenticated'); + socket.emit('socket error', 'User not authenticated') socket.disconnect(); return; } const username = socket.user.username; - // useless option for log in users activity but why - //console.log(username + ' connected'); // Join a room with the user's username socket.join(username); - // chat message event socket.on('chat message', async (msgData) => { const { content, recipient } = msgData; @@ -51,8 +52,10 @@ function initializeSocket(server) { // Insert the new message into the database const result = await db.query('INSERT INTO messages (content, username, recipient) VALUES ($1, $2, $3) RETURNING id', [content, username, recipient]); insertedId = result.rows[0].id; + } catch (err) { console.error('Error inserting message:', err); + socket.emit('socket error', "Error inserting message, try refreshing the page") return; } @@ -63,7 +66,6 @@ function initializeSocket(server) { if (result.rows.length > 0) { const newMessage = result.rows[0]; - //console.log(formattedMessage); // Emit message to the sender's and recipient's rooms io.to(username).to(recipient).emit('chat message', { username: newMessage.username, recipient: newMessage.recipient, content: newMessage.content }); @@ -71,24 +73,6 @@ function initializeSocket(server) { } catch (err) { console.error('Error fetching inserted message:', err); } - - // I think this is not needed? (it cause duplicate messages with loading messages history) - // if (!socket.recovered) { - // try { - // const query = 'SELECT id, content, username, recipient FROM messages WHERE id > $1 ORDER BY id ASC'; - // const values = [socket.handshake.auth.serverOffset || 0]; - // const result = await db.query(query, values); - // //const newMessage = result.rows[0]; - // for (const row of result.rows) { - // if (row.username === username || row.recipient === username) { - // io.to(username).to(recipient).emit('chat message', { username: row.username, recipient: row.recipient, content: row.content }); - // - // } - // } - // } catch (e) { - // console.error('Error retrieving messages:', e); - // } - // } }); socket.on('get messages', async (recipient) => { const username = socket.user.username; @@ -108,17 +92,16 @@ function initializeSocket(server) { //console.log('Sending historical messages'); socket.emit('messages history', result.rows); } else { - io.emit('no messages', ); + io.emit('no messages'); } } catch (e) { console.error('Error retrieving messages:', e); + socket.emit('socket error', "Error retrieving messages, refresh the page") } }); - - // disconnect event socket.on('disconnect', () => { - console.log(username + ' has disconnected'); + return "Disconnected"; }); }); diff --git a/frontend/js/chat.js b/frontend/js/chat.js index c0c24b4..b40abb4 100644 --- a/frontend/js/chat.js +++ b/frontend/js/chat.js @@ -3,7 +3,7 @@ const input = document.getElementById('input'); const recipientForm = document.getElementById('recipientForm'); const recipientInput = document.getElementById('recipient'); const messages = document.getElementById('messages'); -const logoutButton = document.getElementById('logout'); +const error = document.getElementById('error'); document.getElementById('input').placeholder = `Send message as: ${localStorage.getItem('username')}`; let currentRecipient = null; @@ -11,23 +11,7 @@ window.onload = () => { document.getElementById('recipient').focus(); } - -logoutButton.onclick = logout; -function logout() { - fetch('/auth/logout', { - method: 'POST', - credentials: 'include' - }) - .then(response => { - if (response.ok) { - localStorage.clear(); - window.location.href = '/login'; - } - }) - .catch(error => { - console.error('Logout failed:', error); - }); -} +1 function initializeRecipient() { const savedRecipient = localStorage.getItem('currentRecipient'); if (savedRecipient) { @@ -71,7 +55,7 @@ async function initializeSocket() { socket.emit('get messages', initialRecipient); }); - socket.on('chat message', (msg, serverOffset) => { + socket.on('chat message', (msg) => { console.log('Received message:', msg); const { username, content, recipient } = msg; @@ -88,6 +72,11 @@ async function initializeSocket() { console.log('No previous messages found'); messages.innerHTML = '
No messages found
'; }); + socket.on('socket error', (msg) => { + console.log('There was an error: ', msg) + error.innerHTML = msg; + messages.innerHTML = 'No messages found
'; + }) recipientForm.addEventListener('submit', (e) => { e.preventDefault(); if (recipientInput.value) { diff --git a/frontend/js/settings.js b/frontend/js/settings.js new file mode 100644 index 0000000..380ec43 --- /dev/null +++ b/frontend/js/settings.js @@ -0,0 +1,18 @@ +const logoutButton = document.getElementById('logout'); + +logoutButton.onclick = logout; +function logout() { + fetch('/auth/logout', { + method: 'POST', + credentials: 'include' + }) + .then(response => { + if (response.ok) { + localStorage.clear(); + window.location.href = '/login'; + } + }) + .catch(error => { + console.error('Logout failed:', error); + }); +} diff --git a/frontend/routes/chat.html b/frontend/routes/chat.html index 526179b..01f82d8 100644 --- a/frontend/routes/chat.html +++ b/frontend/routes/chat.html @@ -1,25 +1,32 @@ - + - + + +