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

5 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.

Heroku

This site is built on Heroku

Join the ranks of developers at Salesforce, Airbase, DEV, and more who deploy their mission critical applications on Heroku. Sign up today and launch your first app!

Get Started

Top comments (0)

Cloudinary image

Optimize, customize, deliver, manage and analyze your images.

Remove background in all your web images at the same time, use outpainting to expand images with matching content, remove objects via open-set object detection and fill, recolor, crop, resize... Discover these and hundreds more ways to manage your web images and videos on a scale.

Learn more

👋 Kindness is contagious

Dive into an ocean of knowledge with this thought-provoking post, revered deeply within the supportive DEV Community. Developers of all levels are welcome to join and enhance our collective intelligence.

Saying a simple "thank you" can brighten someone's day. Share your gratitude in the comments below!

On DEV, sharing ideas eases our path and fortifies our community connections. Found this helpful? Sending a quick thanks to the author can be profoundly valued.

Okay