Skip to content

Commit

Permalink
Completely new files form scratch
Browse files Browse the repository at this point in the history
  • Loading branch information
rebeljelly2147 committed Feb 4, 2025
1 parent 2deb762 commit 988a87c
Show file tree
Hide file tree
Showing 70 changed files with 3,418 additions and 4,342 deletions.
176 changes: 78 additions & 98 deletions backend/controllers/auth.controller.js
Original file line number Diff line number Diff line change
@@ -1,108 +1,88 @@
import User from '../models/user.model.js';
import bcrypt from 'bcryptjs';
import generateTokenAndSetCookie from '../utils/generateToken.js';
import bcrypt from "bcryptjs";
import User from "../models/user.model.js";
import generateTokenAndSetCookie from "../utils/generateToken.js";

export const signup = async(req, res) => {
// res.send('Signup Route');
// console.log('Signup Route');
try {
const {fullname, username, password, confirmPassword, gender } = req.body;
// if(!fullname || !username || !password || !confirmPassword || !gender) {
// return res.status(400).json({message: "All fields are required"});
// }
export const signup = async (req, res) => {
try {
const { fullName, username, password, confirmPassword, gender } = req.body;

if(password !== confirmPassword) {
return res.status(400).json({message: "Password and Confirm Password do not match"});
}
if (password !== confirmPassword) {
return res.status(400).json({ error: "Passwords don't match" });
}

const user = await User.findOne({username});
const user = await User.findOne({ username });

if (user) {
console.log("User already exists");
return res.status(400).json({error: "User already exists"});
}
if (user) {
return res.status(400).json({ error: "Username already exists" });
}

// Hashed password here
const salt = await bcrypt.genSalt(12); // 12 is the salt round, higher the number more secure the password but it will take more time to hash the password
const hasedPassword = await bcrypt.hash(password,salt);
// HASH PASSWORD HERE
const salt = await bcrypt.genSalt(10);
const hashedPassword = await bcrypt.hash(password, salt);

// Profile Picture
const boyProfilePic = `https://avatar.iran.liara.run/public/boy?name=${username}`;
const girlProfilePic = `https://avatar.iran.liara.run/public/girl?name=${username}`;
// https://avatar-placeholder.iran.liara.run/

const newUser = new User({
fullname,
username,
password: hasedPassword, //now hashed password is stored in the database
gender,
profilePic: gender === "male" ? boyProfilePic : girlProfilePic // ternary operator is used to set the profilePic field based on the gender
});
const boyProfilePic = `https://avatar.iran.liara.run/public/boy?username=${username}`;
const girlProfilePic = `https://avatar.iran.liara.run/public/girl?username=${username}`;

if(newUser){
// Generate JWT token
await generateTokenAndSetCookie(newUser._id, res);
await newUser.save();
res.status(201).json({
message: "User created successfully",
user: {
_id : newUser._id,
fullname: newUser.fullname,
username: newUser.username,
gender: newUser.gender,
profilePic: newUser.profilePic
}
});
}
else {
console.log("Invalid user data");
res.status(400).json({message: "Invalid user data"});
}
}
catch (error) {
console.log("Error in signup controller : ",error.message);
res.status(500).json({message: "Internal Server Error During Signup"});
}
}
export const login = async(req, res) => {
// res.send('Login Route');
// console.log('Login Route');
try {
const {username, password} = req.body; //destructuring username and password from req.body
const user = await User.findOne({username}); //find user by username
const isPasswordCorrect = await bcrypt.compare(password, user?.password || ""); // check if password is correct and if user is null then password is set to empty string and user?.password is used to avoid error
const newUser = new User({
fullName,
username,
password: hashedPassword,
gender,
profilePic: gender === "male" ? boyProfilePic : girlProfilePic,
});

if (newUser) {
// Generate JWT token here
generateTokenAndSetCookie(newUser._id, res);
await newUser.save();

res.status(201).json({
_id: newUser._id,
fullName: newUser.fullName,
username: newUser.username,
profilePic: newUser.profilePic,
});
} else {
res.status(400).json({ error: "Invalid user data" });
}
} catch (error) {
console.log("Error in signup controller", error.message);
res.status(500).json({ error: "Internal Server Error" });
}
};

export const login = async (req, res) => {
try {
const { username, password } = req.body;
const user = await User.findOne({ username });
const isPasswordCorrect = await bcrypt.compare(password, user?.password || "");

if (!user || !isPasswordCorrect) {
return res.status(400).json({ error: "Invalid username or password" });
}

generateTokenAndSetCookie(user._id, res);

res.status(200).json({
_id: user._id,
fullName: user.fullName,
username: user.username,
profilePic: user.profilePic,
});
} catch (error) {
console.log("Error in login controller", error.message);
res.status(500).json({ error: "Internal Server Error" });
}
};

if(!user || !isPasswordCorrect) { // if user is null or password is incorrect
return res.status(400).json({message: "Invalid username or password"});
}
if(!username || !password) { // if username or password is empty
return res.status(400).json({message: "All fields are required"});
}

// Now we will Generate JWT token and set cooki e
await generateTokenAndSetCookie(user._id, res);
res.status(200).json({
message: "User logged in successfully",
user: {
_id : user._id,
fullname: user.fullname,
username: user.username,
gender: user.gender,
profilePic: user.profilePic
}
});
} catch (error) {
console.log("Error in login controller : ",error.message);
res.status(500).json({message: "Internal Server Error During Login"});
}
}
export const logout = (req, res) => {
// res.send('Logout Route');
// console.log('Logout Route');
try {
res.cookie("jwt", "", {maxAge: 1}); // set the jwt cookie to empty string and maxAge to 1 millisecond
res.status(200).json({message: "User logged out successfully"});
} catch (error) {
console.log("Error in logout controller : ",error.message);
res.status(500).json({message: "Internal Server Error During Logout"});
}
}
try {
res.cookie("jwt", "", { maxAge: 0 });
res.status(200).json({ message: "Logged out successfully" });
} catch (error) {
console.log("Error in logout controller", error.message);
res.status(500).json({ error: "Internal Server Error" });
}
};
105 changes: 55 additions & 50 deletions backend/controllers/message.controller.js
Original file line number Diff line number Diff line change
@@ -1,64 +1,69 @@
import Conversation from "../models/conversation.model.js"; // .js is mandatory for proper working of ES6 modules
import Message from "../models/message.model.js"; // Add this line
import Conversation from "../models/conversation.model.js";
import Message from "../models/message.model.js";
import { getReceiverSocketId, io } from "../socket/socket.js";

export const sendMessage = async (req, res) => {
// res.send('Send Message Route');
// console.log('Message sent by userId', req.params.id);
try {
const {message} = req.body;
const {id: recieverId} = req.params;
const senderId = req.user._id; // because we used protectRoute middleware in the route
// console.log('Message sent by userId', senderId);
try {
const { message } = req.body;
const { id: receiverId } = req.params;
const senderId = req.user._id;

let conversation = await Conversation.findOne({
participants: {$all: [senderId, recieverId]} // participants array contains senderId and recieverId $all is used to check if both are present
}); // this will find the conversation between sender and reciever
let conversation = await Conversation.findOne({
participants: { $all: [senderId, receiverId] },
});

if(!conversation) {
conversation = await Conversation.create({
participants: [senderId, recieverId]
});
}; // this will create a new conversation if it does not exist
if (!conversation) {
conversation = await Conversation.create({
participants: [senderId, receiverId],
});
}

const newMessage = new Message({
senderId, //: senderId,
recieverId, //: recieverId,
message
}// this will create a new message
);
const newMessage = new Message({
senderId,
receiverId,
message,
});


if(newMessage){
conversation.messages.push(newMessage._id);
}// this will push the new message to the conversation messages array

await Promise.all([newMessage.save(), conversation.save()]); // Save operations in parallel
if (newMessage) {
conversation.messages.push(newMessage._id);
}

res.status(201).json({newMessage, conversation}); // this will send the new message and the conversation as response
// await conversation.save();
// await newMessage.save();

} catch (error) {
console.log("Error in sendMessages controller : ",error.message);
res.status(500).json({message: "Internal Server Error During Sending Message"});
}
// this will run in parallel
await Promise.all([conversation.save(), newMessage.save()]);

// SOCKET IO FUNCTIONALITY WILL GO HERE
const receiverSocketId = getReceiverSocketId(receiverId);
if (receiverSocketId) {
// io.to(<socket_id>).emit() used to send events to specific client
io.to(receiverSocketId).emit("newMessage", newMessage);
}

res.status(201).json(newMessage);
} catch (error) {
console.log("Error in sendMessage controller: ", error.message);
res.status(500).json({ error: "Internal server error" });
}
};

export const getMessages = async (req, res) => {
try {
const {id: userToChatId} = req.params;
const senderId = req.user._id; // because we used protectRoute middleware in the route
const conversation = await Conversation.findOne({
participants: {$all: [senderId, userToChatId]}
}).populate("messages"); // this will find the conversation between sender and reciever and populate the messages array
try {
const { id: userToChatId } = req.params;
const senderId = req.user._id;

if(!conversation) {
return res.status(404).json({message: "No Messages Found"});
} // if no conversation is found then it will send a 404 status code with message
const conversation = await Conversation.findOne({
participants: { $all: [senderId, userToChatId] },
}).populate("messages"); // NOT REFERENCE BUT ACTUAL MESSAGES

res.status(200).json(conversation.messages); // this will send the messages array as response
if (!conversation) return res.status(200).json([]);

} catch (error) {
console.log("Error in getMessages controller : ",error.message);
res.status(500).json({message: "Internal Server Error During Getting Messages"});

}
};
const messages = conversation.messages;

res.status(200).json(messages);
} catch (error) {
console.log("Error in getMessages controller: ", error.message);
res.status(500).json({ error: "Internal server error" });
}
};
19 changes: 10 additions & 9 deletions backend/controllers/user.controller.js
Original file line number Diff line number Diff line change
@@ -1,13 +1,14 @@
import User from "../models/user.model.js";

export const getUsersForSidebar = async (req, res) => {
try {
const loggedInUserId = req.user._id;
try {
const loggedInUserId = req.user._id;

const filteredUsers = await User.find({ _id: { $ne: loggedInUserId } }).select('-password');// $ne means not equal to loggedInUserId and select is used to select only the required fields from the document
const filteredUsers = await User.find({ _id: { $ne: loggedInUserId } }).select("-password");

res.status(200).json(filteredUsers); // this will send the filteredUsers as response
} catch (error) {
console.error("Error in getUsersForSidebar controller : ",error.message);
res.status(500).json({message: "Internal Server Error During Getting Users From Sidebar"});
}
};
res.status(200).json(filteredUsers);
} catch (error) {
console.error("Error in getUsersForSidebar: ", error.message);
res.status(500).json({ error: "Internal server error" });
}
};
19 changes: 8 additions & 11 deletions backend/db/connectToMongodb.js
Original file line number Diff line number Diff line change
@@ -1,15 +1,12 @@
import mongoose from "mongoose";
import dotenv from "dotenv";

dotenv.config();

const connectToMongodb = async () => {
try {
await mongoose.connect(process.env.MONGO_DB_URI);
console.log("Connected to MongoDB");
} catch (error) {
console.error("Error connecting to MongoDB:", error.message);
}
const connectToMongoDB = async () => {
try {
await mongoose.connect(process.env.MONGO_DB_URI);
console.log("Connected to MongoDB");
} catch (error) {
console.log("Error connecting to MongoDB", error.message);
}
};

export default connectToMongodb;
export default connectToMongoDB;
Loading

0 comments on commit 988a87c

Please sign in to comment.