Skip to content

Commit

Permalink
protectRoute middleware
Browse files Browse the repository at this point in the history
  • Loading branch information
u0509421 committed Jan 10, 2025
1 parent 2384b9b commit 8a0b3e9
Show file tree
Hide file tree
Showing 65 changed files with 4,141 additions and 5 deletions.
2 changes: 1 addition & 1 deletion backend/controllers/auth.controller.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ export const signup = async (req, res) => {
const user = await User.findOne({ username });

if (user) {
return res.status(400).json({ message: "username already exists" });
return res.status(400).json({ error: "username already exists" });
}

// hash the password
Expand Down
38 changes: 37 additions & 1 deletion backend/controllers/message.controller.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,39 @@
import Consersation from "../models/conversation.model.js";
import Message from "../models/message.model.js";

export const sendMessage = async (req, res) => {
console.log("message sent", req.params.id);
try {
const { message } = req.body;
const { id: receiverId } = req.params;
const senderId = req.user._id;

let conversation = await Consersation.findOne({
participants: { $all: [senderId, receiverId] },
});

if (!conversation) {
conversation = await Consersation.create({
participants: [senderId, receiverId],
});
}

const newMessage = new Message({
senderId,
receiverId,
message,
});

if (newMessage) {
conversation.messages.push(newMessage._id);
}

// save conservation and new message to mongoDB
await conversation.save();
await newMessage.save();

res.status(201).json(newMessage);
} catch (error) {
console.log("error in sendMessage controller", error.message);
res.status(500).json({ error: "Internal server error" });
}
};
35 changes: 35 additions & 0 deletions backend/middleware/protectRoute.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
import jwt from "jsonwebtoken";
import User from "../models/user.model.js";

const protectRoute = async (req, res, next) => {
try {
const token = req.cookies.jwt;

if (!token) {
return res
.status(401)
.json({ error: "Unauthorized -- No Token Provided" });
}

const decoded = jwt.verify(token, process.env.JWT_SECRET);

if (!decoded) {
return res.status(401).json({ error: "Unauthorized -- Invalid Token" });
}

const user = await User.findById(decoded.userId).select("-password");

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

req.user = user;

next();
} catch (error) {
console.log("error in protectRoute middleware", error.message);
res.status(500).json({ error: "Internal server error" });
}
};

export default protectRoute;
3 changes: 2 additions & 1 deletion backend/routes/message.routes.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
import express from "express";
import { sendMessage } from "../controllers/message.controller.js";
import protectRoute from "../middleware/protectRoute.js";

const router = express.Router();

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

export default router;
3 changes: 3 additions & 0 deletions backend/server.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
// package imports
import express from "express";
import dotenv from "dotenv";
import cookieParser from "cookie-parser";

// file imports
import authRoutes from "./routes/auth.routes.js";
Expand All @@ -13,7 +14,9 @@ const PORT = process.env.PORT || 3000;
dotenv.config();

// middleware
app.use(cookieParser());
app.use(express.json()); // for parsing application/json (from req.body)

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

Expand Down
4 changes: 2 additions & 2 deletions backend/utils/generateToken.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import jwt from "jsonwebtoken";

const generateTokenAndSetCookie = (id, res) => {
const token = jwt.sign({ id }, process.env.JWT_SECRET, {
const generateTokenAndSetCookie = (userId, res) => {
const token = jwt.sign({ userId }, process.env.JWT_SECRET, {
expiresIn: "30d",
});

Expand Down
143 changes: 143 additions & 0 deletions node_modules/.package-lock.json

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

21 changes: 21 additions & 0 deletions node_modules/@types/body-parser/LICENSE

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

15 changes: 15 additions & 0 deletions node_modules/@types/body-parser/README.md

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

Loading

0 comments on commit 8a0b3e9

Please sign in to comment.