Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
50 commits
Select commit Hold shift + click to select a range
0c17b5d
Update package.json
SethTooSaucy Mar 1, 2024
168ac71
Update testmongo.js
SethTooSaucy Mar 1, 2024
0e790be
Update testmongo.js
SethTooSaucy Mar 5, 2024
60ace82
Update package.json
SethTooSaucy Mar 5, 2024
e60e9dc
Update testmongo.js
SethTooSaucy Mar 5, 2024
dbea6f5
Update testmongo.js
SethTooSaucy Mar 5, 2024
d35aba2
Update testmongo.js
SethTooSaucy Mar 22, 2024
4e86320
Update testmongo.js
SethTooSaucy Mar 23, 2024
2ede8bf
Update testmongo.js
SethTooSaucy Mar 23, 2024
42d4089
Update testmongo.js
SethTooSaucy Mar 23, 2024
17dfaeb
Create authController
SethTooSaucy Apr 26, 2024
73f5c82
Create user
SethTooSaucy Apr 26, 2024
6e57f0d
Create authRoutes
SethTooSaucy Apr 26, 2024
84969f4
Create login
SethTooSaucy Apr 26, 2024
2be9967
Create register
SethTooSaucy Apr 26, 2024
2e48af6
Merge pull request #1 from SethTooSaucy/SethDev
SethTooSaucy Apr 26, 2024
bf417e5
Update and rename authController to authController.js
SethTooSaucy Apr 26, 2024
ddbf00b
Update and rename user to user.js
SethTooSaucy Apr 26, 2024
01d88a0
Update and rename authRoutes to authRoutes.js
SethTooSaucy Apr 26, 2024
6e76022
Update and rename login to login.html
SethTooSaucy Apr 26, 2024
c5ef3ff
Rename register to register.html
SethTooSaucy Apr 26, 2024
b6280b6
Update testmongo.js
SethTooSaucy Apr 26, 2024
73f137b
Create topicsController.js
SethTooSaucy Apr 26, 2024
59c1e49
Create messagesController.js
SethTooSaucy Apr 26, 2024
048a337
Create topic.js
SethTooSaucy Apr 26, 2024
b3a4225
Create message.js
SethTooSaucy Apr 26, 2024
c138fb8
Create topicsRoutes.js
SethTooSaucy Apr 26, 2024
ba069bd
Create messagesRoutes.js
SethTooSaucy Apr 26, 2024
e717e60
Create topics.ejs
SethTooSaucy Apr 26, 2024
e45107e
Create messages.ejs
SethTooSaucy Apr 26, 2024
bbc82d4
Update testmongo.js
SethTooSaucy Apr 26, 2024
9ed6267
Merge pull request #2 from SethTooSaucy/SethDev
SethTooSaucy Apr 26, 2024
175e121
Created userController
ActionIVU Apr 28, 2024
f5f280b
More user stuff
ActionIVU Apr 28, 2024
f64c913
Update topicsController.js
SethTooSaucy Apr 29, 2024
9458e1e
Update topic.js
SethTooSaucy Apr 29, 2024
b9f943f
Update topics.ejs
SethTooSaucy Apr 29, 2024
4ff721c
Delete views/messages.ejs
SethTooSaucy Apr 29, 2024
3a53667
Delete controllers/messagesController.js
SethTooSaucy Apr 29, 2024
e860e6d
Delete routes/messagesRoutes.js
SethTooSaucy Apr 29, 2024
d3c9ab5
Update topicsRoutes.js
SethTooSaucy Apr 29, 2024
e36e511
Update testmongo.js
SethTooSaucy Apr 29, 2024
13e1d4d
subscribe feature hopefully
ActionIVU Apr 30, 2024
b92be3e
Update topicsController.js
SethTooSaucy Apr 30, 2024
c11215b
Update user.js
SethTooSaucy Apr 30, 2024
a2351e7
Update topics.ejs
SethTooSaucy Apr 30, 2024
5d51035
Update topicsRoutes.js
SethTooSaucy Apr 30, 2024
e6ea803
Update testmongo.js
SethTooSaucy Apr 30, 2024
a20ead6
Merge branch 'SethDev' of https://github.com/SethTooSaucy/MongoRender…
ActionIVU Apr 30, 2024
46a1187
sub
ActionIVU Apr 30, 2024
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
The table of contents is too big for display.
Diff view
Diff view
  •  
  •  
  •  
100 changes: 100 additions & 0 deletions controllers/authController.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
// authController.js

const path = require('path');
const { MongoClient } = require("mongodb");
const crypto = require('crypto');
const uri = "mongodb+srv://lillaundry:Antib7iotics!@sethcluster.lbpora8.mongodb.net/?retryWrites=true&w=majority&appName=SethCluster";

// Function to render the register form
function renderRegisterForm(req, res) {
res.sendFile(path.join(__dirname, '..', 'views', 'register.html'));
}

// Function to render the login form
function renderLoginForm(req, res) {
res.sendFile(path.join(__dirname, '..', 'views', 'login.html'));
}

// Function to handle user registration
async function registerUser(req, res) {
try {
// Extract user details from request body
const { user_ID, password } = req.body;

// Hash the password using custom hashing function
const hashedPassword = hashPassword(password);

// Connect to MongoDB
const client = new MongoClient(uri);
await client.connect();
const db = client.db('Sethdb'); // Change to your database name
const users = db.collection('users'); // Create a collection named 'users'

// Check if the user already exists
const existingUser = await users.findOne({ user_ID });
if (existingUser) {
return res.status(400).json({ error: 'User already exists' });
}

// Insert the new user into the database
await users.insertOne({ user_ID, password: hashedPassword });
await client.close();

// Redirect to homepage after successful registration
res.redirect('/');
} catch (error) {
console.error('Error registering user:', error);
res.status(500).json({ error: 'Internal Server Error' });
}
}

// Function to handle user login
async function loginUser(req, res) {
try {
// Extract user details from request body
const { user_ID, password } = req.body;

// Connect to MongoDB
const client = new MongoClient(uri);
await client.connect();
const db = client.db('Sethdb'); // Change to your database name
const users = db.collection('users'); // Create a collection named 'users'

// Find the user in the database
const user = await users.findOne({ user_ID });
if (!user) {
// User not found
return res.status(401).json({ error: 'Invalid credentials' });
}

// Hash the provided password and compare with the stored hashed password
const hashedPassword = hashPassword(password);
if (hashedPassword !== user.password) {
// Incorrect password
return res.status(401).json({ error: 'Invalid credentials' });
}

// Set cookie
res.cookie('authToken', user_ID, { httpOnly: true });

// Redirect to homepage after successful login
res.redirect('/');
} catch (error) {
console.error('Error logging in:', error);
res.status(500).json({ error: 'Internal Server Error' });
}
}

// Custom hashing function using SHA-256
function hashPassword(password) {
const hash = crypto.createHash('sha256');
hash.update(password);
return hash.digest('hex');
}

module.exports = {
renderRegisterForm,
renderLoginForm,
registerUser,
loginUser
};
164 changes: 164 additions & 0 deletions controllers/topicsController.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,164 @@
const { MongoClient, ObjectId } = require("mongodb");
const uri = "mongodb+srv://lillaundry:Antib7iotics!@sethcluster.lbpora8.mongodb.net/?retryWrites=true&w=majority&appName=SethCluster";

async function getAllTopicsWithMessages() {
try {
const client = new MongoClient(uri);
await client.connect();
const db = client.db('Sethdb');
const topics = db.collection('topics');

// Find all topics
const allTopics = await topics.find({}).toArray();

// Fetch messages for each topic
const topicsWithMessages = await Promise.all(allTopics.map(async topic => {
topic.messages = await getMessagesByTopicName(topic.name); // Corrected here
return topic;
}));

await client.close(); // Close the client connection

return topicsWithMessages;
} catch (error) {
console.error('Error fetching topics with messages:', error);
throw new Error('Internal Server Error');
}
}

async function getMessagesByTopicName(topicName) {
try {
const client = new MongoClient(uri);
await client.connect();
const db = client.db('Sethdb');
const topics = db.collection('topics');

// Find messages for the given topic name
const topic = await topics.findOne({ name: topicName });

await client.close(); // Close the client connection

return topic ? topic.messages : [];
} catch (error) {
console.error(`Error fetching messages for topic ${topicName}:`, error);
throw new Error('Internal Server Error');
}
}

async function createTopic(req, res) {
try {
// Extract topic details from request body
const { name, message } = req.body;

// Connect to MongoDB
const client = new MongoClient(uri);
await client.connect();
const db = client.db('Sethdb');
const topics = db.collection('topics');

// Check if topic with the given name already exists
const existingTopic = await topics.findOne({ name });

if (existingTopic) {
// Update existing topic by adding the new message
await topics.updateOne({ name }, { $push: { messages: message } });
} else {
// Create a new topic with the message
await topics.insertOne({ name, messages: [message] });
}

await client.close();

res.redirect('/topics');
} catch (error) {
console.error('Error creating topic:', error);
res.status(500).json({ error: 'Internal Server Error' });
}
}
async function subscribeToTopic(req, res) {
try {
const { topicName } = req.body;
const userId = req.cookies.authToken; // Assuming user ID is available in cookies

// Connect to MongoDB
const client = new MongoClient(uri);
await client.connect();
const db = client.db('Sethdb');
const topics = db.collection('topics');

// Find the topic by name
const topic = await topics.findOne({ name: topicName });

if (!topic) {
// Topic not found
return res.status(404).json({ error: 'Topic not found' });
}

// Check if the user is already subscribed to the topic
if (topic.subscribers.includes(userId)) {
return res.status(400).json({ error: 'User is already subscribed to this topic' });
}

// Add the user to the list of subscribers for the topic
await topics.updateOne(
{ name: topicName },
{ $push: { subscribers: userId } }
);

await client.close(); // Close the client connection

res.redirect('/topics');
} catch (error) {
console.error('Error subscribing to topic:', error);
res.status(500).json({ error: 'Internal Server Error' });
}
}

async function unsubscribeFromTopic(req, res) {
try {
const { topicName } = req.body;
const user_ID = req.cookies.authToken; // Assuming user ID is available in cookies

// Connect to MongoDB
const client = new MongoClient(uri);
await client.connect();
const db = client.db('Sethdb');
const users = db.collection('users');

// Find the user by ID
const user = await users.findOne({ user_ID });

if (!user) {
// User not found
return res.status(404).json({ error: 'User not found' });
}

// Remove the topic name from the user's subscribed topics array
user.subscribedTopics = user.subscribedTopics.filter(topic => topic !== topicName);

// Update the user document
await users.updateOne({ user_ID }, { $set: { subscribedTopics: user.subscribedTopics } });

await client.close(); // Close the client connection

res.redirect('/topics');
} catch (error) {
console.error('Error unsubscribing from topic:', error);
res.status(500).json({ error: 'Internal Server Error' });
}
}



module.exports = {
getAllTopicsWithMessages,
createTopic,
subscribeToTopic,
unsubscribeFromTopic,
};

module.exports = {
getAllTopicsWithMessages,
createTopic,
subscribeToTopic
};
14 changes: 14 additions & 0 deletions models/message.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
// models/Message.jss
const { Schema, model } = require('mongoose');

const messageSchema = new Schema({
content: { type: String, required: true },
userId: { type: Schema.Types.ObjectId, ref: 'User', required: true },
topicId: { type: Schema.Types.ObjectId, ref: 'Topic', required: true },
createdAt: { type: Date, default: Date.now },
updatedAt: { type: Date, default: Date.now }
});

const Message = model('Message', messageSchema);

module.exports = Message;
11 changes: 11 additions & 0 deletions models/topic.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
// models/Topic.js
const { Schema, model } = require('mongoose');

const topicSchema = new Schema({
name: { type: String, required: true, unique: true },
messages: [{ type: String, required: true }] // Define messages as an array of strings
});

const Topic = model('Topic', topicSchema);

module.exports = Topic;
13 changes: 13 additions & 0 deletions models/user.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
// models/User.js

const { Schema, model } = require('mongoose');

const userSchema = new Schema({
user_ID: { type: String, required: true, unique: true },
password: { type: String, required: true },
subscribedTopics: [{ type: Schema.Types.ObjectId, ref: 'Topic' }] // Array of subscribed topics
});

const User = model('User', userSchema);

module.exports = User;
1 change: 1 addition & 0 deletions node_modules/.bin/mime

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading