feat: Add complete user authentication system with JWT and mandatory login

Implemented a comprehensive authentication system requiring all users to be
logged in to access the web interface. Features include:

Backend:
- JWT-based authentication with 7-day token expiration
- bcrypt password hashing with 72-byte limit handling
- User management with JSON file storage (config/users.json)
- Pydantic models for validation (UserCreate, UserLogin, User, Token)
- Authentication endpoints: register, login, me, logout
- Protected route dependency with HTTPBearer security

Frontend:
- Login/register page with dual-tab interface (/login)
- Client-side authentication check with automatic redirect
- All content hidden by default, shown only after auth validation
- User info display with logout button
- Main content and tabs hidden when not authenticated
- Auto-redirect to /login if token missing or invalid

Security:
- Password truncation to 72 bytes (bcrypt limitation)
- Token verification on each page load
- Automatic logout and redirect on token expiry
- Username-to-SHA256 user ID generation

Dependencies:
- passlib[bcrypt]==1.7.4
- python-jose[cryptography]==3.3.0
- bcrypt<4.0

Generated with [Claude Code](https://claude.com/claude-code)
via [Happy](https://happy.engineering)

Co-Authored-By: Claude <noreply@anthropic.com>
Co-Authored-By: Happy <yesreply@happy.engineering>
This commit is contained in:
root
2026-01-29 17:25:50 +00:00
parent c1c31d7685
commit ef72e221be
10 changed files with 974 additions and 14 deletions
+142
View File
@@ -0,0 +1,142 @@
/**
* Authentication management for web interface
*/
// Use relative path for API
const AUTH_API_BASE = '/api';
// Check if user is authenticated
async function checkAuth() {
const token = localStorage.getItem('auth_token');
const userStr = localStorage.getItem('user');
if (!token) {
// Redirect to login page instead of just showing prompt
redirectToLogin();
return false;
}
// Verify token with server
try {
const response = await fetch(`${AUTH_API_BASE}/auth/me`, {
headers: {
'Authorization': `Bearer ${token}`
}
});
if (response.ok) {
const data = await response.json();
showUserInfo(data.user);
showMainContent();
return true;
} else {
// Token invalid, remove it and redirect
localStorage.removeItem('auth_token');
localStorage.removeItem('user');
redirectToLogin();
return false;
}
} catch (error) {
console.error('Auth check error:', error);
// On error, redirect to login
redirectToLogin();
return false;
}
}
// Redirect to login page
function redirectToLogin() {
// Only redirect if not already on login page
if (!window.location.pathname.includes('/login')) {
window.location.href = '/login';
}
}
// Show user info when authenticated
function showUserInfo(user) {
const userInfo = document.getElementById('userInfo');
const loginPrompt = document.getElementById('loginPrompt');
const mainTabs = document.getElementById('mainTabs');
const currentUser = document.getElementById('currentUser');
if (userInfo) userInfo.style.display = 'flex';
if (loginPrompt) loginPrompt.style.display = 'none';
if (mainTabs) mainTabs.style.visibility = 'visible';
if (currentUser) currentUser.textContent = user.full_name || user.username;
}
// Show main content (only when authenticated)
function showMainContent() {
const mainContent = document.getElementById('main-content');
if (mainContent) mainContent.style.display = 'block';
}
// Hide main content (when not authenticated)
function hideMainContent() {
const mainContent = document.getElementById('main-content');
if (mainContent) mainContent.style.display = 'none';
}
// Show login prompt when not authenticated (not used anymore - we redirect instead)
function showLoginPrompt() {
const userInfo = document.getElementById('userInfo');
const loginPrompt = document.getElementById('loginPrompt');
const mainTabs = document.getElementById('mainTabs');
if (userInfo) userInfo.style.display = 'none';
if (loginPrompt) loginPrompt.style.display = 'block';
if (mainTabs) mainTabs.style.visibility = 'hidden';
// Hide main content
hideMainContent();
}
// Handle logout
async function handleLogout() {
if (!confirm('Êtes-vous sûr de vouloir vous déconnecter?')) {
return;
}
// Remove token from localStorage
localStorage.removeItem('auth_token');
localStorage.removeItem('user');
// Call logout endpoint
try {
await fetch(`${AUTH_API_BASE}/auth/logout`, { method: 'POST' });
} catch (error) {
console.error('Logout error:', error);
}
// Redirect to login page
window.location.href = '/login';
}
// Add authorization header to all fetch requests
function addAuthHeader(options = {}) {
const token = localStorage.getItem('auth_token');
if (token) {
options.headers = options.headers || {};
options.headers['Authorization'] = `Bearer ${token}`;
}
return options;
}
// Wrapper for fetch with auth
async function authFetch(url, options = {}) {
options = addAuthHeader(options);
return fetch(url, options);
}
// Make functions available globally
window.checkAuth = checkAuth;
window.showUserInfo = showUserInfo;
window.showLoginPrompt = showLoginPrompt;
window.handleLogout = handleLogout;
window.authFetch = authFetch;
window.addAuthHeader = addAuthHeader;
// Check authentication on page load
document.addEventListener('DOMContentLoaded', () => {
checkAuth();
});