DEV Community

Cover image for Create A Forget password link for one time and expire in 10 minutes in nodeJS
Deepak Jaiswal
Deepak Jaiswal

Posted on

6 4 1 1 1

Create A Forget password link for one time and expire in 10 minutes in nodeJS

here create forget password link with json web token (jwt) to create expire token in 10 minutes.

but in token not make it for one time so store in database after successfully OTP verify i have remove from database.

in mongoose model i add a field name otp has number and expire field in 10 minutes.

user.model.js

const mongoose = require("mongoose")

const userSchema = new mongoose.Schema({
    name:{
        type:String,
        required:true,
        trim:true
    },
        email:{
                type:String,
                required:true
        },
    otp:{
        type:Number,
        expires:'10m',
                index:true
    },
    imageUrl:{
        type:String,
        default:'avatar.png'
    }
})

module.exports = mongoose.model('User',userSchema)
Enter fullscreen mode Exit fullscreen mode

user.controller.js

module.exports.forgetPassword =async (req,res,next)=>{
     try{

    const {email} = req.body

        User.findOne({email}).exec(function(err,user){
                if(err) throw err;
                if(!user){
                    res.json({"error":"User not 
                                      found"})
                }
                else{
                let otp=Math.random().toString(5);
                              user=await User.findOneAndUpdate({
                                   _id:user._id},
                               {$set :{otp}},{new:true});    
     const  {_id,email} = user;
     let  token=jwt.sign({_id,email,tokenId:uuidv4()},"SECRET_TOKEN",{expiresIn: '10m' });
     let url=HOST_URL+token;
     await sendMail(email,"forget password link",url,`your otp is ${user.otp}`);                 
     res.status(200).send({message:"send link to your mail"});


        }
    }
   }catch(err){
    next(err)
  }
}

module.exports.verifyOtp =async (req,res,next)=>{

   try{
        //email get from token
         const {email,otp}=req.body;
        User.findOne({email,otp}).exec(function(err,user){
                if(err) throw err
                if(!user){
                    res.json({"error":"Link is Expired"})
                }
                else{
await User.updateOne({_id:user._id},{$set:{otp:null}});
                            const token=jwt.sign({_id:user._id,tokenId:uuidv4()},"SECRET_TOKEN")
                            res.header("token",token).json({message:"otp verification success"})

        }
    }
    }catch(err){
    next(err)
  }
}
Enter fullscreen mode Exit fullscreen mode

check on client side if token is expired then message token is expired.

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay