首页 > 解决方案 > 如何在 OTP 无效之前将其存储特定时间

问题描述

我正在为我的网站构建一个简单的内部 OTP 系统。我需要在我的函数中生成的值仅存储并仅在几分钟内有效。不知道如何更改返回值以使其过期的 OTP 无效。

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;
}

标签: javascript

解决方案


我找到了解决方案,这就是我为解决我的问题所做的工作。感谢@Tushar Shashi 和@apokryfos 的指导。

    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);
    }

推荐阅读