Skip to content

🛡️ Warracker is an open source, self-hostable warranty tracker to monitor expirations, store receipts, files. You own the data, your rules!

Updated Accounts Settings

sassanix4f3bff83a935
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 25e652f..dc62dc0 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -1,5 +1,15 @@
# Changelog
+## [0.9.8.9] - 2025-04-03
+
+### Added
+- **Settings Page:** Added a new display section within the "Account Settings" card (`settings-new.html`) to show the current user's First Name, Last Name, and Email.
+
+### Changed
+- **Settings Page:** The new user information display now updates instantly when the user saves changes to their profile (First/Last Name) without requiring a page refresh (`settings-new.js`).
+- **Backend API:** Modified the `/api/auth/user` GET endpoint (`backend/app.py`) to query the database and return the full user profile, including `first_name` and `last_name`, instead of just the basic information available from the authentication token. This ensures the settings page can display the complete, up-to-date user details.
+- **Styling:** Added optional CSS rules (`settings-styles.css`) to style the new user information display area on the settings page.
+
## [0.9.8.8] - 2025-04-03
### Fixed
diff --git a/backend/app.py b/backend/app.py
index 5a1a2d2..4dc1c87 100644
--- a/backend/app.py
+++ b/backend/app.py
@@ -591,17 +591,40 @@ def validate_token():
@app.route('/api/auth/user', methods=['GET'])
@token_required
def get_user():
+ conn = None
try:
- user = request.user
- return jsonify({
- 'id': user['id'],
- 'username': user['username'],
- 'email': user['email'],
- 'is_admin': user['is_admin']
- }), 200
+ user_id = request.user['id'] # Get user ID from the decorator
+
+ # --- ADD DATABASE QUERY ---
+ conn = get_db_connection()
+ with conn.cursor() as cur:
+ cur.execute(
+ 'SELECT id, username, email, first_name, last_name, is_admin FROM users WHERE id = %s',
+ (user_id,)
+ )
+ user_data = cur.fetchone()
+ # --- END DATABASE QUERY ---
+
+ if not user_data:
+ return jsonify({'message': 'User not found!'}), 404
+
+ # Map database columns to a dictionary
+ columns = ['id', 'username', 'email', 'first_name', 'last_name', 'is_admin']
+ user_info = dict(zip(columns, user_data))
+
+ # Return the full user information
+ return jsonify(user_info), 200
+
except Exception as e:
logger.error(f"Get user error: {e}")
+ # Optionally rollback if there was an error during DB interaction
+ # if conn:
+ # conn.rollback() # Not strictly needed for SELECT, but good practice if errors occur
return jsonify({'message': 'Failed to retrieve user information!'}), 500
+ finally:
+ # Release the connection back to the pool
+ if conn:
+ release_db_connection(conn)
@app.route('/api/auth/password/reset-request', methods=['POST'])
def request_password_reset():
diff --git a/frontend/settings-new.html b/frontend/settings-new.html
index cac1c1c..8ff6da2 100644
--- a/frontend/settings-new.html
+++ b/frontend/settings-new.html
@@ -378,6 +378,10 @@
<h3>Account Settings</h3>
</div>
<div class="card-body">
+ <div id="currentUserInfoDisplay" class="current-user-info" style="margin-bottom: 20px; padding-bottom: 15px; border-bottom: 1px solid var(--border-color);">
+ <p style="margin: 0; font-size: 1.1rem;"><strong>Editing Profile for:</strong> <span id="currentUserNameDisplay" style="font-weight: normal;">Loading...</span></p>
+ <p style="margin: 5px 0 0 0; font-size: 0.9rem; color: var(--text-muted);">Your email: <span id="currentUserEmailDisplay">Loading...</span></p>
+ </div>
<form id="profileForm">
<div class="form-group">
<label for="firstName">First Name</label>
diff --git a/frontend/settings-new.js b/frontend/settings-new.js
index b1c2a3a..a79f216 100644
--- a/frontend/settings-new.js
+++ b/frontend/settings-new.js
@@ -405,25 +405,36 @@ function setupCriticalEventListeners() {
*/
async function loadUserData() {
showLoading();
-
+ // Get the new display elements
+ const userNameDisplay = document.getElementById('currentUserNameDisplay');
+ const userEmailDisplay = document.getElementById('currentUserEmailDisplay');
+
try {
// Get user from localStorage first
const currentUser = window.auth.getCurrentUser();
-
+
if (currentUser) {
// Populate form fields
- firstNameInput.value = currentUser.first_name || '';
- lastNameInput.value = currentUser.last_name || '';
- emailInput.value = currentUser.email || '';
-
+ if (firstNameInput) firstNameInput.value = currentUser.first_name || ''; // Add null checks
+ if (lastNameInput) lastNameInput.value = currentUser.last_name || ''; // Add null checks
+ if (emailInput) emailInput.value = currentUser.email || ''; // Add null checks
+
+ // --- UPDATE DISPLAY ELEMENT (Initial Load) ---
+ const displayName = `${currentUser.first_name || ''} ${currentUser.last_name || ''}`.trim() || currentUser.username || 'User';
+ if (userNameDisplay) userNameDisplay.textContent = displayName;
+ if (userEmailDisplay) userEmailDisplay.textContent = currentUser.email || 'N/A';
+ // --- END UPDATE ---
+
// Check if user is admin and show admin section
if (currentUser.is_admin) {
- adminSection.style.display = 'block';
- loadUsers();
- loadSiteSettings();
+ if (adminSection) adminSection.style.display = 'block';
+ if (adminSection && adminSection.style.display === 'block') {
+ if (usersTableBody) loadUsers();
+ if (registrationEnabled) loadSiteSettings();
+ }
}
}
-
+
// Fetch fresh user data from API
try {
const response = await fetch('/api/auth/user', {
@@ -432,47 +443,50 @@ async function loadUserData() {
'Authorization': `Bearer ${window.auth.getToken()}`
}
});
-
+
if (response.ok) {
const userData = await response.json();
-
+
// Update form fields with fresh data
- firstNameInput.value = userData.first_name || '';
- lastNameInput.value = userData.last_name || '';
- emailInput.value = userData.email || '';
-
+ if (firstNameInput) firstNameInput.value = userData.first_name || ''; // Add null checks
+ if (lastNameInput) lastNameInput.value = userData.last_name || ''; // Add null checks
+ if (emailInput) emailInput.value = userData.email || ''; // Add null checks
+
+ // --- UPDATE DISPLAY ELEMENT (After API Load) ---
+ const displayName = `${userData.first_name || ''} ${userData.last_name || ''}`.trim() || userData.username || 'User';
+ if (userNameDisplay) userNameDisplay.textContent = displayName;
+ if (userEmailDisplay) userEmailDisplay.textContent = userData.email || 'N/A';
+ // --- END UPDATE ---
+
// Show admin section if user is admin
if (userData.is_admin) {
- if (adminSection) {
- adminSection.style.display = 'block';
- }
-
- // Only try to load admin data if the elements exist
- // This prevents errors when the admin elements don't exist in the DOM
- if (usersTableBody) {
- loadUsers();
- } else {
- console.log('Admin UI elements not found, skipping admin data loading');
- }
-
- if (registrationEnabled) {
- loadSiteSettings();
- }
+ if (adminSection) adminSection.style.display = 'block';
+ if (adminSection && adminSection.style.display === 'block') {
+ if (usersTableBody) loadUsers();
+ if (registrationEnabled) loadSiteSettings();
+ }
}
-
+
// Update localStorage
localStorage.setItem('user_info', JSON.stringify(userData));
} else {
- // Handle error
- const errorData = await response.json();
- console.warn('API error:', errorData.message);
+ const errorData = await response.json().catch(() => ({ message: 'Failed to parse error response' }));
+ console.warn('API error fetching user data:', errorData.message);
+ if (!currentUser) {
+ showToast(errorData.message || 'Failed to load fresh user data', 'warning');
+ }
}
} catch (apiError) {
console.warn('API error, using localStorage data:', apiError);
+ if (!currentUser) {
+ showToast('Could not connect to fetch user data. Displaying cached info.', 'warning');
+ }
}
} catch (error) {
console.error('Error loading user data:', error);
showToast('Failed to load user data. Please try again.', 'error');
+ if (userNameDisplay) userNameDisplay.textContent = 'Error';
+ if (userEmailDisplay) userEmailDisplay.textContent = 'Error';
} finally {
hideLoading();
}
@@ -928,79 +942,66 @@ function setTheme(isDark) {
*/
async function saveProfile() {
// Validate form
- if (!firstNameInput.value.trim() || !lastNameInput.value.trim()) {
- showToast('Please fill in all required fields', 'error');
+ if (!firstNameInput || !lastNameInput || !firstNameInput.value.trim() || !lastNameInput.value.trim()) { // Add null checks for inputs
+ showToast('Please fill in First Name and Last Name', 'error');
return;
}
-
+
showLoading();
-
+ // Get the display element
+ const userNameDisplay = document.getElementById('currentUserNameDisplay');
+
try {
- // Try to update profile via API
- try {
- const response = await fetch('/api/auth/profile', {
- method: 'PUT',
- headers: {
- 'Authorization': `Bearer ${window.auth.getToken()}`,
- 'Content-Type': 'application/json'
- },
- body: JSON.stringify({
- first_name: firstNameInput.value.trim(),
- last_name: lastNameInput.value.trim()
- })
- });
-
- if (response.ok) {
- const userData = await response.json();
-
- // Update localStorage
- const currentUser = window.auth.getCurrentUser();
- const updatedUser = {
- ...currentUser,
- first_name: userData.first_name,
- last_name: userData.last_name
- };
-
- localStorage.setItem('user_info', JSON.stringify(updatedUser));
-
- // Update UI
- if (window.auth.checkAuthState) {
- window.auth.checkAuthState();
- }
-
- showToast('Profile updated successfully', 'success');
- } else {
- // Handle error from API
- const errorData = await response.json();
- throw new Error(errorData.message || 'Failed to update profile');
- }
- } catch (apiError) {
- console.warn('API error, falling back to localStorage:', apiError);
-
- // Fallback to localStorage if API is not available
+ const response = await fetch('/api/auth/profile', {
+ method: 'PUT',
+ headers: {
+ 'Authorization': `Bearer ${window.auth.getToken()}`,
+ 'Content-Type': 'application/json'
+ },
+ body: JSON.stringify({
+ first_name: firstNameInput.value.trim(),
+ last_name: lastNameInput.value.trim()
+ })
+ });
+
+ if (response.ok) {
+ const userData = await response.json();
+
+ // Update localStorage
const currentUser = window.auth.getCurrentUser();
- if (currentUser) {
- const updatedUser = {
- ...currentUser,
- first_name: firstNameInput.value.trim(),
- last_name: lastNameInput.value.trim()
- };
-
- localStorage.setItem('user_info', JSON.stringify(updatedUser));
-
- // Update UI
- if (window.auth.checkAuthState) {
- window.auth.checkAuthState();
- }
-
- showToast('Profile updated successfully (offline mode)', 'success');
+ const updatedUser = {
+ ...(currentUser || {}), // Handle case where currentUser might be null
+ first_name: userData.first_name,
+ last_name: userData.last_name,
+ // Ensure email and username are preserved if they existed
+ email: currentUser ? currentUser.email : userData.email,
+ username: currentUser ? currentUser.username : userData.username,
+ is_admin: currentUser ? currentUser.is_admin : userData.is_admin,
+ id: currentUser ? currentUser.id : userData.id
+ };
+ localStorage.setItem('user_info', JSON.stringify(updatedUser));
+
+ // --- UPDATE DISPLAY ELEMENT IMMEDIATELY ---
+ const displayName = `${userData.first_name || ''} ${userData.last_name || ''}`.trim() || updatedUser.username || 'User'; // Use updatedUser for username fallback
+ if (userNameDisplay) userNameDisplay.textContent = displayName;
+ // --- END UPDATE ---
+
+ // Update UI (Header, etc.) - Ensure auth module is loaded
+ if (window.auth && window.auth.checkAuthState) {
+ window.auth.checkAuthState(); // This should update the header menu
} else {
- throw new Error('User not found in localStorage');
+ console.warn("Auth module or checkAuthState not found, header might not update immediately.");
}
+
+ showToast('Profile updated successfully', 'success');
+ } else {
+ const errorData = await response.json().catch(() => ({ message: 'Failed to parse error response' }));
+
+ throw new Error(errorData.message || 'Failed to update profile');
}
} catch (error) {
console.error('Error updating profile:', error);
- showToast('Failed to update profile. Please try again.', 'error');
+ showToast(`Failed to update profile: ${error.message}`, 'error');
} finally {
hideLoading();
}
diff --git a/frontend/settings-styles.css b/frontend/settings-styles.css
index 17898ec..b8f48d3 100644
--- a/frontend/settings-styles.css
+++ b/frontend/settings-styles.css
@@ -896,4 +896,55 @@ input:checked + .toggle-slider:before {
.admin-actions-grid {
grid-template-columns: 1fr;
}
+}
+
+/* Style for current user info display */
+.current-user-info {
+ margin-bottom: 20px; /* Matches HTML style */
+ padding-bottom: 15px; /* Matches HTML style */
+ border-bottom: 1px solid var(--border-color); /* Matches HTML style */
+ background-color: rgba(var(--primary-rgb), 0.05); /* Subtle background highlight */
+ padding: 15px;
+ border-radius: var(--border-radius);
+}
+
+.current-user-info p {
+ margin: 0; /* Remove default paragraph margins */
+}
+
+.current-user-info p:first-child {
+ font-size: 1.1rem; /* Slightly larger font for the name line */
+ color: var(--text-color);
+}
+
+.current-user-info p:last-child {
+ font-size: 0.9rem; /* Smaller font for the email line */
+ color: var(--text-muted);
+ margin-top: 5px; /* Add a little space below the name */
+}
+
+.current-user-info strong {
+ color: var(--primary-color); /* Highlight the label */
+}
+
+.current-user-info span {
+ font-weight: normal; /* Ensure the actual name/email isn't bold */
+}
+
+/* Dark mode adjustments */
+:root[data-theme="dark"] .current-user-info {
+ background-color: rgba(var(--primary-rgb), 0.1);
+ border-bottom-color: var(--border-color);
+}
+
+:root[data-theme="dark"] .current-user-info p:first-child {
+ color: var(--text-color);
+}
+
+:root[data-theme="dark"] .current-user-info p:last-child {
+ color: var(--text-muted);
+}
+
+:root[data-theme="dark"] .current-user-info strong {
+ color: var(--primary-color);
}
\ No newline at end of file