Skip to content

Commit

Permalink
Merge pull request #156 from agiledev-students-spring2024/UpdateSockets
Browse files Browse the repository at this point in the history
Sockets know which username is associated with them and /chatpage is in accessible unless username is specified
  • Loading branch information
hongsimmon authored Apr 23, 2024
2 parents bbedef9 + e8f3acd commit 444cb5c
Show file tree
Hide file tree
Showing 8 changed files with 30 additions and 4 deletions.
2 changes: 1 addition & 1 deletion back-end/App.js
Original file line number Diff line number Diff line change
Expand Up @@ -215,7 +215,7 @@ app.post('/survey', (req, res) => {
});

app.get('/matches', async (req, res) => {
console.log('matches:', req.session.user)
//console.log('matches:', req.session.user)
req.session.user = req.session.user || "randomname";
try {
User.find()
Expand Down
14 changes: 14 additions & 0 deletions back-end/Server.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ connectDB();

const {createServer} = require('http')
const { Server } = require('socket.io');
const { error } = require("console");
const httpServer = createServer();
const io = new Server(httpServer, {cors: {
origin: ['http://localhost:3000'],
Expand All @@ -18,6 +19,15 @@ io.on('connection_error', (err) => {
console.log(err);
});

io.use((socket) => {
const sockUsername = socket.handshake.auth.username;
if(!sockUsername) {
console.log("No username received");
}
socket.username = sockUsername;
console.log(`Socket username: ${socket.username}`);
});

io.on('connection', (socket) => {
console.log(`a user has connected, user id = ${socket.id}`);

Expand All @@ -29,6 +39,10 @@ io.on('connection', (socket) => {
socket.on('disconnect', () => {
console.log("a user has disconnected");
});

socket.off('disconnect', () => {
console.log("socket is off");
});
});

httpServer.listen(3002, () => {
Expand Down
2 changes: 1 addition & 1 deletion front-end/src/App.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ function App() {
<Routes>
<Route path="/login" element={<LoginForm />} />
<Route path="/register" element={<RegistrationForm />} />
<Route path="/chatpage" element={<ProtectedRoute><ChatPage /></ProtectedRoute>} />
<Route path="/chatpage/:username" element={<ProtectedRoute><ChatPage /></ProtectedRoute>} />
<Route path="/chatlist" element={<ProtectedRoute><ChatList /></ProtectedRoute>} />
<Route path="/matches" element={<ProtectedRoute><Matches /></ProtectedRoute>} />
<Route path="/survey" element={<ProtectedRoute><Survey /></ProtectedRoute>} />
Expand Down
1 change: 0 additions & 1 deletion front-end/src/ChatPage.js
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,6 @@ function ChatPage() {
}, []);

useEffect(() => {

getUser();

console.log("Fetching chat history...")
Expand Down
6 changes: 6 additions & 0 deletions front-end/src/LoginForm.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import React, { useState } from 'react';
import { useNavigate, Link } from 'react-router-dom';
import { socket } from './sockets/ReactSocket';
import './landingPages.css';


Expand Down Expand Up @@ -27,6 +28,11 @@ function LoginForm() {

if (response.ok) {
console.log('Login successful:', data);

//connect the chat socket and register its username
socket.auth = { username };
socket.connect();

localStorage.setItem('token', data.token); // Save the token to localStorage
navigate('/matches'); // Navigate to the 'matches' route on successful login
} else {
Expand Down
2 changes: 2 additions & 0 deletions front-end/src/Profile.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import Header from './Header';
import Button from './Button';
import profilePicture from './ProfilePic.png';
import "./Profile.css";
import { socket } from './sockets/ReactSocket';

function Profile() {
const [profileData, setProfileData] = useState({});
Expand Down Expand Up @@ -39,6 +40,7 @@ function Profile() {
const handleLogout = () => {
console.log("Logging out...");
localStorage.removeItem('token');
socket.disconnect(); //disconnect the socket that was in use
navigate('/login', { replace: true });
};

Expand Down
5 changes: 5 additions & 0 deletions front-end/src/RegistrationForm.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import React, { useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { socket } from './sockets/ReactSocket';
import './landingPages.css';

function RegistrationForm() {
Expand Down Expand Up @@ -35,6 +36,10 @@ function RegistrationForm() {
// If the server responds with a non-OK HTTP status, display the error message
setErrorMessage(data.message || 'Failed to sign up.');
} else {
//connect chat socket and register username
socket.auth.username = username;
socket.connect();

// On successful registration, navigate to the survey page
console.log('Registration successful:', data);
navigate('/survey');
Expand Down
2 changes: 1 addition & 1 deletion front-end/src/sockets/ReactSocket.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
import { io } from 'socket.io-client'

export const socket = io('http://localhost:3002')
export const socket = io('http://localhost:3002', {autoConnect: false});

0 comments on commit 444cb5c

Please sign in to comment.