2FA Enable/Disable problems fixed

This commit is contained in:
Hamit Şimşek
2025-05-30 01:11:52 +03:00
parent 22c747f14a
commit 174b002723
4 changed files with 222 additions and 9 deletions

View File

@@ -234,6 +234,64 @@ def disable_2fa():
return redirect(url_for('main.profile'))
@bp.route('/enable-2fa')
@login_required
def enable_2fa():
"""
Enable 2FA for existing logged-in users.
Security: Requires active login session.
"""
if current_user.is_2fa_enabled:
flash('Two-factor authentication is already enabled for your account.', 'info')
return redirect(url_for('main.profile'))
# Generate new TOTP secret if not exists
if not current_user.totp_secret:
current_user.generate_totp_secret()
db.session.commit()
# Generate QR code for Google Authenticator
qr_code = current_user.generate_qr_code()
return render_template('auth/enable_2fa.html',
qr_code=qr_code,
username=current_user.username,
title='Enable Two-Factor Authentication')
@bp.route('/verify-enable-2fa', methods=['POST'])
@login_required
def verify_enable_2fa():
"""
Verify TOTP token and enable 2FA for existing user.
Security: Requires active login session and valid TOTP token.
"""
if current_user.is_2fa_enabled:
flash('Two-factor authentication is already enabled.', 'info')
return redirect(url_for('main.profile'))
token = request.form.get('token', '').strip()
if not token:
flash('Please enter the authentication code.', 'error')
return redirect(url_for('auth.enable_2fa'))
if current_user.verify_totp(token):
# Enable 2FA for the user
current_user.enable_2fa()
logger.info(f'2FA enabled for user: {current_user.username}')
flash('Two-factor authentication has been successfully enabled!', 'success')
return redirect(url_for('main.profile'))
else:
logger.warning(f'Failed 2FA enable verification for user: {current_user.username}')
flash('Invalid authentication code. Please try again.', 'error')
return redirect(url_for('auth.enable_2fa'))
def track_login_location(user):
"""
Track user login location and handle suspicious login detection.

View File

@@ -94,13 +94,12 @@ class User(UserMixin, db.Model):
totp = pyotp.TOTP(self.totp_secret)
# Verify token with a 1-period window (30 seconds before/after)
return totp.verify(token, valid_window=1)
def generate_qr_code(self, issuer_name='Flask-2FA-App'):
"""
Generate a QR code for the TOTP URI.
Returns:
str: Base64-encoded PNG image of the QR code
str: HTML img tag with base64-encoded PNG image of the QR code
"""
uri = self.generate_totp_uri(issuer_name)
@@ -122,7 +121,8 @@ class User(UserMixin, db.Model):
img.save(img_buffer, format='PNG')
img_buffer.seek(0)
return base64.b64encode(img_buffer.getvalue()).decode()
base64_img = base64.b64encode(img_buffer.getvalue()).decode()
return f'<img src="data:image/png;base64,{base64_img}" class="img-fluid" alt="QR Code for 2FA Setup" style="max-width: 200px;">'
def enable_2fa(self):
"""Enable two-factor authentication for the user."""

View File

@@ -0,0 +1,157 @@
{% extends "base.html" %}
{% block content %}
<div class="row justify-content-center">
<div class="col-md-8">
<div class="card">
<div class="card-header text-center">
<h3><i class="bi bi-shield-check"></i> Enable Two-Factor Authentication</h3>
<p class="mb-0 text-muted">Secure your account with an additional layer of protection</p>
</div>
<div class="card-body">
{% with messages = get_flashed_messages(with_categories=true) %}
{% if messages %}
{% for category, message in messages %}
<div class="alert alert-{{ 'danger' if category == 'error' else ('warning' if category == 'warning' else 'success') }} alert-dismissible fade show">
{{ message }}
<button type="button" class="btn-close" data-bs-dismiss="alert"></button>
</div>
{% endfor %}
{% endif %}
{% endwith %}
<div class="row">
<div class="col-md-6">
<h5><i class="bi bi-qr-code"></i> Step 1: Scan QR Code</h5>
<div class="text-center mb-3">
<div class="qr-code-container">
{{ qr_code|safe }}
</div>
</div>
<div class="alert alert-info">
<h6><i class="bi bi-info-circle"></i> Instructions:</h6>
<ol class="mb-0">
<li>Install an authenticator app like <strong>Google Authenticator</strong> or <strong>Authy</strong></li>
<li>Open the app and scan this QR code</li>
<li>Enter the 6-digit code from your app below</li>
</ol>
</div>
</div>
<div class="col-md-6">
<h5><i class="bi bi-key"></i> Step 2: Verify Setup</h5>
<form method="POST" action="{{ url_for('auth.verify_enable_2fa') }}">
<input type="hidden" name="csrf_token" value="{{ csrf_token() }}"/>
<div class="mb-3">
<label for="token" class="form-label">Authentication Code</label>
<input type="text"
id="token"
name="token"
class="form-control form-control-lg text-center"
placeholder="000000"
maxlength="6"
pattern="[0-9]{6}"
required
autocomplete="off"
style="letter-spacing: 0.5em; font-family: monospace;">
<div class="form-text">Enter the 6-digit code from your authenticator app</div>
</div>
<div class="d-grid gap-2">
<button type="submit" class="btn btn-success btn-lg">
<i class="bi bi-shield-check"></i> Enable 2FA
</button>
<a href="{{ url_for('main.profile') }}" class="btn btn-outline-secondary">
<i class="bi bi-arrow-left"></i> Cancel
</a>
</div>
</form>
</div>
</div>
<hr class="my-4">
<div class="row">
<div class="col-12">
<h6><i class="bi bi-shield-exclamation"></i> Security Benefits</h6>
<div class="row">
<div class="col-md-4">
<div class="text-center">
<i class="bi bi-lock text-success" style="font-size: 2rem;"></i>
<h6 class="mt-2">Enhanced Security</h6>
<small class="text-muted">Protect against password theft</small>
</div>
</div>
<div class="col-md-4">
<div class="text-center">
<i class="bi bi-phone text-primary" style="font-size: 2rem;"></i>
<h6 class="mt-2">Mobile Protection</h6>
<small class="text-muted">Secure codes on your device</small>
</div>
</div>
<div class="col-md-4">
<div class="text-center">
<i class="bi bi-globe text-warning" style="font-size: 2rem;"></i>
<h6 class="mt-2">Location Tracking</h6>
<small class="text-muted">Monitor suspicious logins</small>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<style>
.qr-code-container {
background-color: white;
padding: 20px;
border-radius: 10px;
display: inline-block;
box-shadow: 0 2px 10px rgba(0,0,0,0.1);
}
.qr-code-container svg {
max-width: 200px;
height: auto;
}
@media (max-width: 768px) {
.qr-code-container svg {
max-width: 150px;
}
}
</style>
<script>
document.addEventListener('DOMContentLoaded', function() {
const tokenInput = document.getElementById('token');
// Auto-focus on token input
tokenInput.focus();
// Auto-format input (digits only)
tokenInput.addEventListener('input', function(e) {
let value = e.target.value.replace(/\D/g, '');
if (value.length <= 6) {
e.target.value = value;
}
});
// Auto-submit when 6 digits entered
tokenInput.addEventListener('input', function(e) {
if (e.target.value.length === 6) {
// Small delay to show the complete code
setTimeout(() => {
e.target.form.submit();
}, 500);
}
});
});
</script>
{% endblock %}

View File

@@ -68,22 +68,20 @@
<strong>Enabled</strong><br>
Your account is protected with 2FA
</div>
<form method="POST" action="{{ url_for('auth.disable_2fa') }}"
<form method="POST" action="{{ url_for('auth.disable_2fa') }}"
onsubmit="return confirm('Are you sure you want to disable two-factor authentication? This will make your account less secure.');">
{{ csrf_token() }}
<input type="hidden" name="csrf_token" value="{{ csrf_token() }}"/>
<button type="submit" class="btn btn-outline-warning btn-sm">
<i class="bi bi-shield-x"></i> Disable 2FA
</button>
</form>
{% else %}
<div class="alert alert-warning">
{% else %} <div class="alert alert-warning">
<i class="bi bi-exclamation-triangle"></i>
<strong>Setup Required</strong><br>
Complete 2FA setup for better security
</div>
<a href="{{ url_for('auth.register') }}" class="btn btn-success btn-sm">
<a href="{{ url_for('auth.enable_2fa') }}" class="btn btn-success btn-sm">
<i class="bi bi-shield-check"></i> Setup 2FA
</a>
{% endif %}