migrating vendor frontend to new architecture

This commit is contained in:
2025-10-28 22:58:55 +01:00
parent b0cc0385f8
commit cd5097fc04
28 changed files with 312 additions and 228 deletions

View File

@@ -1,14 +1,8 @@
// static/admin/js/login.js
// Log levels: 0 = None, 1 = Error, 2 = Warning, 3 = Info, 4 = Debug
const LOG_LEVEL = 4; // Set to 4 for full debugging, 1 for errors only
const log = {
error: (...args) => LOG_LEVEL >= 1 && console.error('❌ [ERROR]', ...args),
warn: (...args) => LOG_LEVEL >= 2 && console.warn('⚠️ [WARN]', ...args),
info: (...args) => LOG_LEVEL >= 3 && console.info(' [INFO]', ...args),
debug: (...args) => LOG_LEVEL >= 4 && console.log('🔍 [DEBUG]', ...args)
};
// ✅ Use centralized logger - ONE LINE!
// Create custom logger for login page
const loginLog = window.LogConfig.createLogger('LOGIN');
function adminLogin() {
return {
@@ -23,37 +17,37 @@ function adminLogin() {
errors: {},
init() {
log.info('Login page initializing...');
log.debug('Current pathname:', window.location.pathname);
log.debug('Current URL:', window.location.href);
loginLog.info('=== LOGIN PAGE INITIALIZING ===');
loginLog.debug('Current pathname:', window.location.pathname);
loginLog.debug('Current URL:', window.location.href);
// Just set theme - NO auth checking, NO token clearing!
this.dark = localStorage.getItem('theme') === 'dark';
log.debug('Dark mode:', this.dark);
loginLog.debug('Dark mode:', this.dark);
// DON'T clear tokens on init!
// If user lands here with a valid token, they might be navigating manually
// or got redirected. Let them try to login or navigate away.
const token = localStorage.getItem('admin_token');
if (token) {
log.warn('Found existing token on login page');
log.debug('Token preview:', token.substring(0, 20) + '...');
log.info('Not clearing token - user may have navigated here manually');
loginLog.warn('Found existing token on login page');
loginLog.debug('Token preview:', token.substring(0, 20) + '...');
loginLog.info('Not clearing token - user may have navigated here manually');
} else {
log.debug('No existing token found');
loginLog.debug('No existing token found');
}
log.info('Login page initialization complete');
loginLog.info('=== LOGIN PAGE INITIALIZATION COMPLETE ===');
},
clearTokens() {
log.debug('Clearing all auth tokens...');
loginLog.debug('Clearing all auth tokens...');
const tokensBefore = {
admin_token: !!localStorage.getItem('admin_token'),
admin_user: !!localStorage.getItem('admin_user'),
token: !!localStorage.getItem('token')
};
log.debug('Tokens before clear:', tokensBefore);
loginLog.debug('Tokens before clear:', tokensBefore);
localStorage.removeItem('admin_token');
localStorage.removeItem('admin_user');
@@ -64,67 +58,77 @@ function adminLogin() {
admin_user: !!localStorage.getItem('admin_user'),
token: !!localStorage.getItem('token')
};
log.debug('Tokens after clear:', tokensAfter);
loginLog.debug('Tokens after clear:', tokensAfter);
},
clearErrors() {
log.debug('Clearing form errors');
loginLog.debug('Clearing form errors');
this.error = null;
this.success = null;
this.errors = {};
},
validateForm() {
log.debug('Validating login form...');
loginLog.debug('Validating login form...');
this.clearErrors();
let isValid = true;
if (!this.credentials.username.trim()) {
this.errors.username = 'Username is required';
log.warn('Validation failed: Username is required');
loginLog.warn('Validation failed: Username is required');
isValid = false;
}
if (!this.credentials.password) {
this.errors.password = 'Password is required';
log.warn('Validation failed: Password is required');
loginLog.warn('Validation failed: Password is required');
isValid = false;
} else if (this.credentials.password.length < 6) {
this.errors.password = 'Password must be at least 6 characters';
log.warn('Validation failed: Password too short');
loginLog.warn('Validation failed: Password too short');
isValid = false;
}
log.info('Form validation result:', isValid ? 'VALID' : 'INVALID');
loginLog.info('Form validation result:', isValid ? 'VALID' : 'INVALID');
return isValid;
},
async handleLogin() {
log.info('=== LOGIN ATTEMPT STARTED ===');
loginLog.info('=== LOGIN ATTEMPT STARTED ===');
if (!this.validateForm()) {
log.warn('Form validation failed, aborting login');
loginLog.warn('Form validation failed, aborting login');
return;
}
this.loading = true;
this.clearErrors();
log.debug('Login state set to loading');
loginLog.debug('Login state set to loading');
try {
log.info('Calling login API endpoint...');
log.debug('Username:', this.credentials.username);
log.debug('API endpoint: /api/v1/admin/auth/login');
loginLog.info('Calling login API endpoint...');
loginLog.debug('Username:', this.credentials.username);
const startTime = Date.now();
const response = await apiClient.post('/admin/auth/login', {
const url = '/admin/auth/login';
const payload = {
username: this.credentials.username.trim(),
password: this.credentials.password
});
const duration = Date.now() - startTime;
};
log.info(`Login API response received in ${duration}ms`);
log.debug('Response structure:', {
window.LogConfig.logApiCall('POST', url, { username: payload.username }, 'request');
const startTime = performance.now();
const response = await apiClient.post(url, payload);
const duration = performance.now() - startTime;
window.LogConfig.logApiCall('POST', url, {
hasToken: !!response.access_token,
user: response.user?.username
}, 'response');
window.LogConfig.logPerformance('Login', duration);
loginLog.info(`Login API response received in ${duration}ms`);
loginLog.debug('Response structure:', {
hasToken: !!response.access_token,
hasUser: !!response.user,
userRole: response.user?.role,
@@ -133,27 +137,27 @@ function adminLogin() {
// Validate response
if (!response.access_token) {
log.error('Invalid response: No access token');
loginLog.error('Invalid response: No access token');
throw new Error('Invalid response from server - no token');
}
if (response.user && response.user.role !== 'admin') {
log.error('Authorization failed: User is not admin', {
loginLog.error('Authorization failed: User is not admin', {
actualRole: response.user.role
});
throw new Error('Access denied. Admin privileges required.');
}
log.info('Login successful, storing authentication data...');
loginLog.info('Login successful, storing authentication data...');
// Store authentication data
localStorage.setItem('admin_token', response.access_token);
localStorage.setItem('token', response.access_token);
log.debug('Token stored, length:', response.access_token.length);
loginLog.debug('Token stored, length:', response.access_token.length);
if (response.user) {
localStorage.setItem('admin_user', JSON.stringify(response.user));
log.debug('User data stored:', {
loginLog.debug('User data stored:', {
username: response.user.username,
role: response.user.role,
id: response.user.id
@@ -163,7 +167,7 @@ function adminLogin() {
// Verify storage
const storedToken = localStorage.getItem('admin_token');
const storedUser = localStorage.getItem('admin_user');
log.info('Storage verification:', {
loginLog.info('Storage verification:', {
tokenStored: !!storedToken,
userStored: !!storedUser,
tokenLength: storedToken?.length
@@ -171,44 +175,41 @@ function adminLogin() {
// Show success message
this.success = 'Login successful! Redirecting...';
log.info('Success message displayed to user');
loginLog.info('Success message displayed to user');
log.info('Redirecting to dashboard immediately...');
log.info('=== EXECUTING REDIRECT ===');
log.debug('Target URL: /admin/dashboard');
log.debug('Redirect method: window.location.href');
loginLog.info('Redirecting to dashboard immediately...');
loginLog.info('=== EXECUTING REDIRECT ===');
loginLog.debug('Target URL: /admin/dashboard');
loginLog.debug('Redirect method: window.location.href');
// Use href instead of replace to allow back button
// But redirect IMMEDIATELY - don't wait!
window.location.href = '/admin/dashboard';
} catch (error) {
log.error('Login failed:', error);
log.error('Error details:', {
message: error.message,
name: error.name,
stack: error.stack
});
window.LogConfig.logError(error, 'Login');
this.error = error.message || 'Invalid username or password. Please try again.';
log.info('Error message displayed to user:', this.error);
loginLog.info('Error message displayed to user:', this.error);
// Only clear tokens on login FAILURE
this.clearTokens();
log.info('Tokens cleared after error');
loginLog.info('Tokens cleared after error');
} finally {
this.loading = false;
log.debug('Login state set to not loading');
log.info('=== LOGIN ATTEMPT FINISHED ===');
loginLog.debug('Login state set to not loading');
loginLog.info('=== LOGIN ATTEMPT FINISHED ===');
}
},
toggleDarkMode() {
log.debug('Toggling dark mode...');
loginLog.debug('Toggling dark mode...');
this.dark = !this.dark;
localStorage.setItem('theme', this.dark ? 'dark' : 'light');
log.info('Dark mode:', this.dark ? 'ON' : 'OFF');
loginLog.info('Dark mode:', this.dark ? 'ON' : 'OFF');
}
}
}
}
loginLog.info('Login module loaded');