javascript - 如何在 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;
}
解决方案
我找到了解决方案,这就是我为解决我的问题所做的工作。感谢@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);
}
推荐阅读
- ios - .xcodeproj 文件在 Xcode 中显示为红色是什么意思?
- c# - 应用程序中的数据库验证
- html - 添加/删除组件时某些 div 的 Flexbox 对齐“问题”
- php - 此代码对于最小和最大 int 是否足够安全
- javascript - 使用 const 在 puppeteer 测试中导入定位器
- angular - PrimeNG AutoComplete:选择特定条目后重新运行搜索
- node.js - 尝试使用 PUT 将 PDF 作为 blob 上传到 S3 存储桶时出现 403 禁止
- kubernetes - 如何将多个前缀路由到 istio 中的同一路由?
- visual-studio-code - VS Code 远程容器开发,自签名错误
- chef-infra - 接受版本 >= 14 的 Chef Infra Client 许可协议