Skip to content

Commit

Permalink
added message sending
Browse files Browse the repository at this point in the history
  • Loading branch information
harikrishnan-git committed Dec 26, 2024
1 parent 4c262d5 commit 77201c5
Show file tree
Hide file tree
Showing 12 changed files with 231 additions and 39 deletions.
40 changes: 40 additions & 0 deletions backend/controllers/message.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
import mongoose from "mongoose";
import { Message } from "../models/message.model.js";
import { Conversation } from "../models/communication.model.js";

export const sendMsg = async (req, res) => {
try {
const { message } = req.body;
const senderId = req.params.id;
const recieverId = req.user._id;
const msg = new Message({
senderId,
recieverId,
message,
});
msg.save().then((res) => {
const conv = Conversation.findOne({
participants: { $all: [senderId, recieverId] },
});
if (!conv) {
const con = new Conversation({
participants: [senderId, recieverId],
message: [msg._id],
});
con
.save()
.then(() => {
console.log("Conversation created");
})
.catch((err) => {
console.log("problem while creating conversation");
});
} else {
conv.message.push(msg._id);
}
});
} catch (err) {
console.log("error in controller of sendMsg", err.message);
res.status(500).json({ error: "error while sending message" });
}
};
44 changes: 34 additions & 10 deletions backend/controllers/user.auth.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import bcrypt from "bcryptjs";
import { User } from "../models/user.auth.js";
import { generateTokensAndSetCookies } from "../utils/generate_token.js";

export const Signup = async (req, res) => {
try {
Expand All @@ -20,6 +21,7 @@ export const Signup = async (req, res) => {
const girlProfile = `https://avatar.iran.liara.run/public/girl?username=${userName}`;

const hash_password = await bcrypt.hash(password, 10);

const newUser = await new User({
fullName,
userName,
Expand All @@ -28,14 +30,25 @@ export const Signup = async (req, res) => {
profilePic: gender === "male" ? boyProfile : girlProfile,
});

newUser
.save()
.then((result) => {
res.redirect("/auth/login");
})
.catch((err) => {
console.log(err);
});
if (newUser) {
newUser
.save()
.then((result) => {
generateTokensAndSetCookies(newUser._id, res);
res.status(201).json({
_id: newUser._id,
fullName: newUser.fullName,
userName: newUser.userName,
gender: newUser.gender,
profilePic: newUser.profilePic,
});
})
.catch((err) => {
console.log(err);
});
} else {
res.status(500).json({ error: "Data invalid" });
}
} catch (err) {
console.log(err.message);
res.status(500).send({ error: "Internal server error" });
Expand All @@ -45,9 +58,9 @@ export const Signup = async (req, res) => {
export const Login = async (req, res) => {
try {
const { userName, password } = req.body;
const user = User.findOne({ userName });
const user = await User.findOne({ userName });
const isPassword = await bcrypt.compare(password, user.password || "");
if (!user && !isPassword) {
if (!user || !isPassword) {
res.status(400).json({ error: "Invalid username or password" });
console.log("Invalid password or username");
}
Expand All @@ -61,5 +74,16 @@ export const Login = async (req, res) => {
});
} catch (err) {
console.log(err);
res.status(500).json({ error: "Login internal error" });
}
};

export const Logout = async (req, res) => {
try {
res.cookie("jwt", "", { maxAge: 0 });
res.json("Logged out");
} catch (err) {
console.log(err);
res.status(500).json({ error: "Login internal error" });
}
};
10 changes: 7 additions & 3 deletions backend/index.js
Original file line number Diff line number Diff line change
@@ -1,19 +1,23 @@
import dotenv from "dotenv";
dotenv.config();
import express from "express";
import cookieParser from "cookie-parser";

import { router } from "./routes/user.auth.js";
import authrouter from "./routes/user.auth.js";
import msgRouter from "./routes/message.route.js";
import { authConn } from "./db/user.auth.js";

const app = express();
const PORT = process.env.PORT || 5000;

app.use(express.json());
app.use(cookieParser());

app.use("/auth", router);
app.use("/api/auth", authrouter);
app.use("/api/message", msgRouter);

app.listen(PORT, () => {
authConn();
console.log(`Listening to ${PORT}`);
app.use("/auth", router);
app.use("/api/auth", authrouter);
});
26 changes: 26 additions & 0 deletions backend/middleware/protectRoute.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import jwt from "jsonwebtoken";
import { User } from "../models/user.auth.js";

const protectRoute = async (req, res, next) => {
try {
const token = req.cookies.jwt;
if (!token) {
res.status(401).json({ error: "Unauthorized -> No token found" });
}
const decoded = jwt.verify(token, process.env.JWT_SECRET);
if (!decoded) {
res.status(401).json({ error: "Unauthorized->Invalid token" });
}
const user = await User.findById(decoded.userId).select("-password");
if (!user) {
res.status(404).json({ error: "user not found in login check" });
}
req.user = user;
next();
} catch (error) {
console.log("Problem in protectRoute", error.message);
res.status(500).json({ error: "Internal server error" });
}
};

export default protectRoute;
23 changes: 23 additions & 0 deletions backend/models/communication.model.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import mongoose from "mongoose";

const Schema = new mongoose.Schema(
{
participants: [
{
type: mongoose.Schema.Types.ObjectId,
ref: "User",
required: true,
},
],
messages: [
{
type: mongoose.Schema.Types.ObjectId,
ref: "Message",
default: [],
},
],
},
{ timestamps: true }
);

export const Conversation = mongoose.model("Conversation", Schema);
23 changes: 23 additions & 0 deletions backend/models/message.model.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import mongoose from "mongoose";

const Schema = new mongoose.Schema(
{
recieverId: {
type: mongoose.Schema.Types.ObjectId,
ref: "User",
required: true,
},
senderId: {
type: mongoose.Schema.Types.ObjectId,
ref: "User",
required: true,
},
message: {
type: String,
required: true,
},
},
{ timestamps: true }
);

export const Message = mongoose.model("Message", Schema);
51 changes: 27 additions & 24 deletions backend/models/user.auth.js
Original file line number Diff line number Diff line change
@@ -1,29 +1,32 @@
import mongoose from "mongoose";

const authSchema = mongoose.Schema({
fullName: {
type: String,
required: true,
const authSchema = mongoose.Schema(
{
fullName: {
type: String,
required: true,
},
userName: {
type: String,
required: true,
unique: true,
minLength: 3,
},
password: {
type: String,
required: true,
minLength: 4,
},
gender: {
type: String,
enum: ["male", "female"],
},
profilePic: {
type: "String",
default: "",
},
},
userName: {
type: String,
required: true,
unique: true,
minLength: 3,
},
password: {
type: String,
required: true,
minLength: 4,
},
gender: {
type: String,
enum: ["male", "female"],
},
profilePic: {
type: "String",
default: "",
},
});
{ timestamp: true }
);

export const User = mongoose.model("User", authSchema);
9 changes: 9 additions & 0 deletions backend/routes/message.route.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import express from "express";
import { sendMsg } from "../controllers/message.js";
import protectRoute from "../middleware/protectRoute.js";

const router = express.Router();

router.post("/send/:id", protectRoute, sendMsg);

export default router;
8 changes: 6 additions & 2 deletions backend/routes/user.auth.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,12 @@
import express from "express";
import { Signup, Login } from "../controllers/user.auth.js";
import { Signup, Login, Logout } from "../controllers/user.auth.js";

export const router = express.Router();
const router = express.Router();

router.post("/signup", Signup);

router.post("/login", Login);

router.post("/logout", Logout);

export default router;
14 changes: 14 additions & 0 deletions backend/utils/generate_token.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import jwt from "jsonwebtoken";

export const generateTokensAndSetCookies = (userId, res) => {
const token = jwt.sign({ userId }, process.env.JWT_SECRET, {
expiresIn: "15d",
});

res.cookie("jwt", token, {
maxAge: 15 * 24 * 60 * 60 * 1000,
sameSite: "strict",
httpOnly: true,
strict: process.env.NODE_ENV !== "development",
});
};
21 changes: 21 additions & 0 deletions package-lock.json

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

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
"license": "ISC",
"dependencies": {
"bcryptjs": "^2.4.3",
"cookie-parser": "^1.4.7",
"dotenv": "^16.4.7",
"express": "^4.21.2",
"jsonwebtoken": "^9.0.2",
Expand Down

0 comments on commit 77201c5

Please sign in to comment.