🛡️ Warracker is an open source, self-hostable warranty tracker to monitor expirations, store receipts, files. You own the data, your rules!
Fix view preference persistence, password management, SMTP port 587 support, and UI consistency; enhance footer branding links
sassanix130c5e66e95e
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 9076041..ffde072 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -1,5 +1,40 @@# Changelog+## 0.10.0.0 - 2025-06-4++### Fixed+- **View Preference Persistence Issue:** Fixed user view preferences (Grid, List, Table) not consistently persisting across logins.+ - **Backend (`backend/app.py`):** Modified `/api/auth/login` endpoint to include `is_admin` flag in the returned user object, ensuring proper view preference key prefix calculation immediately after login.+ - **Frontend (`frontend/script.js`):**+ - Enhanced `switchView()` function with `saveToApi` parameter to control when view preferences are saved to the API, preventing unintended overwrites during initialization.+ - Modified `loadViewPreference()` to call `switchView` with `saveToApi = false` to prevent overwriting user's actual preferences with defaults.+ - Updated storage event listener for cross-tab synchronization to prevent redundant API saves when syncing view preferences between browser tabs.+ - **Root Cause:** Missing `is_admin` flag caused incorrect localStorage prefix usage and race conditions where preferences were saved with wrong prefix then not found when correct prefix was established.+ - **Result:** View preferences now properly persist across logins and synchronize between browser tabs for both admin and regular users.+- **Password Management Issues:** Fixed critical password change and reset functionality problems.+ - **Missing Password Change Endpoint (`backend/app.py`):** Implemented `/api/auth/password/change` endpoint to allow logged-in users to change their passwords through the Settings page. The endpoint validates current password, checks new password strength, and securely updates the user's password hash.+ - **Frontend Error Handling (`frontend/settings-new.js`):** Fixed misleading "Password cannot be changed in offline mode" error by removing nested try-catch block that was masking real API error messages. Now properly displays specific backend error messages.+ - **Password Reset Link Issue (`frontend/reset-password.html`):** Fixed "Invalid or Expired Link" error by removing premature token verification that was calling a non-existent `/api/auth/password/verify-token` endpoint. Token validity is now properly checked only during form submission.+ - **Root Cause:** Backend endpoint was missing entirely, frontend had incorrect error handling, and reset page was making unnecessary token verification calls.+ - **Result:** Users can now successfully change passwords while logged in and use password reset links without encountering false error messages.+- **SMTP Port 587 (STARTTLS) Functionality:** Enhanced email sending to support both port 465 (SMTPS/SSL) and port 587 (STARTTLS) configurations.+ - **Enhanced SMTP Connection Logic (`backend/app.py`):** Updated `send_password_reset_email()`, `send_expiration_notifications()`, and `send_email_change_verification_email()` functions with robust port-based SMTP logic.+ - **Port 465:** Uses `smtplib.SMTP_SSL()` for direct SSL connection+ - **Port 587:** Uses `smtplib.SMTP()` followed by `starttls()` for STARTTLS encryption+ - **Other Ports:** Respects `SMTP_USE_TLS` environment variable for explicit STARTTLS control+ - **Environment Variable Support:** Added intelligent defaults where `SMTP_USE_TLS` defaults to true for port 587 unless explicitly set to false, ensuring proper STARTTLS behavior.+ - **Root Cause:** Previous logic used restrictive hostname-based conditions (`if smtp_host != 'localhost'`) instead of proper port-based SMTP configuration, causing STARTTLS failures with external SMTP servers on port 587.+ - **Result:** Email sending now works reliably with both common SMTP configurations, supporting major email providers like Gmail, Office 365, and other services using port 587.+- **Header Appearance Standardization (`frontend/reset-password-request.html`, `frontend/reset-password.html`):** Standardized headers to match consistent appearance across all pages.+ - **Missing CSS Includes:** Added `header-fix.css` and `fix-auth-buttons-loader.js` to ensure consistent header styling and behavior.+ - **Clickable Title:** Made "Warracker" title a clickable link to `index.html` for consistent navigation, matching other auth pages like `login.html` and `register.html`.+ - **Registration Status Script:** Added `registration-status.js` for consistent functionality across auth pages.+ - **Root Cause:** Pages were missing key CSS files and scripts that ensure header consistency, and the title was not a link unlike other pages.+ - **Result:** Headers now have identical appearance, dimensions, and responsive behavior as other application pages, providing consistent user experience.+### Enhanced+- **Footer Links:** Updated all "Powered by Warracker" footer links across the application to point to `https://warracker.com` instead of the GitHub repository, providing users with direct access to the official website.+ - **Files Updated:** `index.html`, `login.html`, `register.html`, `reset-password.html`, `reset-password-request.html`, `settings-new.html`, `status.html`, `auth-redirect.html`, and `about.html`+ - **Result:** Consistent branding and improved user experience with direct access to the official Warracker website.## 0.9.9.9 - 2025-06-01@@ -162,7 +197,6 @@## [0.9.9.8] - 2025-05-24-### Added- **Account Email Change:** Users can now change the email address associated with their account from the Settings page.- The email field in Account Settings is now editable.diff --git a/Docker/.env.example b/Docker/.env.exampleindex af8994e..ce5def4 100644--- a/Docker/.env.example+++ b/Docker/.env.example@@ -14,7 +14,7 @@ DB_PASSWORD=warranty_passwordDB_ADMIN_USER=warracker_adminDB_ADMIN_PASSWORD=change_this_password_in_production-# PostgreSQL-specific settings (for the database container) warrackerdb+# PostgreSQL-specific settings (for the database container)POSTGRES_DB=warranty_dbPOSTGRES_USER=warranty_userPOSTGRES_PASSWORD=warranty_password@@ -149,4 +149,4 @@ WARRACKER_MEMORY_MODE=performance3. **Generate strong passwords** for production use, especially for `SECRET_KEY`, `DB_PASSWORD`, and `DB_ADMIN_PASSWORD`4. **Set your domain URLs** correctly for `FRONTEND_URL` and `APP_BASE_URL` if deploying publicly5. **Configure SMTP** if you want email functionality for password resets and notifications-6. **Set up OIDC/SSO** if you want single sign-on capabilities+6. **Set up OIDC/SSO** if you want single sign-on capabilities\ No newline at end of filediff --git a/Docker/docker-compose.yml b/Docker/docker-compose.ymlindex b2efcf5..7113612 100644--- a/Docker/docker-compose.yml+++ b/Docker/docker-compose.yml@@ -28,7 +28,7 @@ services:- FRONTEND_URL=${FRONTEND_URL:-http://localhost:8005}- APP_BASE_URL=${APP_BASE_URL:-http://localhost:8005}# Memory optimization settings- - WARRACKER_MEMORY_MODE=${WARRACKER_MEMORY_MODE:-optimized} # Options: optimized (default), performance, ultra-light+ - WARRACKER_MEMORY_MODE=${WARRACKER_MEMORY_MODE:-optimized} # Options: optimized (default), ultra-light- PYTHONUNBUFFERED=1# - FLASK_DEBUG=0depends_on:diff --git a/backend/__pycache__/app.cpython-39.pyc b/backend/__pycache__/app.cpython-39.pycdeleted file mode 100644index 503b635..0000000Binary files a/backend/__pycache__/app.cpython-39.pyc and /dev/null differdiff --git a/backend/app.py b/backend/app.pyindex 99884a0..45c84da 100644--- a/backend/app.py+++ b/backend/app.py@@ -942,8 +942,8 @@ def login():conn = get_db_connection()with conn.cursor() as cur:- # Check if user exists- cur.execute('SELECT id, username, email, password_hash, is_active FROM users WHERE username = %s OR email = %s', (username, username))+ # Check if user exists - include is_admin in the query+ cur.execute('SELECT id, username, email, password_hash, is_active, is_admin FROM users WHERE username = %s OR email = %s', (username, username))user = cur.fetchone()if not user or not bcrypt.check_password_hash(user[3], password):@@ -979,7 +979,8 @@ def login():'user': {'id': user_id,'username': user[1],- 'email': user[2]+ 'email': user[2],+ 'is_admin': user[5] # Include is_admin flag}}), 200except Exception as e:@@ -3248,6 +3249,10 @@ The Warracker Team# Use SMTP_USERNAME as sender if available, otherwise a defaultsender_email = smtp_username or '[email protected]'+ # Explicit SMTP_USE_TLS from environment, defaulting to true if port is 587+ # and not explicitly set to false.+ smtp_use_tls_env = os.environ.get('SMTP_USE_TLS', 'not_set').lower()+if not smtp_username:logger.warning("SMTP_USERNAME environment variable not set. Using default sender address.")@@ -3264,27 +3269,43 @@ The Warracker Teammsg.attach(part2)# Connect to SMTP server and send+ server = Nonetry:- server = None # Initialize server to None+ logger.info(f"Attempting SMTP connection to {smtp_host}:{smtp_port}")if smtp_port == 465:- logger.info(f"Using SMTP_SSL connection for port 465 to host {smtp_host}")- server = smtplib.SMTP_SSL(smtp_host, smtp_port, timeout=10) # Add timeout+ logger.info("Using SMTP_SSL for port 465.")+ server = smtplib.SMTP_SSL(smtp_host, smtp_port, timeout=10)else:- logger.info(f"Using standard SMTP connection for port {smtp_port} to host {smtp_host}")- server = smtplib.SMTP(smtp_host, smtp_port, timeout=10) # Add timeout- # Start TLS for security if not local debug server and not using SSL- # Check if host suggests a non-local environment- if smtp_host != 'localhost' and not smtp_host.startswith('127.'):- logger.info("Attempting to start TLS")+ logger.info(f"Using SMTP for port {smtp_port}.")+ server = smtplib.SMTP(smtp_host, smtp_port, timeout=10)+ # For port 587, STARTTLS is standard.+ # For other ports, allow SMTP_USE_TLS to explicitly enable/disable it.+ # If SMTP_USE_TLS is 'not_set', default to True for port 587.+ should_use_starttls = False+ if smtp_port == 587:+ should_use_starttls = (smtp_use_tls_env != 'false') # True unless explicitly 'false'+ logger.info(f"Port is 587. SMTP_USE_TLS set to '{smtp_use_tls_env}'. should_use_starttls: {should_use_starttls}")+ elif smtp_use_tls_env == 'true':+ should_use_starttls = True+ logger.info(f"Port is {smtp_port}. SMTP_USE_TLS explicitly 'true'. should_use_starttls: {should_use_starttls}")+ else:+ logger.info(f"Port is {smtp_port}. SMTP_USE_TLS set to '{smtp_use_tls_env}'. should_use_starttls: {should_use_starttls}")++ if should_use_starttls:+ logger.info("Attempting to start TLS (server.starttls()).")server.starttls()+ logger.info("STARTTLS successful.")+ else:+ logger.info("Not using STARTTLS based on port and SMTP_USE_TLS setting.")# Login if credentials are providedif smtp_username and smtp_password:logger.info(f"Logging in with username: {smtp_username}")server.login(smtp_username, smtp_password)+ logger.info("SMTP login successful.")# Send email- logger.info(f"Sending email via {smtp_host}:{smtp_port} from {sender_email}")+ logger.info(f"Sending email via {smtp_host}:{smtp_port} from {sender_email} to {recipient_email}")server.sendmail(sender_email, recipient_email, msg.as_string())logger.info(f"Password reset email successfully sent to {recipient_email}")@@ -3292,8 +3313,12 @@ The Warracker Teamlogger.error(f"SMTP Authentication Error sending email to {recipient_email}: {e}")# Re-raise a more generic exception or handle appropriatelyraise Exception(f"SMTP Authentication failed for {smtp_username}") from e+ except smtplib.SMTPException as e: # Catch more generic SMTP exceptions+ logger.error(f"SMTP Error sending email to {recipient_email}: {e}")+ logger.error(f"SMTP details used - Host: {smtp_host}, Port: {smtp_port}, Username: {smtp_username}, Sender: {sender_email}")+ raise Exception(f"SMTP error occurred: {str(e)}") from eexcept Exception as e:- logger.error(f"Failed to send password reset email to {recipient_email}: {e}")+ logger.error(f"General error sending email to {recipient_email}: {e}")logger.error(f"SMTP details used - Host: {smtp_host}, Port: {smtp_port}, Username: {smtp_username}, Sender: {sender_email}")# Raise an exception to be caught by the calling functionraise Exception("Failed to send password reset email") from e@@ -3459,22 +3484,44 @@ def send_expiration_notifications(manual_trigger=False):smtp_username = os.environ.get('SMTP_USERNAME', '[email protected]')smtp_password = os.environ.get('SMTP_PASSWORD', '')+ # Explicit SMTP_USE_TLS from environment, defaulting to true if port is 587+ # and not explicitly set to false.+ smtp_use_tls_env = os.environ.get('SMTP_USE_TLS', 'not_set').lower()+# Connect to SMTP servertry:- # Use SMTP_SSL for port 465, regular SMTP for other ports+ logger.info(f"Attempting SMTP connection to {smtp_host}:{smtp_port}")if smtp_port == 465:- logger.info(f"Using SMTP_SSL connection for port 465")- server = smtplib.SMTP_SSL(smtp_host, smtp_port)+ logger.info("Using SMTP_SSL for port 465.")+ server = smtplib.SMTP_SSL(smtp_host, smtp_port, timeout=10)else:- server = smtplib.SMTP(smtp_host, smtp_port)- # Start TLS for security if not local debug server and not using SSL- if smtp_host != 'localhost':+ logger.info(f"Using SMTP for port {smtp_port}.")+ server = smtplib.SMTP(smtp_host, smtp_port, timeout=10)+ # For port 587, STARTTLS is standard.+ # For other ports, allow SMTP_USE_TLS to explicitly enable/disable it.+ # If SMTP_USE_TLS is 'not_set', default to True for port 587.+ should_use_starttls = False+ if smtp_port == 587:+ should_use_starttls = (smtp_use_tls_env != 'false') # True unless explicitly 'false'+ logger.info(f"Port is 587. SMTP_USE_TLS set to '{smtp_use_tls_env}'. should_use_starttls: {should_use_starttls}")+ elif smtp_use_tls_env == 'true':+ should_use_starttls = True+ logger.info(f"Port is {smtp_port}. SMTP_USE_TLS explicitly 'true'. should_use_starttls: {should_use_starttls}")+ else:+ logger.info(f"Port is {smtp_port}. SMTP_USE_TLS set to '{smtp_use_tls_env}'. should_use_starttls: {should_use_starttls}")++ if should_use_starttls:+ logger.info("Attempting to start TLS (server.starttls()).")server.starttls()+ logger.info("STARTTLS successful.")+ else:+ logger.info("Not using STARTTLS based on port and SMTP_USE_TLS setting.")# Login if credentials are providedif smtp_username and smtp_password:logger.info(f"Logging in with username: {smtp_username}")server.login(smtp_username, smtp_password)+ logger.info("SMTP login successful.")# Send emails to each userutc_now = datetime.utcnow()@@ -4413,6 +4460,59 @@ def reset_password():if conn:release_db_connection(conn)[email protected]('/api/auth/password/change', methods=['POST'])+@token_required+def change_password():+ """Allow logged-in users to change their password"""+ conn = None+ try:+ data = request.get_json()++ if not data.get('current_password') or not data.get('new_password'):+ return jsonify({'message': 'Current password and new password are required!'}), 400++ current_password = data['current_password']+ new_password = data['new_password']+ user_id = request.user['id'] # Get user ID from the token_required decorator++ # Validate new password strength+ if not is_valid_password(new_password):+ return jsonify({'message': 'New password must be at least 8 characters and include uppercase, lowercase, and numbers!'}), 400++ conn = get_db_connection()+ with conn.cursor() as cur:+ # Get the user's current password hash+ cur.execute('SELECT password_hash FROM users WHERE id = %s', (user_id,))+ user_data = cur.fetchone()++ if not user_data:+ return jsonify({'message': 'User not found!'}), 404++ current_password_hash = user_data[0]++ # Verify the current password+ if not bcrypt.check_password_hash(current_password_hash, current_password):+ return jsonify({'message': 'Incorrect current password!'}), 401++ # Hash the new password+ new_password_hash = bcrypt.generate_password_hash(new_password).decode('utf-8')++ # Update the password in the database+ cur.execute('UPDATE users SET password_hash = %s WHERE id = %s', (new_password_hash, user_id))++ conn.commit()++ return jsonify({'message': 'Password changed successfully!'}), 200++ except Exception as e:+ logger.error(f"Password change error: {e}")+ if conn:+ conn.rollback()+ return jsonify({'message': 'Failed to change password!'}), 500+ finally:+ if conn:+ release_db_connection(conn)+def send_email_change_verification_email(recipient_email, verification_link_path_with_token):"""Sends an email with a link to verify the new email address."""try:@@ -4425,6 +4525,10 @@ def send_email_change_verification_email(recipient_email, verification_link_pathsender_email = os.environ.get('SMTP_SENDER_EMAIL', '[email protected]')app_name = "Warracker" # Or get from config+ # Explicit SMTP_USE_TLS from environment, defaulting to true if port is 587+ # and not explicitly set to false.+ smtp_use_tls_env = os.environ.get('SMTP_USE_TLS', 'not_set').lower()+subject = f"Confirm Your New Email Address - {app_name}"app_base_url = os.environ.get('APP_BASE_URL', request.url_root.rstrip('/'))@@ -4460,15 +4564,38 @@ def send_email_change_verification_email(recipient_email, verification_link_pathlogger.info(f"Attempting to send email change verification to {recipient_email} via {smtp_host}:{smtp_port}")- if smtp_use_ssl:+ server = None+ logger.info(f"Attempting SMTP connection to {smtp_host}:{smtp_port}")+ if smtp_port == 465:+ logger.info("Using SMTP_SSL for port 465.")server = smtplib.SMTP_SSL(smtp_host, smtp_port, timeout=10)else:+ logger.info(f"Using SMTP for port {smtp_port}.")server = smtplib.SMTP(smtp_host, smtp_port, timeout=10)- if smtp_use_tls:+ # For port 587, STARTTLS is standard.+ # For other ports, allow SMTP_USE_TLS to explicitly enable/disable it.+ # If SMTP_USE_TLS is 'not_set', default to True for port 587.+ should_use_starttls = False+ if smtp_port == 587:+ should_use_starttls = (smtp_use_tls_env != 'false') # True unless explicitly 'false'+ logger.info(f"Port is 587. SMTP_USE_TLS set to '{smtp_use_tls_env}'. should_use_starttls: {should_use_starttls}")+ elif smtp_use_tls_env == 'true':+ should_use_starttls = True+ logger.info(f"Port is {smtp_port}. SMTP_USE_TLS explicitly 'true'. should_use_starttls: {should_use_starttls}")+ else:+ logger.info(f"Port is {smtp_port}. SMTP_USE_TLS set to '{smtp_use_tls_env}'. should_use_starttls: {should_use_starttls}")++ if should_use_starttls:+ logger.info("Attempting to start TLS (server.starttls()).")server.starttls()+ logger.info("STARTTLS successful.")+ else:+ logger.info("Not using STARTTLS based on port and SMTP_USE_TLS setting.")if smtp_username and smtp_password:+ logger.info(f"Logging in with username: {smtp_username}")server.login(smtp_username, smtp_password)+ logger.info("SMTP login successful.")server.sendmail(sender_email, recipient_email, msg.as_string())server.quit()diff --git a/frontend/about.html b/frontend/about.htmlindex 826b813..28e06b6 100644--- a/frontend/about.html+++ b/frontend/about.html@@ -90,7 +90,7 @@<div class="about-container" style="background-color: var(--card-bg); color: var(--text-color); padding: 20px; border-radius: 8px; margin-top: 20px; box-shadow: 0 2px 5px rgba(0,0,0,0.1); width: 100%; box-sizing: border-box;"><h1 style="color: var(--primary-color); margin-bottom: 20px;">About Warracker</h1>- <p><strong>Version:</strong> v0.9.9.9</p>+ <p><strong>Version:</strong> v0.10.0.0</p><div id="versionTracker" style="margin-bottom: 20px;"><p><strong>Update Status:</strong> <span id="updateStatus">Checking for updates...</span></p>@@ -337,7 +337,7 @@<!-- Powered by Warracker Footer --><footer class="warracker-footer" id="warrackerFooter">- <p>Powered by <a href="https://github.com/sassanix/warracker" target="_blank" rel="noopener noreferrer" id="warrackerFooterLink">Warracker</a></p>+ <p>Powered by <a href="https://warracker.com" target="_blank" rel="noopener noreferrer" id="warrackerFooterLink">Warracker</a></p></footer><script>diff --git a/frontend/auth-redirect.html b/frontend/auth-redirect.htmlindex e888605..f16a2f6 100644--- a/frontend/auth-redirect.html+++ b/frontend/auth-redirect.html@@ -160,7 +160,7 @@<!-- Powered by Warracker Footer --><footer class="warracker-footer" id="warrackerFooter">- <p>Powered by <a href="https://github.com/sassanix/warracker" target="_blank" rel="noopener noreferrer" id="warrackerFooterLink">Warracker</a></p>+ <p>Powered by <a href="https://warracker.com" target="_blank" rel="noopener noreferrer" id="warrackerFooterLink">Warracker</a></p></footer><script>diff --git a/frontend/index.html b/frontend/index.htmlindex 0cd5e70..97754cd 100644--- a/frontend/index.html+++ b/frontend/index.html@@ -788,7 +788,7 @@<!-- Powered by Warracker Footer --><footer class="warracker-footer" id="warrackerFooter">- <p>Powered by <a href="https://github.com/sassanix/warracker" target="_blank" rel="noopener noreferrer" id="warrackerFooterLink">Warracker</a></p>+ <p>Powered by <a href="https://warracker.com" target="_blank" rel="noopener noreferrer" id="warrackerFooterLink">Warracker</a></p></footer><script>diff --git a/frontend/login.html b/frontend/login.htmlindex 75932bc..945c9ae 100644--- a/frontend/login.html+++ b/frontend/login.html@@ -540,7 +540,7 @@<!-- Powered by Warracker Footer --><footer class="warracker-footer" id="warrackerFooter">- <p>Powered by <a href="https://github.com/sassanix/warracker" target="_blank" rel="noopener noreferrer" id="warrackerFooterLink">Warracker</a></p>+ <p>Powered by <a href="https://warracker.com" target="_blank" rel="noopener noreferrer" id="warrackerFooterLink">Warracker</a></p></footer><script>diff --git a/frontend/register.html b/frontend/register.htmlindex 8d42756..9dd539b 100644--- a/frontend/register.html+++ b/frontend/register.html@@ -606,7 +606,7 @@<!-- Powered by Warracker Footer --><footer class="warracker-footer" id="warrackerFooter">- <p>Powered by <a href="https://github.com/sassanix/warracker" target="_blank" rel="noopener noreferrer" id="warrackerFooterLink">Warracker</a></p>+ <p>Powered by <a href="https://warracker.com" target="_blank" rel="noopener noreferrer" id="warrackerFooterLink">Warracker</a></p></footer><script>diff --git a/frontend/reset-password-request.html b/frontend/reset-password-request.htmlindex 9b8a36f..b1a5776 100644--- a/frontend/reset-password-request.html+++ b/frontend/reset-password-request.html@@ -14,6 +14,10 @@<script src="theme-loader.js"></script> <!-- Apply theme early --><!-- Font Awesome for icons --><link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">+ <!-- Load header fix styles to ensure consistent header styling -->+ <link rel="stylesheet" href="header-fix.css">+ <!-- Load fix for auth buttons -->+ <script src="fix-auth-buttons-loader.js"></script><style>.auth-container {max-width: 400px;@@ -82,6 +86,9 @@line-height: 1.5;}</style>++ <!-- Registration status check script -->+ <script src="registration-status.js"></script></head><body><!-- Header -->@@ -89,7 +96,7 @@<div class="container"><div class="app-title"><i class="fas fa-shield-alt"></i>- <h1>Warracker</h1>+ <h1><a href="index.html" style="color: inherit; text-decoration: none; cursor: pointer;">Warracker</a></h1></div></div></header>@@ -240,7 +247,7 @@<!-- Powered by Warracker Footer --><footer class="warracker-footer" id="warrackerFooter">- <p>Powered by <a href="https://github.com/sassanix/warracker" target="_blank" rel="noopener noreferrer" id="warrackerFooterLink">Warracker</a></p>+ <p>Powered by <a href="https://warracker.com" target="_blank" rel="noopener noreferrer" id="warrackerFooterLink">Warracker</a></p></footer><script>diff --git a/frontend/reset-password.html b/frontend/reset-password.htmlindex 2aa75d6..9bb73ee 100644--- a/frontend/reset-password.html+++ b/frontend/reset-password.html@@ -14,6 +14,10 @@<script src="theme-loader.js"></script> <!-- Apply theme early --><!-- Font Awesome for icons --><link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">+ <!-- Load header fix styles to ensure consistent header styling -->+ <link rel="stylesheet" href="header-fix.css">+ <!-- Load fix for auth buttons -->+ <script src="fix-auth-buttons-loader.js"></script><style>.auth-container {max-width: 400px;@@ -139,6 +143,9 @@margin-bottom: 15px;}</style>++ <!-- Registration status check script -->+ <script src="registration-status.js"></script></head><body><!-- Header -->@@ -146,7 +153,7 @@<div class="container"><div class="app-title"><i class="fas fa-shield-alt"></i>- <h1>Warracker</h1>+ <h1><a href="index.html" style="color: inherit; text-decoration: none; cursor: pointer;">Warracker</a></h1></div></div></header>@@ -238,8 +245,9 @@// Set token in hidden fielddocument.getElementById('token').value = tokenToUse;- // Verify token validity- verifyToken(tokenToUse);+ // Show the reset form directly if token is present (validity will be checked on submission)+ document.getElementById('resetForm').style.display = 'block';+ document.getElementById('tokenInvalid').style.display = 'none';// Toggle password visibilityconst passwordToggles = document.querySelectorAll('.password-toggle');@@ -377,29 +385,6 @@authMessage.style.display = 'block';}- // Function to verify token validity- async function verifyToken(token) {- try {- const response = await fetch(`/api/auth/password/verify-token?token=${token}`);- const data = await response.json();-- if (!response.ok) {- throw new Error(data.message || 'Invalid token');- }-- // Token is valid, show the form- document.getElementById('resetForm').style.display = 'block';- document.getElementById('tokenInvalid').style.display = 'none';-- } catch (error) {- console.error('Token verification error:', error);-- // Token is invalid, show error message- document.getElementById('resetForm').style.display = 'none';- document.getElementById('tokenInvalid').style.display = 'block';- }- }-// No longer check for 'enabled' value. Theme is handled by theme-loader.js and below.});@@ -428,7 +413,7 @@<!-- Powered by Warracker Footer --><footer class="warracker-footer" id="warrackerFooter">- <p>Powered by <a href="https://github.com/sassanix/warracker" target="_blank" rel="noopener noreferrer" id="warrackerFooterLink">Warracker</a></p>+ <p>Powered by <a href="https://warracker.com" target="_blank" rel="noopener noreferrer" id="warrackerFooterLink">Warracker</a></p></footer><script>diff --git a/frontend/script.js b/frontend/script.jsindex ae4d2fb..4d34624 100644--- a/frontend/script.js+++ b/frontend/script.js@@ -1003,7 +1003,7 @@ async function exportWarranties() {}// Switch view of warranties list-async function switchView(viewType) { // Added async+async function switchView(viewType, saveToApi = true) { // Added saveToApi parameter with default trueconsole.log(`Switching to view: ${viewType}`);currentView = viewType;@@ -1022,8 +1022,8 @@ async function switchView(viewType) { // Added asyncconsole.log(`View preference (${viewKey}) already set to ${viewType} in localStorage.`);}- // --- BEGIN ADDED: Save preference to API ---- if (window.auth && window.auth.isAuthenticated()) {+ // --- MODIFIED: Only save preference to API if saveToApi is true ---+ if (saveToApi && window.auth && window.auth.isAuthenticated()) {const token = window.auth.getToken();if (token) {try {@@ -1053,10 +1053,12 @@ async function switchView(viewType) { // Added async} else {console.warn('Cannot save view preference to API: No auth token found.');}+ } else if (!saveToApi) {+ console.log('Skipping API save as saveToApi is false (likely called from loadViewPreference).');} else {console.warn('Cannot save view preference to API: User not authenticated or auth module not loaded.');}- // --- END ADDED: Save preference to API ---+ // --- END MODIFIED: Save preference to API ---// Make sure warrantiesList exists before modifying classesif (warrantiesList) {@@ -1112,10 +1114,10 @@ function loadViewPreference() {// Default to grid view if no preference is savedsavedView = savedView || 'grid';- console.log(`Applying view preference: ${savedView}`);+ console.log(`Applying view preference from loadViewPreference: ${savedView}`);// Switch view only if view buttons exist (implying it's the main page)if (gridViewBtn || listViewBtn || tableViewBtn) {- switchView(savedView);+ switchView(savedView, false); // Pass false to prevent API save on initial load}}@@ -4505,23 +4507,23 @@ async function handleImport(file) {// --- Add Storage Event Listener for Real-time Sync ---window.addEventListener('storage', (event) => {- const prefix = getPreferenceKeyPrefix();- const viewKeys = [- `${prefix}defaultView`,+ const currentPrefix = getPreferenceKeyPrefix(); // Re-calculate prefix+ const viewKeysToWatch = [+ `${currentPrefix}defaultView`,'viewPreference',- `${prefix}warrantyView`,- // Add `${prefix}viewPreference` if still used/relevant- `${prefix}viewPreference`+ `${currentPrefix}warrantyView`,+ // Add `${currentPrefix}viewPreference` if still used/relevant+ `${currentPrefix}viewPreference`];// Check for view preference changes- if (viewKeys.includes(event.key) && event.newValue) {+ if (viewKeysToWatch.includes(event.key) && event.newValue) {console.log(`Storage event detected for view preference (${event.key}). New value: ${event.newValue}`);// Check if the new value is different from the current view to avoid loopsif (event.newValue !== currentView) {// Ensure view buttons exist before switching (we're on the main page)if (gridViewBtn || listViewBtn || tableViewBtn) {- switchView(event.newValue);+ switchView(event.newValue, false); // Apply change, don't re-save to API}} else {console.log('Storage event value matches current view, ignoring.');@@ -4540,8 +4542,8 @@ window.addEventListener('storage', (event) => {// --- End Added Check ---// --- Added: Check for currency symbol changes ---- if (event.key === `${prefix}currencySymbol` && event.newValue) {- console.log(`Storage event detected for ${prefix}currencySymbol. New value: ${event.newValue}`);+ if (event.key === `${currentPrefix}currencySymbol` && event.newValue) {+ console.log(`Storage event detected for ${currentPrefix}currencySymbol. New value: ${event.newValue}`);if (warrantiesList) { // Only apply if on the main pageupdateCurrencySymbols(); // Update symbols outside cards (e.g., in forms if they exist)applyFilters(); // Re-render cards to update symbols inside themdiff --git a/frontend/settings-new.html b/frontend/settings-new.htmlindex 7de4c77..f600944 100644--- a/frontend/settings-new.html+++ b/frontend/settings-new.html@@ -677,7 +677,7 @@<!-- Powered by Warracker Footer --><footer class="warracker-footer" id="warrackerFooter">- <p>Powered by <a href="https://github.com/sassanix/warracker" target="_blank" rel="noopener noreferrer" id="warrackerFooterLink">Warracker</a></p>+ <p>Powered by <a href="https://warracker.com" target="_blank" rel="noopener noreferrer" id="warrackerFooterLink">Warracker</a></p></footer><script>diff --git a/frontend/settings-new.js b/frontend/settings-new.jsindex b57a7d4..59fd735 100644--- a/frontend/settings-new.js+++ b/frontend/settings-new.js@@ -1116,39 +1116,34 @@ async function changePassword() {showLoading();try {- try {- const response = await fetch('/api/auth/password/change', {- method: 'POST',- headers: {- 'Authorization': `Bearer ${window.auth.getToken()}`,- 'Content-Type': 'application/json'- },- body: JSON.stringify({- current_password: currentPasswordInput.value,- new_password: newPasswordInput.value- })- });+ const response = await fetch('/api/auth/password/change', {+ method: 'POST',+ headers: {+ 'Authorization': `Bearer ${window.auth.getToken()}`,+ 'Content-Type': 'application/json'+ },+ body: JSON.stringify({+ current_password: currentPasswordInput.value,+ new_password: newPasswordInput.value+ })+ });++ if (response.ok) {+ // Reset form and hide it+ resetPasswordForm();+ passwordChangeForm.style.display = 'none';+ changePasswordBtn.style.display = 'block';- if (response.ok) {- // Reset form and hide it- resetPasswordForm();- passwordChangeForm.style.display = 'none';- changePasswordBtn.style.display = 'block';-- // Show success modal- openModal(passwordSuccessModal);- } else {- // Handle error- const errorData = await response.json();- throw new Error(errorData.message || 'Failed to change password');- }- } catch (apiError) {- console.warn('API error, showing offline message:', apiError);- showToast('Password cannot be changed in offline mode', 'warning');+ // Show success modal+ openModal(passwordSuccessModal);+ } else {+ // Handle error+ const errorData = await response.json().catch(() => ({ message: 'Failed to parse error response' }));+ throw new Error(errorData.message || 'Failed to change password');}} catch (error) {console.error('Error changing password:', error);- showToast('Failed to change password. Please try again.', 'error');+ showToast(`Failed to change password: ${error.message}`, 'error');} finally {hideLoading();}diff --git a/frontend/status.html b/frontend/status.htmlindex 46e6534..2186821 100644--- a/frontend/status.html+++ b/frontend/status.html@@ -648,7 +648,7 @@<!-- Powered by Warracker Footer --><footer class="warracker-footer" id="warrackerFooter">- <p>Powered by <a href="https://github.com/sassanix/warracker" target="_blank" rel="noopener noreferrer" id="warrackerFooterLink">Warracker</a></p>+ <p>Powered by <a href="https://warracker.com" target="_blank" rel="noopener noreferrer" id="warrackerFooterLink">Warracker</a></p></footer><script>