Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Am bug fix #7

Merged
merged 3 commits into from
Oct 11, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
290 changes: 179 additions & 111 deletions http_server.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,107 @@ import dotenv from 'dotenv';
dotenv.config();
const clientSecret = process.env.GITHUB_CLIENT_SECRET;
const socketToUserData = new Map();
let globalGithubOAuthID = null;


import pkg from 'pg';
const { Pool } = pkg;


const pool = new Pool({
user: 'postgres',
host: 'localhost',
database: 'postgres',
password: 'ABMARTIN',
port: 5432
});

async function addUserToDatabase(user) {
try {
// Check if the user already exists in the database based on their GitHub OAuth ID
const checkQuery = 'SELECT * FROM users WHERE github_oauth_id = $1;';
const checkResult = await pool.query(checkQuery, [user.github_oauth_id]);

if (checkResult.rows.length > 0) {
// User already exists; return the existing user
return checkResult.rows[0];
}

// User doesn't exist; insert them into the database
const insertQuery = `
INSERT INTO users(github_oauth_id, username, display_name, joined_date)
VALUES($1, $2, $3, $4)
RETURNING *;
`;

const insertValues = [user.github_oauth_id, user.username, user.display_name, user.joined_date];

const result = await pool.query(insertQuery, insertValues);
return result.rows[0]; // Returns the inserted user
} catch (err) {
console.error('Error inserting user into database:', err);
throw err;
}
}

async function getHistoricalMessagesFromDatabase(room) {
try {
const query = `
SELECT * FROM messages
WHERE room = $1
ORDER BY timestamp;
`;
const result = await pool.query(query, [room]);

// Return the result as JSON
return result.rows;
} catch (err) {
console.error('Error retrieving historical messages from database:', err);
throw err;
}
}

async function insertMessageIntoDatabase(user, room, message, timestamp, socket) {
try {
const userData = socketToUserData.get(socket.id);
if (!userData || !userData.user_id) {
console.error('User not found for socket:', socket.id);
return null; // Return null or handle the case when the user is not found
}

const user_id = userData.user_id; // Retrieve the user_id from the user object

const query = `
INSERT INTO messages(user_id, room, message_content, timestamp, is_edited)
VALUES($1, $2, $3, $4, $5)
RETURNING message_id;
`;

const values = [user_id, room, message, timestamp, false];

const result = await pool.query(query, values);
return result.rows[0].message_id;
} catch (err) {
console.error('Error inserting message into database:', err);
throw err;
}
}



// Function to retrieve a message from the database
async function getMessageFromDatabase(messageID) {
try {
const query = 'SELECT * FROM messages WHERE message_id = $1;';
const result = await pool.query(query, [messageID]);
return result.rows[0];
} catch (err) {
console.error('Error retrieving message from database:', err);
throw err;
}
}


let messagesLog = [];
const users = [];

const app = express();
const httpServer = createServer(app);
Expand All @@ -27,20 +125,22 @@ io.on('connection', (socket) => {
socket.on('set-user', (userid, callback) => {
console.log("User ID received:", userid);
if (userid != null) {
socketToUserData.set(socket.id, userid);
callback('User ID received successfully.');
socketToUserData.set(socket.id, { user_id: userid }); // Store user_id as an object
callback('User ID received successfully.');
} else {
callback('error');
}
});

// Handle joining a chatroom

socket.on('join-room', (room) => {
socket.join(room);
socket.emit('request-historical-messages', room);
});

// Handle sending a message
socket.on('send-message', ({ room, message }) => {

// Handle sending a message
socket.on('send-message', async ({ room, message }) => {
const user = socketToUserData.get(socket.id);
if (!user) {
console.error('User not found for socket:', socket.id);
Expand All @@ -49,41 +149,36 @@ io.on('connection', (socket) => {
const timestamp = new Date().toISOString();
console.log(`${room} (${timestamp}): ${message}`);

// Store the message details
/*
Messages
message_id: Primary Key, Auto-incremented
building_id: Foreign Key referencing Buildings
user_id: Foreign Key referencing Users
message_content: Text content of the message
timestamp: Date and time when the message was sent
is_edited: Boolean, indicating if the message was edited
*/
const messageID = (messagesLog.length === 0) ? 0 : messagesLog[messagesLog.length - 1] + 1;
const is_edited = false;
const newMessage = {
messageID,
room,
user,
message,
timestamp,
is_edited
};
messagesLog.push(newMessage);

// Emit the new message to everyone in the room
io.to(room).emit('receive-message', newMessage);
// Pass the 'socket' object as a parameter to 'insertMessageIntoDatabase'
try {
const messageID = await insertMessageIntoDatabase(user, room, message, timestamp, socket);

// Retrieve the newly inserted message from the database
const newMessage = await getMessageFromDatabase(messageID);

// Emit the new message to everyone in the room
io.to(room).emit('receive-message', newMessage);
} catch (err) {
console.error('Error sending message:', err);
// Handle the error and send an appropriate response
// You may want to emit an error event to the client here
}
});

// Handle the request for historical messages
socket.on('request-historical-messages', (room) => {
socket.on('request-historical-messages', async (room) => {
console.log("request-historical-messages");
const roomMessages = messagesLog.filter(msg => msg.room === room);
socket.emit('historical-messages', roomMessages);
try {
const roomMessages = await getHistoricalMessagesFromDatabase(room);
socket.emit('historical-messages', roomMessages);
} catch (err) {
console.error('Error handling request for historical messages:', err);
// Handle the error and send an appropriate response
// You may want to emit an error event to the client here
}
});



socket.on('leave-room', (room) => {
socket.leave(room);
});
Expand Down Expand Up @@ -129,112 +224,85 @@ app.get('/auth/github/callback', async (req, res) => {
const githubUserData = userResponse.data;
console.log('Received user data from GitHub:', githubUserData);

/*
Will stay in callback
const user = {
const user = {
github_oauth_id: githubUserData.id,
username: githubUserData.login,
display_name: githubUserData.name || githubUserData.login,
joined_date: new Date().toISOString()
joined_date: new Date().toISOString(),
};

// Set the global variable to store the GitHub OAuth ID
globalGithubOAuthID = githubUserData.id;

try {
const savedUser = await addUserToDatabase(user);
console.log('User saved to database:', savedUser);

// Set the user data in a cookie
res.cookie('userData', JSON.stringify(savedUser));
// Redirect user back to app
res.redirect('/main'); // This is the only place where you should send a response
console.log('Redirected user back to app.');
} catch (err) {
console.error('Error saving user to database:', err);
// Handle the error and send an appropriate response
res.status(500).json({ error: 'Internal server error' });
}

*/

// Store user data in local storage- will be deleted
const user = {
github_oauth_id: githubUserData.id,
username: githubUserData.login,
display_name: githubUserData.name || githubUserData.login,
joined_date: new Date().toISOString()
};
users.push(user);
console.log('Stored user in local storage:', user);

//end of deleted portion

/*
Digital Ocean replacement-connection template for postgresql
const { Pool } = require('pg');

const pool = new Pool({
user: 'your_db_username',
host: 'your_db_host',
database: 'your_db_name',
password: 'your_db_password',
port: your_db_port
});


*/

/*
Adding new user data to db after oauth
async function addUserToDatabase(user) {
app.get('/get-historical-messages', async (req, res) => {
const { room } = req.query;
try {
const query = `
INSERT INTO users(github_oauth_id, username, display_name, joined_date)
VALUES($1, $2, $3, $4)
RETURNING *;
`;

const values = [user.github_oauth_id, user.username, user.display_name, user.joined_date];

const result = await pool.query(query, values);
return result.rows[0]; // Returns the inserted user
const roomMessages = await getHistoricalMessagesFromDatabase(room);
res.json(roomMessages);
} catch (err) {
console.error('Error inserting user into database:', err);
throw err;
console.error('Error handling request for historical messages:', err);
res.status(500).json({ error: 'Internal server error' });
}
}

*/

/*
SQL CODE for creating table:
CREATE TABLE users (
github_oauth_id BIGINT UNIQUE NOT NULL PRIMARY KEY,
username VARCHAR(255) NOT NULL,
display_name VARCHAR(255),
joined_date TIMESTAMP NOT NULL
);

*/
// Return the user data in the HTTP response
res.cookie('userData', JSON.stringify(user));
res.redirect('/main'); // Redirect user back to app
console.log('Redirected user back to app.');
});


app.get('/logout', (req, res) => {
res.cookie('userData', "")
res.redirect('/')
console.log('logging user out')
})

app.get('/get-username', (req, res) => {
const { userid } = req.query;
console.log("Finding username of user with id " + userid);
app.get('/get-username', async (req, res) => {
let { userid } = globalGithubOAuthID;

console.log("Finding username of user with id " + globalGithubOAuthID);

// Find the user in the users array
const user = users.find(u => u.github_oauth_id === parseInt(userid));
console.log(users)
console.log("username " + user.username);
try {
userid=globalGithubOAuthID;
const user = await getUserFromDatabase(userid);
console.log("username " + user.username);

if (user) {
res.json({ username: user.username });
} else {
res.status(404).json({ error: "User not found" });
if (user) {
res.json({ username: user.username });
} else {
res.status(404).json({ error: "User not found" });
}
} catch (err) {
console.error('Error retrieving user from database:', err);
// Handle the error and send an appropriate response
res.status(500).json({ error: 'Internal server error' });
}
});


async function getUserFromDatabase(userid) {
try {
const query = 'SELECT * FROM users WHERE github_oauth_id = $1;';
const result = await pool.query(query, [parseInt(userid)]);
return result.rows[0];
} catch (err) {
console.error('Error retrieving user from database:', err);
throw err;
}
}


app.use(express.json());

ViteExpress.listen(app, 3000, () => {
Expand Down
Loading