add temp captcha to contact form

This commit is contained in:
Blake Ridgway
2025-11-29 20:52:46 -06:00
parent c8df219f97
commit 59aeab43a9
4 changed files with 98 additions and 37 deletions

1
go.mod
View File

@@ -8,6 +8,7 @@ require (
) )
require ( require (
github.com/altcha-org/altcha-lib-go v0.2.2 // indirect
github.com/jackc/pgpassfile v1.0.0 // indirect github.com/jackc/pgpassfile v1.0.0 // indirect
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect
github.com/jackc/puddle/v2 v2.2.2 // indirect github.com/jackc/puddle/v2 v2.2.2 // indirect

2
go.sum
View File

@@ -1,3 +1,5 @@
github.com/altcha-org/altcha-lib-go v0.2.2 h1:KY7a7jFUf6tFKZF6MzuZMhSWuGMv0MtVkK/Kj4Oas38=
github.com/altcha-org/altcha-lib-go v0.2.2/go.mod h1:I8ESLVWR9C58uvGufB/AJDPhaSU4+4Oh3DLpVtgwDAk=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=

View File

@@ -422,7 +422,6 @@ func (h *Handler) handleContactSubmission(w http.ResponseWriter, r *http.Request
// If subscribe checkbox is checked, add to subscribers // If subscribe checkbox is checked, add to subscribers
if subscribe { if subscribe {
if err := h.db.AddSubscriber(r.Context(), email); err != nil { if err := h.db.AddSubscriber(r.Context(), email); err != nil {
// Log but don't fail the contact submission
h.logger.Printf( h.logger.Printf(
" Subscriber %s already exists or failed to add: %v", " Subscriber %s already exists or failed to add: %v",
email, email,
@@ -463,7 +462,7 @@ func (h *Handler) handleContactSubmission(w http.ResponseWriter, r *http.Request
} }
} }
// Save contact message to database (optional - add to your DB interface) // Save contact message to database
if err := h.db.AddContactMessage(r.Context(), name, email, subject, message); err != nil { if err := h.db.AddContactMessage(r.Context(), name, email, subject, message); err != nil {
h.logger.Printf( h.logger.Printf(
"⚠ Failed to save contact message: %v", "⚠ Failed to save contact message: %v",

View File

@@ -95,6 +95,23 @@
</label> </label>
</div> </div>
<!-- Simple Addition CAPTCHA -->
<div class="form-group">
<label for="captcha">
Quick Math Check <span class="required">*</span>
</label>
<div id="captchaQuestion" style="font-weight: bold; margin-bottom: 8px; color: #333; font-size: 16px;"></div>
<input
type="text"
id="captcha"
name="captcha"
required
placeholder="Enter the answer"
autocomplete="off"
inputmode="numeric"
/>
</div>
<button type="submit" class="form-submit"> <button type="submit" class="form-submit">
<i class="fas fa-paper-plane"></i> <i class="fas fa-paper-plane"></i>
Send Message Send Message
@@ -126,46 +143,88 @@
</div> </div>
<script> <script>
document.getElementById('contactForm').addEventListener( let currentCaptcha = null;
'submit',
async (e) => {
e.preventDefault();
const form = e.target;
const formData = new FormData(form);
console.log('Form submitted'); // Generate simple addition CAPTCHA (easier)
console.log('Form data:', Object.fromEntries(formData)); function generateCaptcha() {
const num1 = Math.floor(Math.random() * 20) + 1; // 1-20
const num2 = Math.floor(Math.random() * 20) + 1; // 1-20
const answer = num1 + num2;
try { return {
const response = await fetch('/contact', { question: `${num1} + ${num2} = ?`,
method: 'POST', answer: answer.toString()
headers: { };
'Content-Type': 'application/x-www-form-urlencoded', }
},
body: new URLSearchParams(formData),
});
console.log('Response status:', response.status); // Initialize CAPTCHA on page load
const data = await response.json(); function initCaptcha() {
console.log('Response data:', data); currentCaptcha = generateCaptcha();
document.getElementById('captchaQuestion').textContent = currentCaptcha.question;
document.getElementById('captcha').value = '';
document.getElementById('captcha').focus();
}
if (response.ok) { // Initialize on load
document.getElementById('successMessage') if (document.readyState === 'loading') {
.classList.add('show'); document.addEventListener('DOMContentLoaded', initCaptcha);
form.reset(); } else {
setTimeout(() => { initCaptcha();
document.getElementById('successMessage') }
.classList.remove('show');
}, 5000); document.getElementById('contactForm').addEventListener('submit', async (e) => {
} else { e.preventDefault();
alert('Error: ' + (data.error || 'Failed to send message'));
} // Validate CAPTCHA
} catch (error) { const userAnswer = document.getElementById('captcha').value.trim();
console.error('Error:', error); if (userAnswer !== currentCaptcha.answer) {
alert('Failed to send message: ' + error.message); alert('Incorrect answer. Please try again.');
} currentCaptcha = generateCaptcha();
document.getElementById('captchaQuestion').textContent = currentCaptcha.question;
document.getElementById('captcha').value = '';
document.getElementById('captcha').focus();
return;
} }
);
const form = e.target;
const formData = new FormData(form);
// Don't send the captcha answer to server
formData.delete('captcha');
console.log('Form submitted');
try {
const response = await fetch('/contact', {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
body: new URLSearchParams(formData),
});
console.log('Response status:', response.status);
const data = await response.json();
console.log('Response data:', data);
if (response.ok) {
document.getElementById('successMessage').classList.add('show');
form.reset();
initCaptcha();
setTimeout(() => {
document.getElementById('successMessage').classList.remove('show');
}, 5000);
} else {
alert('Error: ' + (data.error || 'Failed to send message'));
initCaptcha();
}
} catch (error) {
console.error('Error:', error);
alert('Failed to send message: ' + error.message);
initCaptcha();
}
});
</script> </script>
{{end}} {{end}}