Integrate CF Turnstile
This commit is contained in:
@@ -17,6 +17,7 @@ from payroll_excel_exporter import PayrollExcelExporter
|
||||
|
||||
# Load environment variables in .env
|
||||
load_dotenv()
|
||||
from turnstile_utils import turnstile_utils
|
||||
|
||||
# Initialize Flask application
|
||||
app = Flask(__name__)
|
||||
@@ -1482,15 +1483,28 @@ def register():
|
||||
|
||||
@app.route('/login', methods=['GET', 'POST'])
|
||||
def login():
|
||||
"""Enhanced user authentication with comprehensive logging"""
|
||||
"""Enhanced user authentication with Turnstile and comprehensive logging"""
|
||||
if request.method == 'POST':
|
||||
username = request.form.get('username', '').strip()
|
||||
password = request.form.get('password', '')
|
||||
turnstile_response = request.form.get('cf-turnstile-response', '')
|
||||
|
||||
if not username or not password:
|
||||
flash('Please enter both username and password.', 'error')
|
||||
return render_template('login.html')
|
||||
|
||||
# Verify Turnstile if enabled
|
||||
if turnstile_utils.is_enabled():
|
||||
if not turnstile_utils.verify_turnstile(turnstile_response):
|
||||
# Log failed Turnstile attempt
|
||||
logger_handler.log_security_event(
|
||||
event_type="turnstile_verification_failed",
|
||||
description=f"Failed Turnstile verification for username: {username}",
|
||||
severity="HIGH"
|
||||
)
|
||||
flash('Please complete the security verification.', 'error')
|
||||
return render_template('login.html')
|
||||
|
||||
try:
|
||||
# Find user (case-insensitive username)
|
||||
user = User.query.filter(
|
||||
@@ -1510,13 +1524,21 @@ def login():
|
||||
user.last_login_date = datetime.utcnow()
|
||||
db.session.commit()
|
||||
|
||||
# Log successful login
|
||||
# Log successful login with Turnstile info
|
||||
logger_handler.log_user_login(
|
||||
user_id=user.id,
|
||||
username=user.username,
|
||||
success=True
|
||||
)
|
||||
|
||||
# Log successful Turnstile verification
|
||||
if turnstile_utils.is_enabled():
|
||||
logger_handler.log_security_event(
|
||||
event_type="turnstile_verification_success",
|
||||
description=f"Successful Turnstile verification for user: {user.username}",
|
||||
severity="INFO"
|
||||
)
|
||||
|
||||
flash(f'Welcome back, {user.full_name}!', 'success')
|
||||
print(f"User {user.username} logged in successfully")
|
||||
|
||||
@@ -6266,6 +6288,14 @@ def inject_logging_status():
|
||||
'is_admin': has_admin_privileges(session.get('role', ''))
|
||||
}
|
||||
|
||||
@app.context_processor
|
||||
def inject_turnstile():
|
||||
"""Inject Turnstile settings into all templates"""
|
||||
return {
|
||||
'turnstile_enabled': turnstile_utils.is_enabled(),
|
||||
'turnstile_site_key': turnstile_utils.get_site_key()
|
||||
}
|
||||
|
||||
# Before request handler for request logging
|
||||
@app.before_request
|
||||
def log_request_info():
|
||||
|
||||
@@ -252,3 +252,36 @@
|
||||
transform: none !important;
|
||||
}
|
||||
}
|
||||
|
||||
/* Turnstile Integration */
|
||||
.turnstile-container {
|
||||
display: flex !important;
|
||||
justify-content: center !important;
|
||||
margin: 1.5rem 0 !important;
|
||||
}
|
||||
|
||||
.turnstile-container .cf-turnstile {
|
||||
transform: scale(0.95) !important;
|
||||
transform-origin: center !important;
|
||||
}
|
||||
|
||||
/* Responsive Turnstile */
|
||||
@media screen and (max-width: 480px) {
|
||||
.turnstile-container .cf-turnstile {
|
||||
transform: scale(0.85) !important;
|
||||
}
|
||||
}
|
||||
|
||||
/* Form validation enhancement for Turnstile */
|
||||
.auth-form .form-group.turnstile-error {
|
||||
border: 2px solid var(--error-color) !important;
|
||||
border-radius: var(--radius-lg) !important;
|
||||
padding: 1rem !important;
|
||||
background-color: rgba(239, 68, 68, 0.05) !important;
|
||||
}
|
||||
|
||||
/* Dark theme support */
|
||||
.turnstile-container .cf-turnstile[data-theme="dark"] {
|
||||
background-color: var(--gray-800) !important;
|
||||
border-radius: var(--radius-lg) !important;
|
||||
}
|
||||
@@ -85,5 +85,9 @@
|
||||
csrfToken: '{{ csrf_token() if csrf_token else '' }}'
|
||||
};
|
||||
</script>
|
||||
{% if turnstile_enabled %}
|
||||
<!-- Cloudflare Turnstile -->
|
||||
<script src="https://challenges.cloudflare.com/turnstile/v0/api.js" async defer></script>
|
||||
{% endif %}
|
||||
</body>
|
||||
</html>
|
||||
|
||||
+56
-30
@@ -17,7 +17,7 @@
|
||||
<p>Sign in to your account</p>
|
||||
</div>
|
||||
|
||||
<form method="POST" class="auth-form">
|
||||
<form method="POST" class="auth-form" id="loginForm">
|
||||
<div class="form-group">
|
||||
<label for="username">
|
||||
<i class="fas fa-user"></i>
|
||||
@@ -34,20 +34,30 @@
|
||||
<input type="password" id="password" name="password" required />
|
||||
</div>
|
||||
|
||||
<!-- Turnstile Integration -->
|
||||
{% if turnstile_enabled %}
|
||||
<div class="form-group turnstile-container">
|
||||
<div class="cf-turnstile"
|
||||
data-sitekey="{{ turnstile_site_key }}"
|
||||
data-callback="onTurnstileSuccess"
|
||||
data-expired-callback="onTurnstileExpired"
|
||||
data-theme="light"
|
||||
data-language="en">
|
||||
</div>
|
||||
</div>
|
||||
{% endif %}
|
||||
|
||||
<button type="submit" class="btn btn-primary btn-full">
|
||||
<i class="fas fa-sign-in-alt"></i>
|
||||
Sign In
|
||||
</button>
|
||||
</form>
|
||||
|
||||
<!-- Register link removed as requested -->
|
||||
</div>
|
||||
</div>
|
||||
{% endblock %}
|
||||
|
||||
{% block extra_scripts %}
|
||||
<script>
|
||||
// Enhanced form validation and user experience improvements
|
||||
document.addEventListener("DOMContentLoaded", function () {
|
||||
const form = document.querySelector(".auth-form");
|
||||
const inputs = form.querySelectorAll("input");
|
||||
@@ -70,37 +80,53 @@
|
||||
}
|
||||
});
|
||||
|
||||
// Enhanced form submission with loading state
|
||||
form.addEventListener("submit", function () {
|
||||
const submitBtn = form.querySelector('button[type="submit"]');
|
||||
const originalContent = submitBtn.innerHTML;
|
||||
|
||||
submitBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Signing In...';
|
||||
submitBtn.disabled = true;
|
||||
|
||||
// Re-enable button after 10 seconds as fallback
|
||||
setTimeout(() => {
|
||||
if (submitBtn.disabled) {
|
||||
submitBtn.innerHTML = originalContent;
|
||||
submitBtn.disabled = false;
|
||||
}
|
||||
}, 10000);
|
||||
});
|
||||
|
||||
// Add keyboard navigation enhancement
|
||||
inputs.forEach((input, index) => {
|
||||
input.addEventListener("keydown", function (e) {
|
||||
if (e.key === "Enter" && index < inputs.length - 1) {
|
||||
// Enhanced form validation with Turnstile
|
||||
form.addEventListener("submit", function(e) {
|
||||
{% if turnstile_enabled %}
|
||||
// Check if Turnstile is completed
|
||||
const turnstileResponse = document.querySelector('[name="cf-turnstile-response"]');
|
||||
if (!turnstileResponse || !turnstileResponse.value) {
|
||||
e.preventDefault();
|
||||
inputs[index + 1].focus();
|
||||
|
||||
// Highlight Turnstile container
|
||||
const turnstileContainer = document.querySelector('.turnstile-container');
|
||||
if (turnstileContainer) {
|
||||
turnstileContainer.classList.add('turnstile-error');
|
||||
setTimeout(() => {
|
||||
turnstileContainer.classList.remove('turnstile-error');
|
||||
}, 3000);
|
||||
}
|
||||
|
||||
// Show error message
|
||||
alert('Please complete the security verification.');
|
||||
return false;
|
||||
}
|
||||
{% endif %}
|
||||
|
||||
// Show loading state
|
||||
const submitButton = form.querySelector('button[type="submit"]');
|
||||
if (submitButton) {
|
||||
submitButton.disabled = true;
|
||||
submitButton.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Signing In...';
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
// Auto-focus first input
|
||||
if (inputs.length > 0) {
|
||||
inputs[0].focus();
|
||||
// Turnstile callback functions
|
||||
{% if turnstile_enabled %}
|
||||
function onTurnstileSuccess(token) {
|
||||
// Remove any error styling
|
||||
const turnstileContainer = document.querySelector('.turnstile-container');
|
||||
if (turnstileContainer) {
|
||||
turnstileContainer.classList.remove('turnstile-error');
|
||||
}
|
||||
});
|
||||
console.log('Turnstile verification successful');
|
||||
}
|
||||
|
||||
function onTurnstileExpired() {
|
||||
// Reset form if Turnstile expires
|
||||
console.log('Turnstile expired, please verify again');
|
||||
}
|
||||
{% endif %}
|
||||
</script>
|
||||
{% endblock %}
|
||||
@@ -0,0 +1,65 @@
|
||||
import os
|
||||
import requests
|
||||
from flask import current_app, request as flask_request
|
||||
|
||||
class TurnstileUtils:
|
||||
"""Cloudflare Turnstile utility class for verification"""
|
||||
|
||||
def __init__(self):
|
||||
self.site_key = os.environ.get('TURNSTILE_SITE_KEY', '')
|
||||
self.secret_key = os.environ.get('TURNSTILE_SECRET_KEY', '')
|
||||
self.enabled = os.environ.get('TURNSTILE_ENABLED', 'False').lower() == 'true'
|
||||
self.verify_url = 'https://challenges.cloudflare.com/turnstile/v0/siteverify'
|
||||
|
||||
def is_enabled(self):
|
||||
"""Check if Turnstile is enabled and properly configured"""
|
||||
return self.enabled and self.site_key and self.secret_key
|
||||
|
||||
def get_site_key(self):
|
||||
"""Get the Turnstile site key for frontend usage"""
|
||||
return self.site_key if self.is_enabled() else None
|
||||
|
||||
def verify_turnstile(self, turnstile_response):
|
||||
"""Verify Turnstile response with Cloudflare"""
|
||||
if not self.is_enabled():
|
||||
return True # Skip verification if disabled
|
||||
|
||||
if not turnstile_response:
|
||||
return False
|
||||
|
||||
try:
|
||||
# Get client IP for additional security
|
||||
client_ip = self._get_client_ip()
|
||||
|
||||
# Prepare verification request
|
||||
payload = {
|
||||
'secret': self.secret_key,
|
||||
'response': turnstile_response,
|
||||
'remoteip': client_ip
|
||||
}
|
||||
|
||||
# Send verification request to Cloudflare
|
||||
response = requests.post(self.verify_url, data=payload, timeout=10)
|
||||
result = response.json()
|
||||
|
||||
# Log verification attempt
|
||||
current_app.logger.info(f"Turnstile verification: success={result.get('success', False)}, IP={client_ip}")
|
||||
|
||||
return result.get('success', False)
|
||||
|
||||
except Exception as e:
|
||||
current_app.logger.error(f"Turnstile verification error: {e}")
|
||||
return False # Fail secure
|
||||
|
||||
def _get_client_ip(self):
|
||||
"""Get client IP address with proxy support"""
|
||||
# Check for forwarded IP (behind proxy/load balancer)
|
||||
if flask_request.headers.get('X-Forwarded-For'):
|
||||
return flask_request.headers.get('X-Forwarded-For').split(',')[0].strip()
|
||||
elif flask_request.headers.get('X-Real-IP'):
|
||||
return flask_request.headers.get('X-Real-IP')
|
||||
else:
|
||||
return flask_request.environ.get('REMOTE_ADDR', 'unknown')
|
||||
|
||||
# Initialize global instance
|
||||
turnstile_utils = TurnstileUtils()
|
||||
Reference in New Issue
Block a user