This content originally appeared on DEV Community and was authored by Sandeep
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)
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)
}
}
check on client side if token is expired then message token is expired.
This content originally appeared on DEV Community and was authored by Sandeep
Sandeep | Sciencx (2022-07-03T07:50:14+00:00) Create A Forget password link for one time and expire in 10 minutes in nodeJS. Retrieved from https://www.scien.cx/2022/07/03/create-a-forget-password-link-for-one-time-and-expire-in-10-minutes-in-nodejs/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.