Скрипт приложений Google для генерации OTP [закрыто]Javascript

Форум по Javascript
Ответить
Anonymous
 Скрипт приложений Google для генерации OTP [закрыто]

Сообщение Anonymous »

Я попытался использовать скрипт Google Apps, прикрепленный к форме Google, чтобы сгенерировать однократный пароль. поле пусто. Кнопка отправки запускает генерацию OTP и будет отправлена ​​на идентификатор электронной почты. Затем респондент редактирует ответ и ключи в OTP, а затем представляет. Последнее представление запускает проверку OTP и отображает сообщение об успехе/неудаче. > Ссылка для респондера < /p>
script: < /p>
function onSubmit(e) {
Logger.log("onSubmit triggered");

var itemResponses = e.response.getItemResponses();
var emailItem = itemResponses.find(item =>
item.getItem().getTitle() == "Your Email Address"); // Replace with your email question title

if (!emailItem) {
Logger.log("ERROR: Email question NOT found!");
itemResponses.forEach(itemResponse => Logger.log("Item Title: " + itemResponse.getItem().getTitle()));
return;
}

var email = emailItem.getResponse();
Logger.log("Email: " + email);

var emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;

if (!emailRegex.test(email)) {
Logger.log("ERROR: Invalid email address: " + email);
e.response.withItemResponses().setConfirmationMessage("Invalid email address. Please enter a valid email.");
return;
}

// Get the edit URL
var editUrl = e.response.getEditResponseUrl();
Logger.log("Edit URL: " + editUrl);

var cache = CacheService.getScriptCache();
cache.put("pending_email", email, 300); // Store email for 5 minutes
cache.put("edit_url", editUrl, 300); // Store edit URL

// Generate and send OTP
var otp = generateOTP();
cache.put(email + "_otp", otp, 300); // Store OTP for 5 minutes
sendEmail(email, otp, editUrl); // Send email with OTP and edit URL

// Instead of setEditResponse, use a confirmation message to prompt for OTP entry
e.response.withItemResponses().setConfirmationMessage("Thank you
for submitting your email. Please check your inbox (and spam
folder) for the OTP. Click the link in the email to complete your
submission.");

return;
}

function onFormSubmit(e) {
Logger.log("onFormSubmit triggered");

var itemResponses = e.response.getItemResponses();
var emailItem = itemResponses.find(item => item.getItem().getTitle() == "Your Email Address"); // Replace with your email question title
var email = emailItem.getResponse();
var otpQuestion = itemResponses.find(item => item.getItem().getTitle() == "OTP"); // Replace with your OTP question title
var submittedOtp = otpQuestion ? otpQuestion.getResponse() : null;

var cache = CacheService.getScriptCache();
var cachedOtp = cache.get(email + "_otp");

if (submittedOtp && cachedOtp && submittedOtp == cachedOtp) {
cache.put(email + "_verified", true, 3600);
e.response.withItemResponses().setConfirmationMessage("Your
email has been verified. Thank you for your submission!");
} else if (submittedOtp) {
e.response.withItemResponses().setConfirmationMessage("Incorrect OTP. Please try again.");
} else {
e.response.withItemResponses().setConfirmationMessage("Please enter the OTP.");
}
}

function generateOTP() {
var otp = Math.floor(100000 + Math.random() * 900000); // 6-digit OTP
return otp.toString();
}

function sendEmail(email, otp, editUrl) { // Add editUrl parameter
var subject = "Your OTP for Google Form Verification";
var body = "Your OTP is: " + otp + "\n\nPlease click the
following link to complete your submission: " + editUrl; // Include editUrl

try {
MailApp.sendEmail(email, subject, body);
Logger.log("OTP email sent successfully to: " + email);
} catch (error) {
Logger.log("ERROR sending OTP email: " + error);
}
}


Подробнее здесь: https://stackoverflow.com/questions/794 ... generation
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «Javascript»