#167 - Login Form Throttle With Security Check v0.1
Limit failed login attempts and trigger a timed security check to prevent brute force attacks.
<!-- 💙 MEMBERSCRIPT #167 v0.1 💙 - LOGIN THROTTLE WITH SECURITY CHECK -->
<script>
(function() {
const MAX_ATTEMPTS = 3;
const STORAGE_KEY = 'ms_login_attempts';
const SECURITY_DELAY = 30; // seconds
const formWrapper = document.querySelector('[data-ms-code="login-throttle-form"]');
const submitButton = document.querySelector('[data-ms-code="throttle-submit"]');
const errorMessage = document.querySelector('[data-ms-code="throttle-error"]');
const attemptCounter = document.querySelector('[data-ms-code="attempt-counter"]');
const loginForm = formWrapper?.querySelector('[data-ms-form="login"]');
if (!formWrapper || !submitButton || !loginForm) {
console.warn('MemberScript #167: Required elements not found.');
return;
}
function getAttemptData() {
const stored = sessionStorage.getItem(STORAGE_KEY);
if (!stored) return { count: 0, timestamp: 0 };
try {
return JSON.parse(stored);
} catch {
return { count: 0, timestamp: 0 };
}
}
function setAttemptData(count, timestamp = Date.now()) {
sessionStorage.setItem(STORAGE_KEY, JSON.stringify({ count, timestamp }));
}
let attemptData = getAttemptData();
let securityTimer = null;
function updateUIState() {
const remainingAttempts = MAX_ATTEMPTS - attemptData.count;
// Don't update UI if security timer is running
if (securityTimer) {
return;
}
if (attemptData.count >= MAX_ATTEMPTS) {
showSecurityCheck();
showError('Too many failed attempts. Please wait for security verification.');
} else {
hideSecurityCheck();
if (attemptData.count > 0) {
showError(`Login failed. ${remainingAttempts} attempt${remainingAttempts === 1 ? '' : 's'} remaining.`);
} else {
hideError();
}
}
if (attemptCounter) {
if (attemptData.count >= MAX_ATTEMPTS) {
attemptCounter.textContent = 'Security verification required';
attemptCounter.style.color = '#e74c3c';
} else if (attemptData.count > 0) {
attemptCounter.textContent = `${remainingAttempts} attempt${remainingAttempts === 1 ? '' : 's'} remaining`;
attemptCounter.style.color = attemptData.count >= 2 ? '#e67e22' : '#95a5a6';
} else {
attemptCounter.textContent = '';
}
}
console.log(`UI State: ${attemptData.count}/${MAX_ATTEMPTS} attempts, security timer: ${securityTimer ? 'active' : 'inactive'}`);
}
function showSecurityCheck() {
let securityBox = formWrapper.querySelector('[data-ms-security-check]');
if (!securityBox) {
securityBox = document.createElement('div');
securityBox.setAttribute('data-ms-security-check', 'true');
securityBox.style.cssText = `
width: 100%;
margin: 15px 0;
padding: 20px;
border: 2px solid #ff6b6b;
border-radius: 8px;
background: #fff5f5;
text-align: center;
box-sizing: border-box;
`;
submitButton.parentNode.insertBefore(securityBox, submitButton);
}
securityBox.innerHTML = `
<strong>Security Check</strong><br>
<small>Please wait ${SECURITY_DELAY} seconds before trying again</small><br>
<div id="security-countdown" style="margin-top: 10px; font-size: 24px; font-weight: bold; color: #ff6b6b;">${SECURITY_DELAY}</div>
`;
// Disable submit button
submitButton.disabled = true;
submitButton.style.opacity = '0.5';
// Clear any existing timer
if (securityTimer) {
clearInterval(securityTimer);
}
// Start countdown
let timeLeft = SECURITY_DELAY;
securityTimer = setInterval(() => {
timeLeft--;
const countdown = securityBox.querySelector('#security-countdown');
if (countdown) {
countdown.textContent = timeLeft;
}
if (timeLeft <= 0) {
clearInterval(securityTimer);
securityTimer = null;
securityBox.innerHTML = `
<strong style="color: #27ae60;">✓ Security Check Complete</strong><br>
<small>You may now try logging in again</small>
`;
// Re-enable submit button
submitButton.disabled = false;
submitButton.style.opacity = '1';
// Reset attempt count so user gets fresh attempts
attemptData.count = 0;
setAttemptData(0);
// Update UI to reflect fresh state
updateUIState();
// Hide security box after 5 seconds (longer so user sees message)
setTimeout(() => {
if (securityBox) {
securityBox.style.display = 'none';
}
}, 5000);
}
}, 1000);
}
function hideSecurityCheck() {
const securityBox = formWrapper.querySelector('[data-ms-security-check]');
if (securityBox && !securityTimer) {
securityBox.remove();
}
if (securityTimer) {
clearInterval(securityTimer);
securityTimer = null;
}
// Only enable button if we're not in security check mode
if (attemptData.count < MAX_ATTEMPTS) {
submitButton.disabled = false;
submitButton.style.opacity = '1';
}
}
function showError(message) {
if (errorMessage) {
errorMessage.textContent = message;
errorMessage.style.display = 'block';
}
}
function hideError() {
if (errorMessage) {
errorMessage.style.display = 'none';
}
}
function handleSubmit(event) {
// Prevent submission if security check is active
if (attemptData.count >= MAX_ATTEMPTS && securityTimer) {
event.preventDefault();
showError('Please wait for the security check to complete.');
return false;
}
const currentAttemptCount = attemptData.count;
setTimeout(() => {
checkLoginResult(currentAttemptCount);
}, 1500);
}
function checkLoginResult(previousAttemptCount) {
const hasError = document.querySelector('[data-ms-error]') ||
document.querySelector('.w-form-fail:not([style*="display: none"])') ||
formWrapper.querySelector('.w-form-fail:not([style*="display: none"])') ||
loginForm.querySelector('[data-ms-error]');
if (window.$memberstackDom) {
window.$memberstackDom.getCurrentMember().then(member => {
if (member && member.id) {
// Success! Reset everything
sessionStorage.removeItem(STORAGE_KEY);
attemptData = { count: 0, timestamp: 0 };
hideError();
hideSecurityCheck();
if (attemptCounter) {
attemptCounter.textContent = 'Login successful!';
attemptCounter.style.color = '#27ae60';
}
} else if (hasError) {
handleFailedLogin(previousAttemptCount);
}
}).catch(() => {
if (hasError) {
handleFailedLogin(previousAttemptCount);
}
});
} else {
if (hasError) {
handleFailedLogin(previousAttemptCount);
} else {
const successElement = document.querySelector('.w-form-done:not([style*="display: none"])');
if (successElement) {
sessionStorage.removeItem(STORAGE_KEY);
attemptData = { count: 0, timestamp: 0 };
hideError();
hideSecurityCheck();
}
}
}
}
function handleFailedLogin(previousAttemptCount) {
attemptData.count = previousAttemptCount + 1;
setAttemptData(attemptData.count);
console.log(`Failed login attempt ${attemptData.count}/${MAX_ATTEMPTS}`);
// Force UI update after a brief delay to ensure DOM is ready
setTimeout(() => {
updateUIState();
}, 100);
}
function init() {
loginForm.addEventListener('submit', handleSubmit);
updateUIState();
if (window.$memberstackDom) {
window.$memberstackDom.getCurrentMember().then(member => {
if (member && member.id) {
sessionStorage.removeItem(STORAGE_KEY);
attemptData = { count: 0, timestamp: 0 };
}
}).catch(() => {
// No user logged in
});
}
}
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', init);
} else {
init();
}
})();
</script>
Creación del escenario Make.com
1. Descargue el proyecto JSON a continuación para empezar.
2. Navegue hasta Make.com y Cree un nuevo escenario...

3. Haga clic en el pequeño cuadro con 3 puntos y luego Importar Blueprint...

4. Sube tu archivo y ¡voilá! Ya está listo para vincular sus propias cuentas.
¿Necesitas ayuda con este MemberScript?
Todos los clientes de Memberstack pueden solicitar asistencia en el Slack 2.0. Tenga en cuenta que no se trata de funciones oficiales y que no se puede garantizar la asistencia.
Únete al Slack 2.0Autenticación y pagos para sitios Webflow
Añada inicios de sesión, suscripciones, contenido cerrado y mucho más a su sitio Webflow: fácil y totalmente personalizable.
.webp)
"Hemos estado utilizando Memberstack durante mucho tiempo, y nos ha ayudado a lograr cosas que nunca hubiéramos creído posible usando Webflow. Nos ha permitido construir plataformas con gran profundidad y funcionalidad y el equipo que hay detrás siempre ha sido súper servicial y receptivo a los comentarios"

"He estado construyendo un sitio de membresía con Memberstack y Jetboost para un cliente. Se siente como magia construir con estas herramientas. Como alguien que ha trabajado en una agencia donde algunas de estas aplicaciones fueron codificadas desde cero, finalmente entiendo el bombo ahora. Esto es mucho más rápido y mucho más barato."

"Uno de los mejores productos para iniciar un sitio de membresía - Me gusta la facilidad de uso de Memberstack. Yo era capaz de mi sitio de membresía en marcha y funcionando dentro de un día. No hay nada más fácil que eso. También proporciona la funcionalidad que necesito para hacer la experiencia del usuario más personalizada."

"Mi negocio no sería lo que es sin Memberstack. Si crees que 30 $/mes es caro, prueba a contratar a un desarrollador para que integre recomendaciones personalizadas en tu sitio por ese precio. Increíblemente flexible conjunto de herramientas para aquellos dispuestos a poner en algunos esfuerzos mínimos para ver su documentación bien elaborado."


"La comunidad de Slack es una de las más activas que he visto y los clientes están dispuestos a responder preguntas y ofrecer soluciones. He realizado evaluaciones en profundidad de herramientas alternativas y siempre volvemos a Memberstack: ahórrate el tiempo y dale una oportunidad"."

¿Necesitas ayuda con este MemberScript? ¡Únete a nuestra comunidad Slack!
Únete al Slack de la comunidad Memberstack y ¡pregunta! Espera una respuesta rápida de un miembro del equipo, un experto de Memberstack o un compañero de la comunidad.
Únete a nuestro Slack