I am creating an Authentication System using with 2-Factor Authentication. Sending an OTP code to the user’s email and validating it.
The OTP is saved on my MongoDB using a Mongoose Schema, and it is supposed to expire after one hour. However, sometimes it gets deleted instantly for no reason, so the user has to request for another one.
I’ve already tried different approaches; deleted all the users, the DB, etc. But sometimes it’s still doing that.
How can I avoid that the OTP gets deleted before the right time?
Here you have the OTP Schema with the user’s reference to compare to the code that the user introduces.
import mongoose, {Schema, model} from 'mongoose'
import bcrypt from 'bcrypt'
const EmailVerificationTokenSchema = mongoose.Schema({
owner: {
type: mongoose.Schema.Types.ObjectId,
ref: "User",
required: true,
},
token: {
type: String,
required: true,
},
createdAt: {
type: Date,
expires: 3600,
default: Date.now(),
},
})
EmailVerificationTokenSchema.pre('save', async function(next) {
if (this.isModified('token')) {
this.token = await bcrypt.hash(this.token, 10)
}
next()
})
EmailVerificationTokenSchema.methods.compareToken = async function(token) {
const result = await bcrypt.compare(token, this.token)
return result
}
export default model('EmailVerificationToken', EmailVerificationTokenSchema)
Here I leave the URL of the project in production: Vite + React
Here is the github repo: GitHub - JaviKeziah/mern-milan.org