Files
edh-stats/frontend/public/js/auth-check.js
Michael Skrynski a2b9827279 Fix security vulnerability: validate auth tokens with backend
SECURITY FIX:
- Removed unsafe client-side only token check
- Added server-side token validation via /api/auth/me endpoint
- Prevents tokens spoofed in localStorage from granting access
- Only redirects if token is verified as valid by backend

How it works:
- When user visits login/register page with token in storage
- auth-check.js makes API call to /api/auth/me with token
- Backend JWT middleware verifies token signature and expiration
- If valid, user is redirected to dashboard
- If invalid/expired, token is cleared and user stays on login page
- If network error, user stays on login page (no redirect)
2026-01-23 09:45:34 +01:00

51 lines
1.6 KiB
JavaScript

// Authentication Check - Validates token with backend and redirects if already authenticated
// Only runs on login.html and register.html pages
(function() {
const currentPage = window.location.pathname.split('/').pop() || 'index.html'
const authPages = ['login.html', 'register.html']
// Only run on auth pages
if (!authPages.includes(currentPage)) {
return
}
// Check if token exists in storage
const token = localStorage.getItem('edh-stats-token') || sessionStorage.getItem('edh-stats-token')
// If no token, user is already logged out, no need to check
if (!token) {
return
}
// Validate token with backend before redirecting
validateToken(token)
async function validateToken(token) {
try {
const response = await fetch('/api/auth/me', {
method: 'GET',
headers: {
'Authorization': `Bearer ${token}`,
'Content-Type': 'application/json'
}
})
if (response.ok) {
// Token is valid, user is authenticated - redirect to dashboard
window.location.href = '/dashboard.html'
} else if (response.status === 401) {
// Token is invalid or expired, clear storage
localStorage.removeItem('edh-stats-token')
sessionStorage.removeItem('edh-stats-token')
// User stays on login/register page
} else {
// Other error, log but don't block user
console.warn('Token validation failed with status:', response.status)
}
} catch (error) {
// Network error or other issue, log but don't block user
console.warn('Token validation error:', error)
}
}
})()