Compare commits

...

3 Commits

Author SHA1 Message Date
Leo Vasanko
d4e5497406 carolina. 2025-07-08 18:05:05 -06:00
Leo Vasanko
e7f0e4ac1b Use async/await, move all css/js to separate files. 2025-07-08 06:33:46 -06:00
Leo Vasanko
28911d117e Remove semicolons 2025-07-08 06:10:47 -06:00
10 changed files with 199 additions and 512 deletions

View File

@ -1,93 +0,0 @@
<!DOCTYPE html>
<html>
<head>
<title>Add Device - Passkey Authentication</title>
<link rel="stylesheet" href="/static/style.css">
<script src="/static/simplewebauthn-browser.min.js"></script>
<script src="/static/qrcodejs/qrcode.min.js"></script>
<script src="/static/awaitable-websocket.js"></script>
</head>
<body>
<div class="container">
<!-- Device Addition View -->
<div id="deviceAdditionView" class="view active">
<h1>📱 Add Device</h1>
<div id="deviceAdditionStatus"></div>
<div id="deviceLinkSection">
<h2>Device Addition Link</h2>
<div class="token-info">
<p><strong>Share this link to add this account to another device:</strong></p>
<div class="qr-container">
<div id="qrCode" class="qr-code"></div>
<p><small>Scan this QR code with your other device</small></p>
</div>
<div class="link-container">
<p class="link-text" id="deviceLinkText">Loading...</p>
<button class="copy-button" onclick="copyDeviceLink()">Copy Link</button>
</div>
<p><small>⚠️ This link expires in 24 hours and can only be used once.</small></p>
<p><strong>Human-readable code:</strong> <code id="deviceToken"></code></p>
</div>
</div>
<button onclick="window.location.href='/auth/profile'" class="btn-secondary">
Back to Profile
</button>
</div>
</div>
<script src="/static/app.js"></script>
<script>
// Initialize the device addition view when page loads
document.addEventListener('DOMContentLoaded', function() {
initializeApp();
// Auto-generate device link when page loads
generateDeviceLink();
});
// Generate device link function
function generateDeviceLink() {
clearStatus('deviceAdditionStatus');
showStatus('deviceAdditionStatus', 'Generating device link...', 'info');
fetch('/api/create-device-link', {
method: 'POST',
credentials: 'include'
})
.then(response => response.json())
.then(result => {
if (result.error) throw new Error(result.error);
// Update UI with the link
document.getElementById('deviceLinkText').textContent = result.addition_link;
document.getElementById('deviceToken').textContent = result.token;
// Store link globally for copy function
window.currentDeviceLink = result.addition_link;
// Generate QR code
const qrCodeEl = document.getElementById('qrCode');
qrCodeEl.innerHTML = '';
new QRCode(qrCodeEl, {
text: result.addition_link,
width: 200,
height: 200,
colorDark: '#000000',
colorLight: '#ffffff',
correctLevel: QRCode.CorrectLevel.M
});
showStatus('deviceAdditionStatus', 'Device link generated successfully!', 'success');
})
.catch(error => {
console.error('Error generating device link:', error);
showStatus('deviceAdditionStatus', `Failed to generate device link: ${error.message}`, 'error');
});
}
</script>
</body>
</html>

View File

@ -84,19 +84,21 @@ function showDeviceAdditionView() {
} }
} }
function showDashboardView() { async function showDashboardView() {
if (window.location.pathname !== '/auth/profile') { if (window.location.pathname !== '/auth/profile') {
window.location.href = '/auth/profile' window.location.href = '/auth/profile'
return return
} }
showView('profileView') showView('profileView')
clearStatus('profileStatus') clearStatus('profileStatus')
loadUserInfo().then(() => {
try {
await loadUserInfo()
updateUserInfo() updateUserInfo()
loadCredentials() await loadCredentials()
}).catch(error => { } catch (error) {
showStatus('profileStatus', `Failed to load user info: ${error.message}`, 'error') showStatus('profileStatus', `Failed to load user info: ${error.message}`, 'error')
}) }
} }
// ======================================== // ========================================

View File

@ -1,106 +0,0 @@
<!DOCTYPE html>
<html>
<head>
<title>Dashboard - Passkey Authentication</title>
<link rel="stylesheet" href="/static/style.css">
<script src="/static/simplewebauthn-browser.min.js"></script>
<script src="/static/qrcodejs/qrcode.min.js"></script>
<script src="/static/awaitable-websocket.js"></script>
</head>
<body>
<div class="container">
<!-- Dashboard View -->
<div id="dashboardView" class="view active">
<h1>👋 Welcome!</h1>
<div id="userInfo" class="user-info"></div>
<div id="dashboardStatus"></div>
<h2>Your Passkeys</h2>
<div id="credentialList" class="credential-list">
<p>Loading credentials...</p>
</div>
<button onclick="addNewCredential()" class="btn-primary">
Add New Passkey
</button>
<button onclick="generateAndShowDeviceLink()" class="btn-secondary">
Generate Device Link
</button>
<button onclick="logout()" class="btn-danger">
Logout
</button>
<!-- Device Addition Section -->
<div id="deviceLinkSection" style="display: none;">
<h2>Device Addition Link</h2>
<div class="token-info">
<p><strong>Share this link to add this account to another device:</strong></p>
<div class="qr-container">
<div id="qrCode" class="qr-code"></div>
<p><small>Scan this QR code with your other device</small></p>
</div>
<div class="link-container">
<p class="link-text" id="deviceLinkText">Loading...</p>
<button class="copy-button" onclick="copyDeviceLink()">Copy Link</button>
</div>
<p><small>⚠️ This link expires in 24 hours and can only be used once.</small></p>
<p><strong>Human-readable code:</strong> <code id="deviceToken"></code></p>
</div>
</div>
</div>
</div>
<script src="/static/app.js"></script>
<script>
// Initialize the dashboard view when page loads
document.addEventListener('DOMContentLoaded', function() {
initializeApp();
});
// Override the generateAndShowDeviceLink function to show the device link section
function generateAndShowDeviceLink() {
clearStatus('dashboardStatus');
fetch('/api/create-device-link', {
method: 'POST',
credentials: 'include'
})
.then(response => response.json())
.then(result => {
if (result.error) throw new Error(result.error);
// Update UI with the link
document.getElementById('deviceLinkText').textContent = result.addition_link;
document.getElementById('deviceToken').textContent = result.token;
// Store link globally for copy function
window.currentDeviceLink = result.addition_link;
// Generate QR code
const qrCodeEl = document.getElementById('qrCode');
qrCodeEl.innerHTML = '';
new QRCode(qrCodeEl, {
text: result.addition_link,
width: 200,
height: 200,
colorDark: '#000000',
colorLight: '#ffffff',
correctLevel: QRCode.CorrectLevel.M
});
// Show the device link section
document.getElementById('deviceLinkSection').style.display = 'block';
showStatus('dashboardStatus', 'Device link generated successfully!', 'success');
})
.catch(error => {
console.error('Error generating device link:', error);
showStatus('dashboardStatus', `Failed to generate device link: ${error.message}`, 'error');
});
}
</script>
</body>
</html>

View File

@ -2,32 +2,32 @@
document.addEventListener('DOMContentLoaded', function() { document.addEventListener('DOMContentLoaded', function() {
// Initialize the app // Initialize the app
initializeApp(); initializeApp()
// Authentication form handler // Authentication form handler
const authForm = document.getElementById('authenticationForm'); const authForm = document.getElementById('authenticationForm')
if (authForm) { if (authForm) {
const authSubmitBtn = authForm.querySelector('button[type="submit"]'); const authSubmitBtn = authForm.querySelector('button[type="submit"]')
authForm.addEventListener('submit', async (ev) => { authForm.addEventListener('submit', async (ev) => {
ev.preventDefault(); ev.preventDefault()
authSubmitBtn.disabled = true; authSubmitBtn.disabled = true
clearStatus('loginStatus'); clearStatus('loginStatus')
try { try {
showStatus('loginStatus', 'Starting authentication...', 'info'); showStatus('loginStatus', 'Starting authentication...', 'info')
await authenticate(); await authenticate()
showStatus('loginStatus', 'Authentication successful!', 'success'); showStatus('loginStatus', 'Authentication successful!', 'success')
// Navigate to profile // Navigate to profile
setTimeout(() => { setTimeout(() => {
window.location.href = '/auth/profile'; window.location.href = '/auth/profile'
}, 1000); }, 1000)
} catch (err) { } catch (err) {
showStatus('loginStatus', `Authentication failed: ${err.message}`, 'error'); showStatus('loginStatus', `Authentication failed: ${err.message}`, 'error')
} finally { } finally {
authSubmitBtn.disabled = false; authSubmitBtn.disabled = false
} }
}); })
} }
}); })

36
static/profile-dialog.css Normal file
View File

@ -0,0 +1,36 @@
/* Profile page dialog styles */
.container.dialog-open {
filter: blur(2px);
pointer-events: none;
user-select: none;
}
/* Dialog styling */
#deviceLinkDialog {
position: fixed;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
z-index: 999;
color: black;
background: white;
border: none;
border-radius: 8px;
box-shadow: 0 4px 20px rgba(0, 0, 0, 0.3);
padding: 2rem;
max-width: 500px;
width: 90%;
max-height: 90vh;
overflow-y: auto;
}
#deviceLinkDialog::backdrop {
background: rgba(0, 0, 0, 0.5);
backdrop-filter: blur(4px);
}
/* Prevent scrolling when dialog is open */
body.dialog-open {
overflow: hidden;
}

View File

@ -3,69 +3,10 @@
<head> <head>
<title>Profile - Passkey Authentication</title> <title>Profile - Passkey Authentication</title>
<link rel="stylesheet" href="/static/style.css"> <link rel="stylesheet" href="/static/style.css">
<link rel="stylesheet" href="/static/profile-dialog.css">
<script src="/static/simplewebauthn-browser.min.js"></script> <script src="/static/simplewebauthn-browser.min.js"></script>
<script src="/static/qrcodejs/qrcode.min.js"></script> <script src="/static/qrcodejs/qrcode.min.js"></script>
<script src="/static/awaitable-websocket.js"></script> <script src="/static/awaitable-websocket.js"></script>
<style>
/* Dialog backdrop and blur effects */
.dialog-backdrop {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
background: rgba(0, 0, 0, 0.5);
backdrop-filter: blur(4px);
z-index: 998;
display: none;
}
.dialog-backdrop.active {
display: block;
}
.container.dialog-open {
filter: blur(2px);
pointer-events: none;
user-select: none;
}
/* Dialog styling */
#deviceLinkDialog {
position: fixed;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
z-index: 999;
background: white;
border: none;
border-radius: 8px;
box-shadow: 0 4px 20px rgba(0, 0, 0, 0.3);
padding: 2rem;
max-width: 500px;
width: 90%;
max-height: 90vh;
overflow-y: auto;
}
#deviceLinkDialog::backdrop {
background: rgba(0, 0, 0, 0.5);
backdrop-filter: blur(4px);
}
/* Dark mode dialog styling */
@media (prefers-color-scheme: dark) {
#deviceLinkDialog {
background: #1a1a1a;
color: white;
}
}
/* Prevent scrolling when dialog is open */
body.dialog-open {
overflow: hidden;
}
</style>
</head> </head>
<body> <body>
<div class="container"> <div class="container">
@ -74,12 +15,12 @@
<h1>👋 Welcome!</h1> <h1>👋 Welcome!</h1>
<div id="userInfo" class="user-info"></div> <div id="userInfo" class="user-info"></div>
<div id="profileStatus"></div> <div id="profileStatus"></div>
<h2>Your Passkeys</h2> <h2>Your Passkeys</h2>
<div id="credentialList" class="credential-list"> <div id="credentialList" class="credential-list">
<p>Loading credentials...</p> <p>Loading credentials...</p>
</div> </div>
<button onclick="addNewCredential()" class="btn-primary"> <button onclick="addNewCredential()" class="btn-primary">
Add New Passkey Add New Passkey
</button> </button>
@ -90,31 +31,27 @@
Logout Logout
</button> </button>
</div> </div>
<!-- Device Link Dialog --> <!-- Device Link Dialog -->
<dialog id="deviceLinkDialog"> <dialog id="deviceLinkDialog">
<h1>📱 Add Device</h1> <h1>📱 Add Device</h1>
<div id="deviceAdditionStatus"></div> <div id="deviceAdditionStatus"></div>
<div id="deviceLinkSection"> <div id="deviceLinkSection">
<h2>Device Addition Link</h2> <h2>Device Addition Link</h2>
<div class="token-info"> <div class="token-info">
<p><strong>Share this link to add this account to another device:</strong></p>
<div class="qr-container"> <div class="qr-container">
<div id="qrCode" class="qr-code"></div> <div id="qrCode" class="qr-code"></div>
<p><small>Scan this QR code with your other device</small></p> <p><a href="#" id="deviceLinkText"></a></p>
</div> </div>
<div class="link-container"> <p>
<p class="link-text" id="deviceLinkText">Loading...</p> <strong>Scan the above code and visit the URL on another device.</strong><br>
<button class="copy-button" onclick="copyDeviceLink()">Copy Link</button> <small>⚠️ Expires in 24 hours and can only be used once.</small>
</div> </p>
<p><small>⚠️ This link expires in 24 hours and can only be used once.</small></p>
</div> </div>
</div> </div>
<button onclick="closeDeviceLinkDialog()" class="btn-secondary"> <button onclick="closeDeviceLinkDialog()" class="btn-secondary">
Close Close
</button> </button>
@ -122,90 +59,6 @@
</div> </div>
<script src="/static/app.js"></script> <script src="/static/app.js"></script>
<script> <script src="/static/profile.js"></script>
// Initialize the profile view when page loads
document.addEventListener('DOMContentLoaded', function() {
initializeApp();
});
// Open device link dialog
function openDeviceLinkDialog() {
const dialog = document.getElementById('deviceLinkDialog');
const container = document.querySelector('.container');
const body = document.body;
// Add blur and disable effects
container.classList.add('dialog-open');
body.classList.add('dialog-open');
dialog.showModal();
generateDeviceLink();
}
// Close device link dialog
function closeDeviceLinkDialog() {
const dialog = document.getElementById('deviceLinkDialog');
const container = document.querySelector('.container');
const body = document.body;
// Remove blur and disable effects
container.classList.remove('dialog-open');
body.classList.remove('dialog-open');
dialog.close();
}
// Generate device link function
function generateDeviceLink() {
clearStatus('deviceAdditionStatus');
showStatus('deviceAdditionStatus', 'Generating device link...', 'info');
fetch('/api/create-device-link', {
method: 'POST',
credentials: 'include'
})
.then(response => response.json())
.then(result => {
if (result.error) throw new Error(result.error);
// Update UI with the link
document.getElementById('deviceLinkText').textContent = result.addition_link;
// Store link globally for copy function
window.currentDeviceLink = result.addition_link;
// Generate QR code
const qrCodeEl = document.getElementById('qrCode');
qrCodeEl.innerHTML = '';
new QRCode(qrCodeEl, {
text: result.addition_link,
width: 200,
height: 200,
colorDark: '#000000',
colorLight: '#ffffff',
correctLevel: QRCode.CorrectLevel.M
});
})
.catch(error => {
console.error('Error generating device link:', error);
showStatus('deviceAdditionStatus', `Failed to generate device link: ${error.message}`, 'error');
});
}
// Close dialog when clicking outside
document.getElementById('deviceLinkDialog').addEventListener('click', function(e) {
if (e.target === this) {
closeDeviceLinkDialog();
}
});
// Close dialog when pressing Escape key
document.addEventListener('keydown', function(e) {
if (e.key === 'Escape' && document.getElementById('deviceLinkDialog').open) {
closeDeviceLinkDialog();
}
});
</script>
</body> </body>
</html> </html>

View File

@ -2,96 +2,107 @@
document.addEventListener('DOMContentLoaded', function() { document.addEventListener('DOMContentLoaded', function() {
// Initialize the app // Initialize the app
initializeApp(); initializeApp()
// Setup dialog event handlers // Setup dialog event handlers
setupDialogHandlers(); setupDialogHandlers()
}); })
// Setup dialog event handlers // Setup dialog event handlers
function setupDialogHandlers() { function setupDialogHandlers() {
// Close dialog when clicking outside // Close dialog when clicking outside
const dialog = document.getElementById('deviceLinkDialog'); const dialog = document.getElementById('deviceLinkDialog')
if (dialog) { if (dialog) {
dialog.addEventListener('click', function(e) { dialog.addEventListener('click', function(e) {
if (e.target === this) { if (e.target === this) {
closeDeviceLinkDialog(); closeDeviceLinkDialog()
} }
}); })
} }
// Close dialog when pressing Escape key // Close dialog when pressing Escape key
document.addEventListener('keydown', function(e) { document.addEventListener('keydown', function(e) {
const dialog = document.getElementById('deviceLinkDialog'); const dialog = document.getElementById('deviceLinkDialog')
if (e.key === 'Escape' && dialog && dialog.open) { if (e.key === 'Escape' && dialog && dialog.open) {
closeDeviceLinkDialog(); closeDeviceLinkDialog()
} }
}); })
} }
// Open device link dialog // Open device link dialog
function openDeviceLinkDialog() { function openDeviceLinkDialog() {
const dialog = document.getElementById('deviceLinkDialog'); const dialog = document.getElementById('deviceLinkDialog')
const container = document.querySelector('.container'); const container = document.querySelector('.container')
const body = document.body; const body = document.body
if (dialog && container && body) { if (dialog && container && body) {
// Add blur and disable effects // Add blur and disable effects
container.classList.add('dialog-open'); container.classList.add('dialog-open')
body.classList.add('dialog-open'); body.classList.add('dialog-open')
dialog.showModal(); dialog.showModal()
generateDeviceLink(); generateDeviceLink()
} }
} }
// Close device link dialog // Close device link dialog
function closeDeviceLinkDialog() { function closeDeviceLinkDialog() {
const dialog = document.getElementById('deviceLinkDialog'); const dialog = document.getElementById('deviceLinkDialog')
const container = document.querySelector('.container'); const container = document.querySelector('.container')
const body = document.body; const body = document.body
if (dialog && container && body) { if (dialog && container && body) {
// Remove blur and disable effects // Remove blur and disable effects
container.classList.remove('dialog-open'); container.classList.remove('dialog-open')
body.classList.remove('dialog-open'); body.classList.remove('dialog-open')
dialog.close(); dialog.close()
} }
} }
// Generate device link function // Generate device link function
function generateDeviceLink() { async function generateDeviceLink() {
clearStatus('deviceAdditionStatus'); clearStatus('deviceAdditionStatus')
showStatus('deviceAdditionStatus', 'Generating device link...', 'info'); showStatus('deviceAdditionStatus', 'Generating device link...', 'info')
fetch('/api/create-device-link', { try {
method: 'POST', const response = await fetch('/api/create-device-link', {
credentials: 'include' method: 'POST',
}) credentials: 'include'
.then(response => response.json()) })
.then(result => {
if (result.error) throw new Error(result.error); const result = await response.json()
if (result.error) {
throw new Error(result.error)
}
// Update UI with the link // Update UI with the link
const deviceLinkText = document.getElementById('deviceLinkText'); const deviceLinkText = document.getElementById('deviceLinkText')
const deviceToken = document.getElementById('deviceToken');
if (deviceLinkText) { if (deviceLinkText) {
deviceLinkText.textContent = result.addition_link; deviceLinkText.href = result.addition_link
deviceLinkText.textContent = result.addition_link.replace(/^[a-z]+:\/\//i, '')
// Add click event listener for copying the link
deviceLinkText.addEventListener('click', function(e) {
e.preventDefault() // Prevent navigation
navigator.clipboard.writeText(deviceLinkText.href).then(() => {
closeDeviceLinkDialog() // Close the dialog
showStatus('deviceAdditionStatus', 'Device registration link copied', 'success') // Display status
}).catch(() => {
showStatus('deviceAdditionStatus', 'Failed to copy device registration link', 'error')
})
})
} }
if (deviceToken) {
deviceToken.textContent = result.token;
}
// Store link globally for copy function // Store link globally for copy function
window.currentDeviceLink = result.addition_link; window.currentDeviceLink = result.addition_link
// Generate QR code // Generate QR code
const qrCodeEl = document.getElementById('qrCode'); const qrCodeEl = document.getElementById('qrCode')
if (qrCodeEl && typeof QRCode !== 'undefined') { if (qrCodeEl && typeof QRCode !== 'undefined') {
qrCodeEl.innerHTML = ''; qrCodeEl.innerHTML = ''
new QRCode(qrCodeEl, { new QRCode(qrCodeEl, {
text: result.addition_link, text: result.addition_link,
width: 200, width: 200,
@ -99,17 +110,15 @@ function generateDeviceLink() {
colorDark: '#000000', colorDark: '#000000',
colorLight: '#ffffff', colorLight: '#ffffff',
correctLevel: QRCode.CorrectLevel.M correctLevel: QRCode.CorrectLevel.M
}); })
} }
showStatus('deviceAdditionStatus', 'Device link generated successfully!', 'success'); clearStatus('deviceAdditionStatus')
}) } catch (error) {
.catch(error => { showStatus('deviceAdditionStatus', `Failed to generate device link: ${error.message}`, 'error')
console.error('Error generating device link:', error); }
showStatus('deviceAdditionStatus', `Failed to generate device link: ${error.message}`, 'error');
});
} }
// Make functions available globally for onclick handlers // Make functions available globally for onclick handlers
window.openDeviceLinkDialog = openDeviceLinkDialog; window.openDeviceLinkDialog = openDeviceLinkDialog
window.closeDeviceLinkDialog = closeDeviceLinkDialog; window.closeDeviceLinkDialog = closeDeviceLinkDialog

View File

@ -2,34 +2,34 @@
document.addEventListener('DOMContentLoaded', function() { document.addEventListener('DOMContentLoaded', function() {
// Initialize the app // Initialize the app
initializeApp(); initializeApp()
// Registration form handler // Registration form handler
const regForm = document.getElementById('registrationForm'); const regForm = document.getElementById('registrationForm')
if (regForm) { if (regForm) {
const regSubmitBtn = regForm.querySelector('button[type="submit"]'); const regSubmitBtn = regForm.querySelector('button[type="submit"]')
regForm.addEventListener('submit', async (ev) => { regForm.addEventListener('submit', async (ev) => {
ev.preventDefault(); ev.preventDefault()
regSubmitBtn.disabled = true; regSubmitBtn.disabled = true
clearStatus('registerStatus'); clearStatus('registerStatus')
const user_name = (new FormData(regForm)).get('username'); const user_name = (new FormData(regForm)).get('username')
try { try {
showStatus('registerStatus', 'Starting registration...', 'info'); showStatus('registerStatus', 'Starting registration...', 'info')
await register(user_name); await register(user_name)
showStatus('registerStatus', `Registration successful for ${user_name}!`, 'success'); showStatus('registerStatus', `Registration successful for ${user_name}!`, 'success')
// Auto-login after successful registration // Auto-login after successful registration
setTimeout(() => { setTimeout(() => {
window.location.href = '/auth/profile'; window.location.href = '/auth/profile'
}, 1500); }, 1500)
} catch (err) { } catch (err) {
showStatus('registerStatus', `Registration failed: ${err.message}`, 'error'); showStatus('registerStatus', `Registration failed: ${err.message}`, 'error')
} finally { } finally {
regSubmitBtn.disabled = false; regSubmitBtn.disabled = false
} }
}); })
} }
}); })

View File

@ -1,7 +1,7 @@
/* Passkey Authentication - Main Styles */ /* Passkey Authentication - Main Styles */
body { body {
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
margin: 0; margin: 0;
padding: 0; padding: 0;
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
@ -11,7 +11,7 @@ body {
justify-content: center; justify-content: center;
} }
.container { .container {
background: white; background: white;
padding: 40px; padding: 40px;
border-radius: 15px; border-radius: 15px;
@ -59,7 +59,7 @@ input[type="text"]:focus {
border-color: #667eea; border-color: #667eea;
} }
button { button {
width: 100%; width: 100%;
padding: 15px; padding: 15px;
margin-bottom: 15px; margin-bottom: 15px;
@ -326,18 +326,3 @@ button:disabled {
color: #495057; color: #495057;
margin: 0; margin: 0;
} }
.copy-button {
background: #28a745;
color: white;
border: none;
padding: 8px 16px;
border-radius: 4px;
cursor: pointer;
font-size: 14px;
margin-top: 10px;
}
.copy-button:hover {
background: #218838;
}

View File

@ -2,57 +2,58 @@
// Initialize the app based on current page // Initialize the app based on current page
function initializeApp() { function initializeApp() {
checkExistingSession(); checkExistingSession()
} }
// Show status message // Show status message
function showStatus(elementId, message, type = 'info') { function showStatus(elementId, message, type = 'info') {
const statusEl = document.getElementById(elementId); const statusEl = document.getElementById(elementId)
if (statusEl) { if (statusEl) {
statusEl.innerHTML = `<div class="status ${type}">${message}</div>`; statusEl.innerHTML = `<div class="status ${type}">${message}</div>`
} }
} }
// Clear status message // Clear status message
function clearStatus(elementId) { function clearStatus(elementId) {
const statusEl = document.getElementById(elementId); const statusEl = document.getElementById(elementId)
if (statusEl) { if (statusEl) {
statusEl.innerHTML = ''; statusEl.innerHTML = ''
} }
} }
// Check if user is already logged in on page load // Check if user is already logged in on page load
async function checkExistingSession() { async function checkExistingSession() {
const isLoggedIn = await validateStoredToken(); const isLoggedIn = await validateStoredToken()
const path = window.location.pathname; const path = window.location.pathname
// Protected routes that require authentication // Protected routes that require authentication
const protectedRoutes = ['/auth/profile']; const protectedRoutes = ['/auth/profile']
if (isLoggedIn) { if (isLoggedIn) {
// User is logged in // User is logged in
if (path === '/auth/login' || path === '/auth/register' || path === '/') { if (path === '/auth/login' || path === '/auth/register' || path === '/') {
// Redirect to profile if accessing login/register pages while logged in // Redirect to profile if accessing login/register pages while logged in
window.location.href = '/auth/profile'; window.location.href = '/auth/profile'
} else if (path === '/auth/add-device') { } else if (path === '/auth/add-device') {
// Redirect old add-device route to profile // Redirect old add-device route to profile
window.location.href = '/auth/profile'; window.location.href = '/auth/profile'
} else if (protectedRoutes.includes(path)) { } else if (protectedRoutes.includes(path)) {
// Stay on current protected page and load user data // Stay on current protected page and load user data
if (path === '/auth/profile') { if (path === '/auth/profile') {
loadUserInfo().then(() => { try {
updateUserInfo(); await loadUserInfo()
loadCredentials(); updateUserInfo()
}).catch(error => { await loadCredentials()
showStatus('profileStatus', `Failed to load user info: ${error.message}`, 'error'); } catch (error) {
}); showStatus('profileStatus', `Failed to load user info: ${error.message}`, 'error')
}
} }
} }
} else { } else {
// User is not logged in // User is not logged in
if (protectedRoutes.includes(path) || path === '/auth/add-device') { if (protectedRoutes.includes(path) || path === '/auth/add-device') {
// Redirect to login if accessing protected pages without authentication // Redirect to login if accessing protected pages without authentication
window.location.href = '/auth/login'; window.location.href = '/auth/login'
} }
} }
} }
@ -63,12 +64,12 @@ async function validateStoredToken() {
const response = await fetch('/api/validate-token', { const response = await fetch('/api/validate-token', {
method: 'GET', method: 'GET',
credentials: 'include' credentials: 'include'
}); })
const result = await response.json(); const result = await response.json()
return result.status === 'success'; return result.status === 'success'
} catch (error) { } catch (error) {
return false; return false
} }
} }
@ -76,28 +77,28 @@ async function validateStoredToken() {
async function copyDeviceLink() { async function copyDeviceLink() {
try { try {
if (window.currentDeviceLink) { if (window.currentDeviceLink) {
await navigator.clipboard.writeText(window.currentDeviceLink); await navigator.clipboard.writeText(window.currentDeviceLink)
const copyButton = document.querySelector('.copy-button'); const copyButton = document.querySelector('.copy-button')
if (copyButton) { if (copyButton) {
const originalText = copyButton.textContent; const originalText = copyButton.textContent
copyButton.textContent = 'Copied!'; copyButton.textContent = 'Copied!'
copyButton.style.background = '#28a745'; copyButton.style.background = '#28a745'
setTimeout(() => { setTimeout(() => {
copyButton.textContent = originalText; copyButton.textContent = originalText
copyButton.style.background = '#28a745'; copyButton.style.background = '#28a745'
}, 2000); }, 2000)
} }
} }
} catch (error) { } catch (error) {
console.error('Failed to copy link:', error); console.error('Failed to copy link:', error)
const linkText = document.getElementById('deviceLinkText'); const linkText = document.getElementById('deviceLinkText')
if (linkText) { if (linkText) {
const range = document.createRange(); const range = document.createRange()
range.selectNode(linkText); range.selectNode(linkText)
window.getSelection().removeAllRanges(); window.getSelection().removeAllRanges()
window.getSelection().addRange(range); window.getSelection().addRange(range)
} }
} }
} }