feat: Implement Two-Factor Authentication (2FA) functionality

- Added support for Two-Factor Authentication, including setup, verification, and disabling features.
- Introduced new components for 2FA setup and verification, enhancing user security.
- Updated user model to include fields for 2FA secret, status, and backup codes.
- Created migration to add necessary database fields for 2FA.
- Enhanced authentication handlers to manage 2FA processes during login and profile updates.
- Updated routes to include 2FA-related endpoints for setup and verification.
This commit is contained in:
StarFleetCPTN
2025-03-17 05:17:03 -07:00
parent ef4bee88b8
commit a7d912aa44
14 changed files with 955 additions and 18 deletions
+133
View File
@@ -5,8 +5,112 @@ import (
"github.com/starfleetcptn/gomft/internal/db"
)
// Dialog component for 2FA disable confirmation
templ TwoFactorDisableDialog() {
<div id="disable-2fa-dialog" class="hidden fixed inset-0 bg-secondary-900/50 dark:bg-secondary-900/80 backdrop-blur-sm z-50 flex items-center justify-center">
<div class="bg-white dark:bg-secondary-800 rounded-lg shadow-xl max-w-md w-full mx-4 overflow-hidden">
<div class="px-6 pt-5 pb-3 text-center">
<div class="flex justify-center mb-2">
<i class="fas fa-shield-alt text-yellow-400 text-3xl"></i>
</div>
<h3 class="text-xl font-medium text-secondary-900 dark:text-secondary-100">
Disable Two-Factor Authentication
</h3>
</div>
<div class="px-6 py-4">
<p class="text-secondary-700 dark:text-secondary-300 mb-4">
Are you sure you want to disable two-factor authentication? This will make your account less secure.
</p>
<div class="space-y-4">
<div>
<label for="current-password-2fa" class="block text-sm font-medium text-secondary-700 dark:text-secondary-300 mb-1">
<i class="fas fa-lock mr-1"></i> Current Password
</label>
<div class="relative">
<div class="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
<i class="fas fa-key text-secondary-400 dark:text-secondary-600"></i>
</div>
<input
type="password"
id="current-password-2fa"
name="current_password"
class="form-input pl-10 w-full"
placeholder="Enter your current password"
required/>
</div>
</div>
<div id="disable-2fa-result"></div>
</div>
</div>
<div class="px-6 py-4 flex justify-end space-x-3">
<button type="button" class="btn-secondary" onclick="hideDisable2FADialog()">
Cancel
</button>
<button
type="button"
class="btn-danger"
onclick="submitDisable2FA()">
<i class="fas fa-times mr-1"></i>
Disable 2FA
</button>
</div>
</div>
</div>
}
templ Profile(ctx context.Context, user db.User) {
@LayoutWithContext("Profile", ctx) {
<script>
// Initialize dialog functionality
document.addEventListener('DOMContentLoaded', function() {
console.log('Initializing 2FA dialog functionality');
// Global functions for dialog control
window.hideDisable2FADialog = function() {
document.getElementById('disable-2fa-dialog').classList.add('hidden');
document.getElementById('current-password-2fa').value = '';
document.getElementById('disable-2fa-result').innerHTML = '';
};
window.showDisable2FADialog = function() {
console.log('Showing 2FA disable dialog');
document.getElementById('disable-2fa-dialog').classList.remove('hidden');
};
window.submitDisable2FA = function() {
const password = document.getElementById('current-password-2fa').value;
if (!password) {
document.getElementById('disable-2fa-result').innerHTML = `
<div class="bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded" role="alert">
<span class="block sm:inline">Current password is required</span>
</div>`;
return;
}
htmx.ajax('POST', '/profile/2fa/disable', {
target: '#disable-2fa-result',
swap: 'innerHTML',
values: { current_password: password }
});
};
// Close dialog when clicking outside
document.getElementById('disable-2fa-dialog').addEventListener('click', function(e) {
if (e.target === this) {
hideDisable2FADialog();
}
});
// Close dialog on escape key
document.addEventListener('keydown', function(e) {
if (e.key === 'Escape' && !document.getElementById('disable-2fa-dialog').classList.contains('hidden')) {
hideDisable2FADialog();
}
});
});
</script>
@TwoFactorDisableDialog()
<div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
<div class="flex items-center justify-between mb-6">
<h1 class="text-3xl font-bold text-secondary-900 dark:text-secondary-100">
@@ -45,6 +149,35 @@ templ Profile(ctx context.Context, user db.User) {
}
</dd>
</div>
<div class="flex flex-col sm:flex-row">
<dt class="text-sm font-medium text-secondary-500 dark:text-secondary-400 sm:w-1/3 mb-1 sm:mb-0">Two-Factor Authentication</dt>
<dd class="text-sm text-secondary-900 dark:text-secondary-100 sm:w-2/3">
if user.TwoFactorEnabled {
<div class="flex items-center space-x-4">
<span class="badge badge-success">
<i class="fas fa-shield-alt mr-1"></i> Enabled
</span>
<button
type="button"
class="btn-danger btn-sm"
onclick="showDisable2FADialog()">
<i class="fas fa-times mr-1"></i>
Disable 2FA
</button>
</div>
} else {
<div class="flex items-center space-x-4">
<span class="badge badge-warning">
<i class="fas fa-shield-alt mr-1"></i> Disabled
</span>
<a href="/profile/2fa/setup" class="btn-primary btn-sm">
<i class="fas fa-lock mr-1"></i>
Enable 2FA
</a>
</div>
}
</dd>
</div>
<div class="flex flex-col sm:flex-row">
<dt class="text-sm font-medium text-secondary-500 dark:text-secondary-400 sm:w-1/3 mb-1 sm:mb-0">Theme</dt>
<dd class="text-sm text-secondary-900 dark:text-secondary-100 sm:w-2/3">
@@ -74,6 +74,7 @@ templ GooglePhotosDestinationForm() {
<input id="dest_read_only" name="dest_read_only" type="checkbox"
class="sr-only"
x-model="destReadOnly"
:value="destReadOnly ? 'true' : 'false'"
/>
<div class="block bg-secondary-200 dark:bg-secondary-700 w-14 h-8 rounded-full"></div>
<div class="dot absolute left-1 top-1 bg-white dark:bg-secondary-100 w-6 h-6 rounded-full transition"
@@ -109,6 +110,7 @@ templ GooglePhotosDestinationForm() {
<input id="dest_include_archived" name="dest_include_archived" type="checkbox"
class="sr-only"
x-model="destIncludeArchived"
:value="destIncludeArchived ? 'true' : 'false'"
/>
<div class="block bg-secondary-200 dark:bg-secondary-700 w-14 h-8 rounded-full"></div>
<div class="dot absolute left-1 top-1 bg-white dark:bg-secondary-100 w-6 h-6 rounded-full transition"
@@ -74,6 +74,7 @@ templ GooglePhotosSourceForm() {
<input id="source_read_only" name="source_read_only" type="checkbox"
class="sr-only"
x-model="sourceReadOnly"
:value="sourceReadOnly ? 'true' : 'false'"
/>
<div class="block bg-secondary-200 dark:bg-secondary-700 w-14 h-8 rounded-full"></div>
<div class="dot absolute left-1 top-1 bg-white dark:bg-secondary-100 w-6 h-6 rounded-full transition"
@@ -109,6 +110,7 @@ templ GooglePhotosSourceForm() {
<input id="source_include_archived" name="source_include_archived" type="checkbox"
class="sr-only"
x-model="sourceIncludeArchived"
:value="sourceIncludeArchived ? 'true' : 'false'"
/>
<div class="block bg-secondary-200 dark:bg-secondary-700 w-14 h-8 rounded-full"></div>
<div class="dot absolute left-1 top-1 bg-white dark:bg-secondary-100 w-6 h-6 rounded-full transition"
+150
View File
@@ -0,0 +1,150 @@
package components
import "context"
type TwoFactorSetupData struct {
QRCodeURL string
Secret string
BackupCodes []string
ErrorMessage string
}
templ TwoFactorSetup(ctx context.Context, data TwoFactorSetupData) {
@LayoutWithContext("Two-Factor Authentication Setup", ctx) {
<div class="min-h-screen bg-secondary-50 dark:bg-secondary-900 py-12">
<div class="max-w-3xl mx-auto px-4 sm:px-6 lg:px-8">
<div class="bg-white dark:bg-secondary-800 shadow rounded-lg p-6">
<div class="text-center mb-8">
<h2 class="text-3xl font-bold text-secondary-900 dark:text-secondary-100">Set Up Two-Factor Authentication</h2>
<p class="mt-2 text-secondary-600 dark:text-secondary-400">Enhance your account security with 2FA</p>
</div>
if data.ErrorMessage != "" {
<div class="bg-red-100 dark:bg-red-900 border border-red-400 dark:border-red-700 text-red-700 dark:text-red-300 px-4 py-3 rounded-lg mb-6" role="alert">
<div class="flex items-center">
<i class="fas fa-exclamation-circle mr-2"></i>
<span class="block sm:inline">{ data.ErrorMessage }</span>
</div>
</div>
}
<div class="space-y-8">
<div>
<h3 class="text-xl font-semibold text-secondary-900 dark:text-secondary-100 mb-4">1. Scan QR Code</h3>
<p class="text-secondary-600 dark:text-secondary-400 mb-4">
Scan this QR code with your authenticator app (Google Authenticator, Authy, etc.)
</p>
<div class="flex justify-center mb-4">
<img src={ data.QRCodeURL } alt="QR Code" class="border border-secondary-200 dark:border-secondary-700 rounded-lg p-2 bg-white"/>
</div>
<div class="text-center">
<p class="text-sm text-secondary-600 dark:text-secondary-400">
Can't scan the QR code? Use this code instead:
</p>
<code class="block mt-2 p-2 bg-secondary-100 dark:bg-secondary-700 rounded font-mono text-sm">
{ data.Secret }
</code>
</div>
</div>
<div>
<h3 class="text-xl font-semibold text-secondary-900 dark:text-secondary-100 mb-4">2. Verify Setup</h3>
<form
method="POST"
action="/profile/2fa/verify"
class="space-y-4"
x-data="{ code: '', loading: false }"
@submit="loading = true">
<div>
<label for="code" class="block text-sm font-medium text-secondary-700 dark:text-secondary-300 mb-1">
Enter the 6-digit code from your authenticator app
</label>
<input
type="text"
id="code"
name="code"
x-model="code"
class="form-input block w-full"
pattern="[0-9]*"
inputmode="numeric"
maxlength="6"
required/>
</div>
<button
type="submit"
class="btn-primary w-full"
x-bind:disabled="code.length !== 6 || loading">
<span x-show="!loading">Verify and Enable 2FA</span>
<span x-show="loading" class="flex items-center justify-center">
<svg class="animate-spin -ml-1 mr-3 h-5 w-5 text-white" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
<circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
<path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
</svg>
Verifying...
</span>
</button>
</form>
</div>
if len(data.BackupCodes) > 0 {
<div>
<h3 class="text-xl font-semibold text-secondary-900 dark:text-secondary-100 mb-4">3. Save Backup Codes</h3>
<p class="text-secondary-600 dark:text-secondary-400 mb-4">
Store these backup codes in a safe place. You can use them to access your account if you lose your authenticator device.
</p>
<div class="grid grid-cols-2 gap-4 mb-4">
for _, code := range data.BackupCodes {
<div class="p-2 bg-secondary-100 dark:bg-secondary-700 rounded font-mono text-sm text-center">
{ code }
</div>
}
</div>
<div class="text-center">
<button
class="btn-secondary"
onclick="downloadBackupCodes(this)">
<i class="fas fa-download mr-2"></i>
Download Backup Codes
</button>
<script>
function downloadBackupCodes(button) {
// Get backup codes from the displayed elements
const codes = Array.from(
document.querySelectorAll('.bg-secondary-100.dark\\:bg-secondary-700')
).map(el => el.textContent.trim());
// Create content for the file
const content =
"2FA Backup Codes - Keep these safe!\n" +
"=====================================\n\n" +
codes.join("\n") +
"\n\n" +
"Generated: " + new Date().toISOString().split('T')[0] + "\n" +
"These codes can be used to access your account if you lose access to your authenticator app.\n" +
"Each code can only be used once. Keep these codes safe and secure.";
// Create blob and download link
const blob = new Blob([content], { type: 'text/plain' });
const url = window.URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = '2fa-backup-codes.txt';
// Trigger download
document.body.appendChild(a);
a.click();
// Cleanup
window.URL.revokeObjectURL(url);
document.body.removeChild(a);
}
</script>
</div>
</div>
}
</div>
</div>
</div>
</div>
}
}
+83
View File
@@ -0,0 +1,83 @@
package components
import "context"
type TwoFactorVerifyData struct {
ErrorMessage string
}
templ TwoFactorVerify(ctx context.Context, data TwoFactorVerifyData) {
@LayoutWithContext("Two-Factor Authentication", ctx) {
<div class="min-h-screen bg-secondary-50 dark:bg-secondary-900 py-12">
<div class="max-w-md mx-auto px-4 sm:px-6 lg:px-8">
<div class="bg-white dark:bg-secondary-800 shadow rounded-lg p-6">
<div class="text-center mb-8">
<div class="inline-flex items-center justify-center w-20 h-20 rounded-full bg-primary-100 dark:bg-primary-900 mb-4">
<i class="fas fa-shield-alt text-primary-600 dark:text-primary-400 text-3xl"></i>
</div>
<h2 class="text-3xl font-bold text-secondary-900 dark:text-secondary-100">Two-Factor Authentication</h2>
<p class="mt-2 text-secondary-600 dark:text-secondary-400">Enter the code from your authenticator app</p>
</div>
if data.ErrorMessage != "" {
<div class="bg-red-100 dark:bg-red-900 border border-red-400 dark:border-red-700 text-red-700 dark:text-red-300 px-4 py-3 rounded-lg mb-6" role="alert">
<div class="flex items-center">
<i class="fas fa-exclamation-circle mr-2"></i>
<span class="block sm:inline">{ data.ErrorMessage }</span>
</div>
</div>
}
<form
method="POST"
action="/login/verify"
class="space-y-6"
x-data="{ code: '', loading: false }"
@submit="loading = true">
<div>
<label for="code" class="block text-sm font-medium text-secondary-700 dark:text-secondary-300 mb-1">
Authentication Code
</label>
<div class="relative">
<div class="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
<i class="fas fa-key text-secondary-400 dark:text-secondary-600"></i>
</div>
<input
type="text"
id="code"
name="code"
x-model="code"
class="form-input pl-10 w-full"
pattern="[0-9]*"
inputmode="numeric"
maxlength="6"
placeholder="Enter 6-digit code"
required/>
</div>
</div>
<button
type="submit"
class="btn-primary w-full"
x-bind:disabled="code.length !== 6 || loading">
<span x-show="!loading">Verify</span>
<span x-show="loading" class="flex items-center justify-center">
<svg class="animate-spin -ml-1 mr-3 h-5 w-5 text-white" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
<circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
<path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
</svg>
Verifying...
</span>
</button>
<div class="text-center">
<a href="/backup-code" class="text-sm text-primary-600 dark:text-primary-400 hover:text-primary-500 dark:hover:text-primary-300">
Use a backup code instead
</a>
</div>
</form>
</div>
</div>
</div>
}
}