I am working on building a simple in house OTP system for my website. I need the value generated in my function to only be stored and valid for only a few minutes. Don’t know how to change the return value to make it render the expired OTP as invalid.
async function OTP() {
// Storing digits variable
var digits = '0123456789';
let OTP = '';
for (let i = 0; i < 6; i++ ) {
OTP += digits[Math.floor(Math.random() * 10)];
}
return OTP;
}
Advertisement
Answer
I found the solution, here is what I have done to solve my issue. Thanks @Tushar Shashi and @apokryfos for the guidance.
async function requestOtp(email: string): Promise<string> {
// Generate 6 Digit Otp
const newOtp = security.generateSecureOTP(6);
// Store OTP in firebase.
const newOtpDoc = new otp();
newOtpDoc.otp = newOtp;
await newOtpDoc.addToFirestore().catch(error => {
console.error(error);
throw new functions.https.HttpsError("aborted", "Failed to create OTP");
});
// Send 6 Digit OTP to Email
const emailText = "Your OTP for is <strong>" + newOtp + "</strong>. It will expire in 6 hours.";
await sendEmail(email, "OTP for ", emailText);
// Return Verification ID
return newOtpDoc.verificationId;
}
// Returns true/false if otp is correct or not.
async function verifyOtp(otpStr: string, verificationId: string): Promise<boolean> {
// Try to find verification code in firebase.
const otpRef = otpsCollection.doc(verificationId);
const otpDoc = await otpRef.get().catch(error => {
console.error(error);
throw new functions.https.HttpsError("aborted", "Failed to verify OTP.");
});
if (otpDoc.exists == false) {
console.error("Could not find OTP within database.");
throw new functions.https.HttpsError("aborted", "Failed to create OTP.");
}
const currentOtp = otp.fromJSON(otpDoc.data()!);
if (currentOtp.expires < admin.firestore.Timestamp.now()) {
throw new functions.https.HttpsError("aborted", "OTP has expired.");
}
return (currentOtp.otp == otpStr);
}