I am creating a login form which is limited to only 3 attempts then redirects the user. However, it quickly iterates from 3 to 0 at only 1 failed try then redirects the user. I have been trying but have been stuck at this.
Javascript loginUser code which runs upon submit:
function loginUser() {
var form = document.getElementById("myForm");
var username = document.getElementById("username").value;
var password = document.getElementById("password").value;
google.script.run.withSuccessHandler(function(output) {
var atmp = 3;
while(atmp > 0) {
if(output == 'TRUE') {
console.log("Success");
form.reset();
break;
}
else if (output == 'FALSE') {
console.log("Denied");
atmp--;
form.reset();
Swal.fire({
icon: 'error',
title: 'Wrong Username/Password! Please, try again.',
showCancelButton: false,
});
}
} if (atmp == 0) {
console.log("3 Failed attempts!");
// Redirect code here...
}
}).checkLogin(username, password);
}
Code.gs checkLogin function:
function checkLogin(username, password) {
var url = 'sheetLinkHere';
var ss= SpreadsheetApp.openByUrl(url);
var webAppSheet = ss.getSheetByName("users");
var find = webAppSheet.getDataRange().getDisplayValues().find(([, , c, d]) => c == username && d == password);
return find ? 'TRUE' : 'FALSE';
}
I tried placing the while loop at different parts of the code but still wont work for me.
CodePudding user response:
I was finally able to fix it. Credits to @Ruben in the comment section for giving me an idea. I just placed the variable outside the function and used an if-statement instead.
var atmp = 2;
function loginUser() {
var form = document.getElementById("myForm");
var username = document.getElementById("username").value;
var password = document.getElementById("password").value;
google.script.run.withSuccessHandler(function(output) {
if(atmp == 0) {
//redirect code here...
}else if(atmp > 0) {
if(output == 'TRUE') {
console.log("Success");
form.reset();
}
else if (output == 'FALSE') {
console.log("Denied");
atmp--;
}
}
}).checkLogin(username, password);
}
CodePudding user response:
I think you're trying to do something like this:
const
realPassword = "Melon",
input = document.querySelector('input'),
feedback = document.querySelector('span');
input.addEventListener('change', handlePasswordAttempt);
input.focus();
let attempts = 3;
function handlePasswordAttempt(event){
--attempts;
const attemptedPassword = input.value;
input.value = "";
input.focus();
if(attempts == 0){
feedback.textContent = "No login for you!";
input.setAttribute("disabled", "");
}
else if(attemptedPassword == realPassword){
feedback.textContent = "Qapla'!";
input.setAttribute("disabled", "");
}
else{
feedback.textContent = `Incorrect password. ${attempts} tries left.`;
}
}
<div>Enter password:<input></div><br/>
<div><span></span></div>