OiO.lk Community platform!

Oio.lk is an excellent forum for developers, providing a wide range of resources, discussions, and support for those in the developer community. Join oio.lk today to connect with like-minded professionals, share insights, and stay updated on the latest trends and technologies in the development field.
  You need to log in or register to access the solved answers to this problem.
  • You have reached the maximum number of guest views allowed
  • Please register below to remove this limitation

Cannot GET /verify-email/:token Error in Email Verification Process

  • Thread starter Thread starter user20880929
  • Start date Start date
U

user20880929

Guest
I am in the process of implementing an email verification system in the web application I am developing in Node. js , Express, and React. Everything is working as intended but the database value "verified" does not get set to true after the user clicks on the link.

//routes/user.js:

Code:
// routes/user.js
const express = require("express");
const router = express.Router();
const {
  login,
  register,
  dashboard,
  getAllUsers,
} = require("../controllers/user");
const {
  createPost,
  getPostDetails,
  getAllPosts,
} = require("../controllers/post");
const authMiddleware = require("../middleware/auth");
const { verifyEmail } = require("../controllers/user");

router.post("/register", register);
router.post("/login", login);
router.get("/dashboard", authMiddleware, dashboard);
router.get("/allusers", getAllUsers);
router.get("/verify-email/:token", verifyEmail);

router.post("/posts", authMiddleware, createPost);
router.get("/posts/:id", authMiddleware, getPostDetails);
router.get("/posts", authMiddleware, getAllPosts);

module.exports = router;

//controllers/user.js:

Code:
const login = async (req, res) => {
  const { email, password } = req.body;
  if (!email || !password) {
    return res.status(400).json({
      msg: "Bad request. Please add email and password in the request body",
    });
  }

  try {
    let foundUser = await User.findOne({ email: req.body.email });
    if (foundUser) {
      const isMatch = await foundUser.comparePassword(password);
      if (isMatch) {
        if (!foundUser.verified) {
          return res
            .status(401)
            .json({ msg: "Please verify your email before logging in" });
        }
        const token = jwt.sign({ id: foundUser._id }, process.env.JWT_SECRET, {
          expiresIn: "30d",
        });
        return res.status(200).json({ msg: "User logged in", token });
      } else {
        return res.status(400).json({ msg: "Bad password" });
      }
    } else {
      return res.status(400).json({ msg: "Username not found" });
    }
  } catch (error) {
    console.error(error);
    return res.status(500).json({ msg: "Server error" });
  }
};

const dashboard = async (req, res) => {
  try {
    const { _id, name, email, avatar } = req.user;
    res.status(200).json({
      user: {
        id: _id,
        name,
        email,
      },
    });
  } catch (error) {
    console.error(error);
    return res.status(500).json({ msg: "Server error" });
  }
};

const getAllUsers = async (req, res) => {
  let users = await User.find({});
  return res.status(200).json({ users });
};

const register = async (req, res) => {
  try {
    let foundUser = await User.findOne({ email: req.body.email });
    if (foundUser === null) {
      let { username, email, password } = req.body;
      if (username.length && email.length && password.length) {
        const person = new User({
          name: username,
          email: email,
          password: password,
          verified: false,
        });
        await person.save();

        const verificationToken = generateEmailVerificationToken(person._id);
        await sendVerificationEmail(email, verificationToken);

        return res.status(201).json({
          msg: "Registration successful. Please check your email to verify your account.",
        });
      } else {
        return res
          .status(400)
          .json({ msg: "Please add all values in the request body" });
      }
    } else {
      return res.status(400).json({ msg: "Email already in use" });
    }
  } catch (error) {
    console.error(error);
    return res.status(500).json({ msg: "Server error" });
  }
};

const verifyEmail = async (req, res) => {
  try {
    const { token } = req.params;
    const decoded = jwt.verify(token, process.env.JWT_SECRET);
    const user = await User.findById(decoded.userId);

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

    if (user.verified) {
      return res.status(400).json({ msg: "Email already verified" });
    }

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

    return res.status(200).json({ msg: "Email verified successfully" });
  } catch (error) {
    console.error(error);
    return res.status(400).json({ msg: "Invalid or expired token" });
  }
};

<p>I am in the process of implementing an email verification system in the web application I am developing in Node. js , Express, and React. Everything is working as intended but the database value "verified" does not get set to true after the user clicks on the link.</p>
<p>//routes/user.js:</p>
<pre><code>// routes/user.js
const express = require("express");
const router = express.Router();
const {
login,
register,
dashboard,
getAllUsers,
} = require("../controllers/user");
const {
createPost,
getPostDetails,
getAllPosts,
} = require("../controllers/post");
const authMiddleware = require("../middleware/auth");
const { verifyEmail } = require("../controllers/user");

router.post("/register", register);
router.post("/login", login);
router.get("/dashboard", authMiddleware, dashboard);
router.get("/allusers", getAllUsers);
router.get("/verify-email/:token", verifyEmail);

router.post("/posts", authMiddleware, createPost);
router.get("/posts/:id", authMiddleware, getPostDetails);
router.get("/posts", authMiddleware, getAllPosts);

module.exports = router;
</code></pre>
<p>//controllers/user.js:</p>
<pre><code>const login = async (req, res) => {
const { email, password } = req.body;
if (!email || !password) {
return res.status(400).json({
msg: "Bad request. Please add email and password in the request body",
});
}

try {
let foundUser = await User.findOne({ email: req.body.email });
if (foundUser) {
const isMatch = await foundUser.comparePassword(password);
if (isMatch) {
if (!foundUser.verified) {
return res
.status(401)
.json({ msg: "Please verify your email before logging in" });
}
const token = jwt.sign({ id: foundUser._id }, process.env.JWT_SECRET, {
expiresIn: "30d",
});
return res.status(200).json({ msg: "User logged in", token });
} else {
return res.status(400).json({ msg: "Bad password" });
}
} else {
return res.status(400).json({ msg: "Username not found" });
}
} catch (error) {
console.error(error);
return res.status(500).json({ msg: "Server error" });
}
};

const dashboard = async (req, res) => {
try {
const { _id, name, email, avatar } = req.user;
res.status(200).json({
user: {
id: _id,
name,
email,
},
});
} catch (error) {
console.error(error);
return res.status(500).json({ msg: "Server error" });
}
};

const getAllUsers = async (req, res) => {
let users = await User.find({});
return res.status(200).json({ users });
};

const register = async (req, res) => {
try {
let foundUser = await User.findOne({ email: req.body.email });
if (foundUser === null) {
let { username, email, password } = req.body;
if (username.length && email.length && password.length) {
const person = new User({
name: username,
email: email,
password: password,
verified: false,
});
await person.save();

const verificationToken = generateEmailVerificationToken(person._id);
await sendVerificationEmail(email, verificationToken);

return res.status(201).json({
msg: "Registration successful. Please check your email to verify your account.",
});
} else {
return res
.status(400)
.json({ msg: "Please add all values in the request body" });
}
} else {
return res.status(400).json({ msg: "Email already in use" });
}
} catch (error) {
console.error(error);
return res.status(500).json({ msg: "Server error" });
}
};

const verifyEmail = async (req, res) => {
try {
const { token } = req.params;
const decoded = jwt.verify(token, process.env.JWT_SECRET);
const user = await User.findById(decoded.userId);

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

if (user.verified) {
return res.status(400).json({ msg: "Email already verified" });
}

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

return res.status(200).json({ msg: "Email verified successfully" });
} catch (error) {
console.error(error);
return res.status(400).json({ msg: "Invalid or expired token" });
}
};

</code></pre>
 

Latest posts

Top