2

Whenever a user registers i am sending him an email which contains the link which user needs to click to get verified. I am passing a token in that link. When the user clicks the link he should get verified but i am not able to do this. I can just retrieve the token from the link but i am unable to find the user in the database and update the value.

Here is my code:

router.route('/verify')
.get(isNotAuthenticated, function(req, res){
var verifyToken = req.query.id;
var user =  User.findOne({ 'secretToken': verifyToken });


        if (!user) {
        req.flash('error', 'No user found with this email id, please check your email id or incorrect link');
        res.redirect('/users/register');
        return;
      }

      user.active = true;
      user.secretToken = '';
      user.save();

      req.flash('success', 'Thank you! Now you may login.');
      res.redirect('/users/login');
      res.redirect('login');
2

2 Answers 2

1

Try using promise to do this instead of assignment.

User.findOne({ 'secretToken': verifyToken })
.then(user => {
  // do something with user
})
.catch(err => {
  // do something with error
 })
Sign up to request clarification or add additional context in comments.

Comments

0

If you are using JWT to validate your routes you can:

1 - Generate the link verification with one "hash value"(token), save this token in the user document (user collection).

send the link e.g. "https://site/user/verify?token=3f0621f7e4c41ece51926a40cee4dae0be65ct7"

2 - Disable the security for this route:

app.use(jwt({secret: process.env.SECRET}).unless({path: ['/users/verify']})); 

3 - Receive the request to verify the user:

router.put('/verify', bodyParser.json(), function (req, res, next) {
  try {
    const user = userController.verify(req.query.token);
    res.status(200).json(user);
  } catch (err) {
    next(err);
  }
});

4 - Find and update the user(as verified):

User.findOneAndUpdate(
    {
      token: token,
    },{$set:{verified:true}})
    .then((result) => {
      return result;
    }).catch((err) => {
      //throw error
    });

If you need to wait the update for execute other sttufs, you can use async/wait: Async/Await Tutorial

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.