Skip to content
Open
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
5 changes: 5 additions & 0 deletions .env
Original file line number Diff line number Diff line change
@@ -1 +1,6 @@

MONGODB_URL=""
PORT = 8000
JWT_SECRET=""
NODE_ENV=development

59 changes: 35 additions & 24 deletions backend/controllers/auth.controllers.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,50 +3,58 @@ import User from "../models/user.model.js";
import generateTokenAndSetCookie from "../utils/generateToken.js";

export const signup = async (req, res) => {

res.send("User registered successfully");

try {
const { fullName, username, password, confirmPassword, gender } = req.body;

if (!fullName || !username || !password || !confirmPassword || !gender) {
return res.status(400).json({ error: "All fields are required" });
}

if (!["male", "female"].includes(gender)) {
return res.status(400).json({ error: "Invalid gender value" });
}

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

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

if (user) {
const existingUser = await User.findOne({ username });
if (existingUser) {
return res.status(400).json({ error: "Username already exists" });
}

// HASH PASSWORD HERE
const salt = await bcrypt.genSalt(10);
const hashedPassword = await bcrypt.hash(password, salt);

// https://avatar-placeholder.iran.liara.run/

const boyProfilePic = `https://avatar.iran.liara.run/public/boy?username=${username}`;
const girlProfilePic = `https://avatar.iran.liara.run/public/girl?username=${username}`;
const profilePic =
gender === "male"
? `https://avatar.iran.liara.run/public/boy?username=${username}`
: `https://avatar.iran.liara.run/public/girl?username=${username}`;

const newUser = new User({
fullName,
username,
password: hashedPassword,
gender,
profilePic: gender === "male" ? boyProfilePic : girlProfilePic,
profilePic,
});

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" });
}
await newUser.save();

// Generate JWT Token
generateTokenAndSetCookie(newUser._id, res);



res.status(201).json({
_id: newUser._id,
fullName: newUser.fullName,
username: newUser.username,
profilePic: newUser.profilePic,
});
} catch (error) {
console.log("Error in signup controller", error.message);
res.status(500).json({ error: "Internal Server Error" });
Expand All @@ -55,8 +63,9 @@ export const signup = async (req, res) => {




export const login = async(req,res)=>{
// res.send("User registered successfully");

try{
const {username, password} = req.body;
const user = await User.findOne({username});
Expand All @@ -82,6 +91,8 @@ export const login = async(req,res)=>{
}

export const logout = (req,res)=>{
// res.send("User registered successfully");

try {
res.cookie("jwt", "", { maxAge: 0 });
res.status(200).json({ message: "Logged out successfully" });
Expand Down
17 changes: 13 additions & 4 deletions backend/server.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import cors from "cors";
import path from "path";
import express from "express";
import dotenv from "dotenv";
Expand All @@ -19,19 +20,27 @@ const PORT = process.env.PORT || 5000;

const __dirname = path.resolve();

app.use(express.json()); // For JSON request body parsing
app.use(express.urlencoded({ extended: true })); // Handles form data
app.use(cookieParser()); // Handles cookies

app.use(express.json()); // to parse the incoming requests with JSON payloads (from req.body)
app.use(cookieParser());

app.use("/api/auth", authRoutes);
app.use("/api/messages", messageRoutes);
app.use("/api/user", userRoutes)


app.use(express.static(path.join(__dirname, "/frontend/dist")));
app.use(cors({
origin: ["http://localhost:3000", "https://chat-application-ed5w.onrender.com"],
credentials: true, // Important if using cookies
}));



app.use(express.static(path.join(__dirname, "/public")));

app.get("*", (req, res) => {
res.sendFile(path.join(__dirname, "frontend", "dist", "index.html"));
res.sendFile(path.join(__dirname, "public", "index.html"));
});


Expand Down
9 changes: 5 additions & 4 deletions backend/socket/socket.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,13 @@ const app = express();

const server = http.createServer(app);
const io = new Server(server, {
cors: {
origin: ["http://localhost:8000"],
methods: ["GET", "POST"],
},
cors: {
origin: ["http://localhost:3000", "https://chat-application-ed5w.onrender.com"],
methods: ["GET", "POST"],
},
});


const userSocketMap = {}; // {userId: socketId}
export const getReceiverSocketId = (receiverId) => {
return userSocketMap[receiverId];
Expand Down
Loading