Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

signed up verify email bug corrected #338 and #345 done #425

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
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
67 changes: 20 additions & 47 deletions server/Controllers/auth.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,22 +6,27 @@ require('dotenv').config(); // Load environment variables from .env file

// Signup route
const createUser = async (req, res) => {
const VITE_CLIENT_PORT = process.env.VITE_CLIENT_PORT || "https://bitbox-in.netlify.app";
const VITE_CLIENT_PORT = process.env.VITE_CLIENT_PORT || "http://localhost:3000";


const { name, email, password } = req.body;


try {
const saltRounds = 10;

const hashedPassword = await bcrypt.hash(password, saltRounds);


const image = `https://api.dicebear.com/5.x/initials/svg?seed=${name}`;

// Create a new user (save in your database)

const user = new User({ image: image, name, email, password: hashedPassword, verified: false });
await user.save();

const verificationToken = crypto.randomBytes(32).toString("hex");
user.verificationToken = verificationToken;
await user.save();


const transporter = nodemailer.createTransport({
service: "gmail",
Expand All @@ -31,14 +36,17 @@ const createUser = async (req, res) => {
},
});

const verificationLink = `${VITE_CLIENT_PORT}/verify/${verificationToken}`;

const verificationLink = `http://localhost:5000/api/auth/verify/${verificationToken}`;

const mailOptions = {
from: process.env.EMAIL_USER,
to: email,
subject: "Email Verification",
text: `Click this link to verify your email: ${verificationLink}`,
};


transporter.sendMail(mailOptions, (error, info) => {
if (error) {
console.error("Error sending email:", error);
Expand All @@ -47,56 +55,21 @@ const createUser = async (req, res) => {
message: `Error sending verification email: ${error.message}`,
});
}


if (!user.verified) {
return res.status(401).json({ success: false, message: "Signup successful! Please check your email for the verification link." });
return res.status(200).json({
success: true,
message: "Signup successful! Please check your email for the verification link.",
});
}
});
} catch (error) {
console.error("An error occurred during signup:", error);
res.status(500).json({ success: false, message: 'An error occurred during signup' });
}
};

const verifyToken = async (req, res) => {
const { token } = req.params;

try {
const VITE_CLIENT_PORT = process.env.VITE_CLIENT_PORT || "https://bitbox-in.netlify.app";

const user = await User.findOne({ verificationToken: token });
if (!user) {
return res.status(400).json({
success: false,
message: "Invalid or expired verification link",
});
}

user.verified = true;
user.verificationToken = token;
await user.save();

if (user) {
return res.status(200).json({
success: true,
message: "Email verified successfully",
});
}

res.status(200).json({
success: true,
message: "Signup successfully",
});

// Redirect to the frontend's home page after verification
return res.redirect(`${VITE_CLIENT_PORT}/login`);
} catch (err) {
console.error(err);
return res.status(500).json({
success: false,
message: "Server error. Please try again later.",
});
}
};

async function ResetPasswordByEmail(req, res) {

const VITE_CLIENT_PORT = process.env.VITE_CLIENT_PORT || "https://bitbox-in.netlify.app";
Expand Down Expand Up @@ -174,9 +147,9 @@ const forgetpassword = async (req, res) => {
}
};


module.exports = {
forgetpassword,
createUser,
verifyToken,
ResetPasswordByEmail,
};
65 changes: 58 additions & 7 deletions server/routes/auth.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ require('dotenv').config(); // Load environment variables from .env file

const {
forgetpassword,
verifyToken,

createUser,
ResetPasswordByEmail,
} = require("../Controllers/auth");
Expand Down Expand Up @@ -96,7 +96,7 @@ router.post(
// Check for validation errors
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(400).json({ errors: errors.array() });
return res.status(400).json({ success, errors: errors.array() });
}

const { email, password } = req.body;
Expand All @@ -113,6 +113,15 @@ router.post(
});
}

// Check if the user is verified
if (!user.verified) {
// Return failure message if email is not verified
return res.status(403).json({
success,
error: "Email not verified. Please verify your email to activate your account.",
});
}

// Compare provided password with stored password
const passwordCompare = await bcrypt.compare(password, user.password);

Expand All @@ -133,16 +142,21 @@ router.post(
// Sign the JWT
const authtoken = jwt.sign(data, JWT_SECRET);

// Send token in response to be stored in localStorage on the client
return res.status(200).json({ success: true, authtoken });
// Send success response with token
success = true;
return res.status(200).json({ success, authtoken });
} catch (error) {
console.error(error.message);
return res.status(500).send("Internal Server Error");
return res.status(500).json({
success: false,
error: "Internal Server Error",
});
}
}
);



// ROUTE 3 : Get Loggedin User Details : GET: "/api/auth/getuser". Login required
router.get("/getuser", fetchuser, async (req, res) => {
try {
Expand All @@ -157,9 +171,46 @@ router.get("/getuser", fetchuser, async (req, res) => {
}
});

// In your auth.js route file
router.get("/verify/:token", async (req, res) => {
const { token } = req.params;
try {
// Find the user based on the verification token
const user = await User.findOne({ verificationToken: token });

if (!user) {
// If the user is not found or token is invalid, show an error
return res.status(404).send(`
<h2>Invalid or expired verification link</h2>
<p>Please try registering again or contact support.</p>
`);
}

if (user.verified) {
// If the user is already verified, redirect them to login
return res.redirect('http://localhost:5173/login');
}

// Update the user as verified and clear the verification token
user.verified = true;
user.verificationToken = undefined;
await user.save();

// Redirect the user to the login page after successful verification
return res.redirect('http://localhost:5173/login');

} catch (error) {

res.status(500).send(`
<h2>Verification failed</h2>
<p>An error occurred. Please try again later or contact support.</p>
`);
}
});


router.post("/forget", forgetpassword);
router.post("/createUser", createUser);
router.post("/verify/:token", verifyToken);
router.post("/createuser", createUser);
router.post("/ResetByEmail", ResetPasswordByEmail);

module.exports = router;
Loading