Skip to content

Commit

Permalink
configured user route to hanlde user choice route
Browse files Browse the repository at this point in the history
  • Loading branch information
abhiraj-ku committed Aug 30, 2024
1 parent d373510 commit e21ace0
Show file tree
Hide file tree
Showing 5 changed files with 68 additions and 22 deletions.
Empty file removed controllers/groupChoice.js
Empty file.
42 changes: 42 additions & 0 deletions controllers/userController.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ const bcrypt = require("bcryptjs");
const { storeuser, verifyCode } = require("../services/emailServices");
const { verifyEmail, verifyPhone } = require("../utils/isContactsValid");
const cookieToken = require("../utils/cookieToken");
const { validateUsersChoice } = require("../helpers/validateUserChoice");

// Register a new user
module.exports.register = async (req, res) => {
Expand Down Expand Up @@ -67,8 +68,11 @@ module.exports.register = async (req, res) => {

password = undefined;

const token = await user.createJwtToken();

res.status(200).json({
message: "User created successfully",
token,
user,
});
} catch (error) {
Expand Down Expand Up @@ -222,3 +226,41 @@ exports.resendVerificationEmail = async (req, res) => {
// TODO: Implement the update password route

// TODO: Implement the reset token route

// Take user's choice to create group or join group

module.exports.handleUserChoice = async (req, res) => {
const { choice } = req.body;

try {
const validOptions = ["create", "join"];
const validation = validateUsersChoice(choice, validOptions);

if (!validation.isValid) {
return res.status(400).json({
message: validation.message,
});
}

const userID = req.user.userID;
if (!userID) {
return res.status(401).json({ message: "User not authenticated." });
}
switch (choice) {
case "create":
return createGroup(req, res);
case "join":
return joinGroup(req, res);

default:
return res.status(400).json({
message: `Invalid user choice`,
});
}
} catch (error) {
return res.status(500).json({
message:
"Server error while handling user choice. Please try again later.",
});
}
};
37 changes: 23 additions & 14 deletions middlewares/authMiddleware.js
Original file line number Diff line number Diff line change
@@ -1,23 +1,32 @@
const JWT = require("jsonwebtoken");
const User = require("../models/userModel");

const jwtsecret = process.env.JWT_SECRET;
if (!jwtsecret) {
throw new Error("Missing JWt token from env variable");
throw new Error("Missing JWT token from env variable");
}

const isAuthorized = async (req, res, next) => {
const authHeader = req.headers.authorization;
if (!authHeader || !authHeader.startsWith("Bearer")) {
next("Authentication Failed");
}
const token = authHeader.split(" ")[1];
module.exports.isAuthorized = async (req, res, next) => {
try {
const payload = JWT.verify(token, jwtsecret);
req.user = { userId: payload.userId };
next();
const token =
req.cookie.token ||
(req.headers.authorization || "").replace("Bearer", "");

// Verify if token is present or not
if (!token) {
console.log(`Missing header token`);
throw new Error(`No token found , please login to generate`);
}

// verify the jwt token from cookie
const decodeToken = JWT.verify(token, jwtsecret);

// find and attach user object to the decoded user
req.user = await User.findById(decodeToken.id);

return next();
} catch (error) {
return next(new Error("Auth failed"));
console.log(`Error while verifying token`);

return next(error);
}
};

module.exports = isAuthorized;
8 changes: 0 additions & 8 deletions routes/userRedirect.js

This file was deleted.

3 changes: 3 additions & 0 deletions routes/userRoute.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ const {
verifyCode,
login,
logout,
handleUserChoice,
} = require("../controllers/userController");

router.post("/register", register);
Expand All @@ -15,4 +16,6 @@ router.post("/verify-mail", verifyCode);
router.post("/logout", logout);
router.post("/resend-verification", limitRoute, verifyCode);

router.post("/choice", auth, handleUserChoice);

module.exports = router;

0 comments on commit e21ace0

Please sign in to comment.