Skip to content

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

Authentication, Settings Page

sassanixf6e11a629ec1
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 6cc75c9..a624748 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -1,5 +1,59 @@
# Changelog
+## [0.9.7] - 2025-03-13
+
+- **Authentication Enhancements**
+ - Added "Remember Me" functionality to the login page, allowing users to stay logged in across sessions.
+ - Implemented auto-login feature that checks for a valid session cookie and automatically logs in users if they have opted for "Remember Me".
+ - Updated the login endpoint to accept a `remember_me` parameter and set a persistent session cookie when checked.
+ - Created a new `/api/auth/auto-login` endpoint to handle auto-login requests.
+
+- **User Management Improvements**
+ - Enhanced user registration process to validate email format and password strength.
+ - Added functionality to check if registration is enabled or disabled via the `/api/auth/registration-status` endpoint.
+ - Implemented user profile update functionality, allowing users to change their first and last names.
+ - Added admin-only endpoints for managing user accounts, including viewing, updating, and deleting users.
+ - **User Deletion Functionality**
+ - Enhanced modal functionality for user deletion, including improved error checking and logging.
+ - Improved `deleteUser` function with better error handling and user ID retrieval.
+ - Added support for handling both numeric IDs and usernames in the deletion process.
+ - Created diagnostic functions to test modal functionality and user deletion processes.
+ - Improved event handling for user-related actions, ensuring proper setup of event listeners.
+
+- **Admin Management**
+ - View Users: Admins can view a list of all registered users, including their details such as usernames, email addresses, and account statuses.
+ - Delete User Accounts: Admins have the ability to delete user accounts, removing them from the system entirely.
+ - Monitor System Health: Admins can check the health of the application and server, ensuring that everything is running smoothly.
+
+- **Settings Page Updates**
+ - Created a settings page for users to manage their preferences, including email notifications and default view settings.
+ - Implemented backend support for retrieving and updating user preferences via the `/api/auth/preferences` endpoint.
+ - Added validation for user preferences to ensure only valid values are accepted.
+
+- **Database Enhancements**
+ - Updated database schema to include user sessions and password reset tokens for improved security and functionality.
+ - Added indexes to improve query performance for user and warranty data.
+ - Implemented error handling and logging for database operations to facilitate easier debugging and maintenance.
+
+- **UI/UX Improvements**
+ - Enhanced the login form with a "Remember Me" checkbox and improved styling for better user experience.
+ - Added loading indicators and toast notifications for better feedback during authentication processes.
+ - Improved the overall layout and design of the settings and authentication pages for a more cohesive look.
+ - Added a "Show Users List" button to the admin controls for easy access to user management.
+
+- **Security Enhancements**
+ - Implemented secure cookie handling for session tokens to prevent XSS attacks.
+ - Added validation checks for user input to prevent SQL injection and other common vulnerabilities.
+ - Ensured that sensitive operations are protected by authentication and authorization checks.
+
+- **What's not working**
+ - The menu still needs work done, the gear icon is not consistent
+ - When putting in the wrong password, you will need to refresh the page and try again manually.
+ - Email notification still doesn't work
+ - Users can't delete their own account, but admins can
+ - Users can't delete their own account, but admins can
+
+
## [0.5.2] - 2025-03-09
### Changed
diff --git a/Dockerfile b/Dockerfile
index 43dcb03..8534702 100644
--- a/Dockerfile
+++ b/Dockerfile
@@ -17,6 +17,10 @@ RUN pip install --no-cache-dir -r requirements.txt
# Copy backend code
COPY backend/app.py .
+COPY backend/run_migrations.py .
+COPY backend/fix_permissions.py .
+COPY backend/fix_permissions.sql .
+COPY backend/migrations/ ./migrations/
# Create directory for uploads with proper permissions
RUN mkdir -p /data/uploads && chmod 777 /data/uploads
@@ -31,15 +35,32 @@ COPY test.html /var/www/html/
RUN rm /etc/nginx/sites-enabled/default
COPY nginx.conf /etc/nginx/conf.d/default.conf
-# Add MIME type configuration - this is now included in nginx.conf
-
-# Create startup script with directory permission check
+# Create startup script with directory permission check and database initialization
RUN echo '#!/bin/bash\n\
echo "Checking /data/uploads directory:"\n\
ls -la /data/uploads\n\
echo "Setting permissions:"\n\
chmod -R 777 /data/uploads\n\
ls -la /data/uploads\n\
+echo "Running database migrations..."\n\
+python /app/run_migrations.py\n\
+echo "Ensuring admin role has proper permissions..."\n\
+# Retry logic for granting superuser privileges\n\
+max_attempts=5\n\
+attempt=0\n\
+while [ $attempt -lt $max_attempts ]; do\n\
+ echo "Attempt $((attempt+1)) to grant superuser privileges..."\n\
+ if PGPASSWORD=$DB_PASSWORD psql -h $DB_HOST -U $DB_USER -d $DB_NAME -c "ALTER ROLE warranty_user WITH SUPERUSER;" 2>/dev/null; then\n\
+ echo "Successfully granted superuser privileges to warranty_user"\n\
+ break\n\
+ else\n\
+ echo "Failed to grant privileges, retrying in 5 seconds..."\n\
+ sleep 5\n\
+ attempt=$((attempt+1))\n\
+ fi\n\
+done\n\
+echo "Running fix permissions script..."\n\
+python /app/fix_permissions.py\n\
echo "Starting services..."\n\
nginx\n\
gunicorn --bind 0.0.0.0:5000 --workers 4 app:app\n\
diff --git a/backend/Dockerfile b/backend/Dockerfile
deleted file mode 100644
index 19f735d..0000000
--- a/backend/Dockerfile
+++ /dev/null
@@ -1,17 +0,0 @@
-FROM python:3.9-slim
-
-WORKDIR /app
-
-COPY requirements.txt .
-RUN pip install --no-cache-dir -r requirements.txt
-
-COPY . .
-
-# Create directory for uploads
-RUN mkdir -p /data/uploads && chmod 777 /data/uploads
-
-# Expose port
-EXPOSE 5000
-
-# Start the application
-CMD ["python", "app.py"]
\ No newline at end of file
diff --git a/backend/app.py b/backend/app.py
index 80f6554..167cdff 100644
--- a/backend/app.py
+++ b/backend/app.py
@@ -1,4 +1,4 @@
-from flask import Flask, request, jsonify, send_from_directory
+from flask import Flask, request, jsonify, send_from_directory, session, redirect, url_for
import psycopg2
from psycopg2 import pool
import os
@@ -8,14 +8,24 @@ from flask_cors import CORS
import logging
import time
from decimal import Decimal
+import jwt
+from flask_bcrypt import Bcrypt
+import re
+from functools import wraps
+import uuid
app = Flask(__name__)
-CORS(app) # Enable CORS
+CORS(app, supports_credentials=True) # Enable CORS with credentials
+bcrypt = Bcrypt(app)
# Configure logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
+# Set a secret key for session and JWT
+app.config['SECRET_KEY'] = os.environ.get('SECRET_KEY', 'dev_secret_key_change_in_production')
+app.config['JWT_EXPIRATION_DELTA'] = timedelta(days=7) # Token expiration time
+
UPLOAD_FOLDER = '/data/uploads'
ALLOWED_EXTENSIONS = {'pdf', 'png', 'jpg', 'jpeg'}
MAX_CONTENT_LENGTH = 16 * 1024 * 1024 # 16MB max upload
@@ -28,6 +38,8 @@ DB_HOST = os.environ.get('DB_HOST', 'warrackerdb')
DB_NAME = os.environ.get('DB_NAME', 'warranty_db')
DB_USER = os.environ.get('DB_USER', 'warranty_user')
DB_PASSWORD = os.environ.get('DB_PASSWORD', 'warranty_password')
+DB_ADMIN_USER = os.environ.get('DB_ADMIN_USER', 'warracker_admin')
+DB_ADMIN_PASSWORD = os.environ.get('DB_ADMIN_PASSWORD', 'change_this_password_in_production')
# Add connection retry logic
def create_db_pool(max_retries=5, retry_delay=5):
@@ -75,6 +87,21 @@ def get_db_connection():
logger.error(f"Database connection error: {e}")
raise
+def get_admin_db_connection():
+ """Get a database connection with admin privileges for user management"""
+ try:
+ # Connect using the admin role for administrative tasks
+ conn = psycopg2.connect(
+ host=DB_HOST,
+ database=DB_NAME,
+ user=DB_ADMIN_USER,
+ password=DB_ADMIN_PASSWORD
+ )
+ return conn
+ except Exception as e:
+ logger.error(f"Admin database connection error: {e}")
+ raise
+
def release_db_connection(conn):
connection_pool.putconn(conn)
@@ -87,7 +114,7 @@ def init_db():
try:
conn = get_db_connection()
with conn.cursor() as cur:
- # Add indexes to frequently queried fields
+ # Create warranties table if it doesn't exist
cur.execute('''
CREATE TABLE IF NOT EXISTS warranties (
id SERIAL PRIMARY KEY,
@@ -103,9 +130,24 @@ def init_db():
)
''')
+ # Add user_id column if it doesn't exist - use DO block to avoid errors
+ cur.execute('''
+ DO $$
+ BEGIN
+ IF NOT EXISTS (
+ SELECT column_name
+ FROM information_schema.columns
+ WHERE table_name='warranties' AND column_name='user_id'
+ ) THEN
+ ALTER TABLE warranties ADD COLUMN user_id INTEGER;
+ END IF;
+ END $$;
+ ''')
+
# Add indexes for faster queries
cur.execute('CREATE INDEX IF NOT EXISTS idx_expiration_date ON warranties(expiration_date)')
cur.execute('CREATE INDEX IF NOT EXISTS idx_product_name ON warranties(product_name)')
+ cur.execute('CREATE INDEX IF NOT EXISTS idx_user_id ON warranties(user_id)')
# Create serial numbers table
cur.execute('''
@@ -122,6 +164,60 @@ def init_db():
cur.execute('CREATE INDEX IF NOT EXISTS idx_warranty_id ON serial_numbers(warranty_id)')
cur.execute('CREATE INDEX IF NOT EXISTS idx_serial_number ON serial_numbers(serial_number)')
+ # Create users table
+ cur.execute('''
+ CREATE TABLE IF NOT EXISTS users (
+ id SERIAL PRIMARY KEY,
+ username VARCHAR(255) NOT NULL UNIQUE,
+ email VARCHAR(255) NOT NULL UNIQUE,
+ password_hash VARCHAR(255) NOT NULL,
+ first_name VARCHAR(255),
+ last_name VARCHAR(255),
+ is_active BOOLEAN DEFAULT TRUE,
+ is_admin BOOLEAN DEFAULT FALSE,
+ created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
+ last_login TIMESTAMP
+ )
+ ''')
+
+ # Add indexes for users
+ cur.execute('CREATE INDEX IF NOT EXISTS idx_username ON users(username)')
+ cur.execute('CREATE INDEX IF NOT EXISTS idx_email ON users(email)')
+
+ # Create password reset tokens table
+ cur.execute('''
+ CREATE TABLE IF NOT EXISTS password_reset_tokens (
+ id SERIAL PRIMARY KEY,
+ user_id INTEGER NOT NULL,
+ token VARCHAR(255) NOT NULL,
+ expires_at TIMESTAMP NOT NULL,
+ created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
+ FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
+ )
+ ''')
+
+ # Add indexes for password reset tokens
+ cur.execute('CREATE INDEX IF NOT EXISTS idx_token ON password_reset_tokens(token)')
+ cur.execute('CREATE INDEX IF NOT EXISTS idx_user_id_token ON password_reset_tokens(user_id)')
+
+ # Create user sessions table
+ cur.execute('''
+ CREATE TABLE IF NOT EXISTS user_sessions (
+ id SERIAL PRIMARY KEY,
+ user_id INTEGER NOT NULL,
+ session_token VARCHAR(255) NOT NULL,
+ expires_at TIMESTAMP NOT NULL,
+ ip_address VARCHAR(45),
+ user_agent TEXT,
+ created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
+ FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
+ )
+ ''')
+
+ # Add indexes for user sessions
+ cur.execute('CREATE INDEX IF NOT EXISTS idx_session_token ON user_sessions(session_token)')
+ cur.execute('CREATE INDEX IF NOT EXISTS idx_user_id_session ON user_sessions(user_id)')
+
conn.commit()
logger.info("Database initialized successfully")
except Exception as e:
@@ -133,13 +229,629 @@ def init_db():
if conn:
release_db_connection(conn)
+# Authentication helper functions
+def generate_token(user_id):
+ """Generate a JWT token for the user"""
+ payload = {
+ 'exp': datetime.utcnow() + app.config['JWT_EXPIRATION_DELTA'],
+ 'iat': datetime.utcnow(),
+ 'sub': user_id
+ }
+ return jwt.encode(payload, app.config['SECRET_KEY'], algorithm='HS256')
+
+def decode_token(token):
+ """Decode a JWT token and return the user_id"""
+ try:
+ payload = jwt.decode(token, app.config['SECRET_KEY'], algorithms=['HS256'])
+ return payload['sub']
+ except jwt.ExpiredSignatureError:
+ return None # Token has expired
+ except jwt.InvalidTokenError:
+ return None # Invalid token
+
+def token_required(f):
+ """Decorator to protect routes that require authentication"""
+ @wraps(f)
+ def decorated(*args, **kwargs):
+ token = None
+
+ # Get token from Authorization header
+ auth_header = request.headers.get('Authorization')
+ if auth_header and auth_header.startswith('Bearer '):
+ token = auth_header.split(' ')[1]
+
+ # If no token is provided
+ if not token:
+ return jsonify({'message': 'Authentication token is missing!'}), 401
+
+ # Decode the token
+ user_id = decode_token(token)
+ if not user_id:
+ return jsonify({'message': 'Invalid or expired token!'}), 401
+
+ # Check if user exists
+ conn = None
+ try:
+ conn = get_db_connection()
+ with conn.cursor() as cur:
+ cur.execute('SELECT id, username, email, is_admin FROM users WHERE id = %s AND is_active = TRUE', (user_id,))
+ user = cur.fetchone()
+
+ if not user:
+ return jsonify({'message': 'User not found or inactive!'}), 401
+
+ # Add user info to request context
+ request.user = {
+ 'id': user[0],
+ 'username': user[1],
+ 'email': user[2],
+ 'is_admin': user[3]
+ }
+
+ return f(*args, **kwargs)
+ except Exception as e:
+ logger.error(f"Authentication error: {e}")
+ return jsonify({'message': 'Authentication error!'}), 500
+ finally:
+ if conn:
+ release_db_connection(conn)
+
+ return decorated
+
+def admin_required(f):
+ """Decorator to protect routes that require admin privileges"""
+ @wraps(f)
+ def decorated(*args, **kwargs):
+ logger.info("Admin required check started")
+ token_required_result = token_required(lambda: None)()
+
+ if isinstance(token_required_result, tuple) and token_required_result[1] != 200:
+ logger.error(f"Token validation failed: {token_required_result}")
+ return token_required_result
+
+ logger.info(f"User info: {request.user}")
+ if not request.user.get('is_admin', False):
+ logger.error(f"User {request.user.get('username')} is not an admin")
+ return jsonify({'message': 'Admin privileges required!'}), 403
+
+ logger.info(f"Admin check passed for user {request.user.get('username')}")
+ return f(*args, **kwargs)
+
+ return decorated
+
+def is_valid_email(email):
+ """Validate email format"""
+ pattern = r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$'
+ return re.match(pattern, email) is not None
+
+def is_valid_password(password):
+ """Validate password strength"""
+ # At least 8 characters, 1 uppercase, 1 lowercase, 1 number
+ if len(password) < 8:
+ return False
+ if not re.search(r'[A-Z]', password):
+ return False
+ if not re.search(r'[a-z]', password):
+ return False
+ if not re.search(r'[0-9]', password):
+ return False
+ return True
+
+# Authentication routes
[email protected]('/api/auth/register', methods=['POST'])
+def register():
+ conn = None
+ try:
+ data = request.get_json()
+
+ # Check if registration is enabled
+ conn = get_db_connection()
+ with conn.cursor() as cur:
+ # Check if settings table exists
+ cur.execute("""
+ SELECT EXISTS (
+ SELECT FROM information_schema.tables
+ WHERE table_name = 'site_settings'
+ )
+ """)
+ table_exists = cur.fetchone()[0]
+
+ registration_enabled = True
+ if table_exists:
+ # Get registration_enabled setting
+ cur.execute("SELECT value FROM site_settings WHERE key = 'registration_enabled'")
+ result = cur.fetchone()
+
+ if result:
+ registration_enabled = result[0].lower() == 'true'
+
+ # Check if there are any users (first user can register regardless of setting)
+ cur.execute('SELECT COUNT(*) FROM users')
+ user_count = cur.fetchone()[0]
+
+ # If registration is disabled and this is not the first user, return error
+ if not registration_enabled and user_count > 0:
+ return jsonify({'message': 'Registration is currently disabled!'}), 403
+
+ # Validate required fields
+ required_fields = ['username', 'email', 'password']
+ for field in required_fields:
+ if field not in data or not data[field]:
+ return jsonify({'message': f'{field} is required!'}), 400
+
+ username = data['username']
+ email = data['email']
+ password = data['password']
+ first_name = data.get('first_name', '')
+ last_name = data.get('last_name', '')
+
+ # Validate email format
+ if not is_valid_email(email):
+ return jsonify({'message': 'Invalid email format!'}), 400
+
+ # Validate password strength
+ if not is_valid_password(password):
+ return jsonify({'message': 'Password must be at least 8 characters and include uppercase, lowercase, and numbers!'}), 400
+
+ # Hash the password
+ password_hash = bcrypt.generate_password_hash(password).decode('utf-8')
+
+ with conn.cursor() as cur:
+ # Check if username or email already exists
+ cur.execute('SELECT id FROM users WHERE username = %s OR email = %s', (username, email))
+ existing_user = cur.fetchone()
+
+ if existing_user:
+ return jsonify({'message': 'Username or email already exists!'}), 409
+
+ # Check if this is the first user (who will be an admin)
+ cur.execute('SELECT COUNT(*) FROM users')
+ user_count = cur.fetchone()[0]
+ is_admin = user_count == 0
+
+ # Insert new user
+ cur.execute(
+ 'INSERT INTO users (username, email, password_hash, first_name, last_name, is_admin) VALUES (%s, %s, %s, %s, %s, %s) RETURNING id',
+ (username, email, password_hash, first_name, last_name, is_admin)
+ )
+ user_id = cur.fetchone()[0]
+
+ # Generate token
+ token = generate_token(user_id)
+
+ # Update last login
+ cur.execute('UPDATE users SET last_login = %s WHERE id = %s', (datetime.utcnow(), user_id))
+
+ conn.commit()
+
+ return jsonify({
+ 'message': 'User registered successfully!',
+ 'token': token,
+ 'user': {
+ 'id': user_id,
+ 'username': username,
+ 'email': email,
+ 'is_admin': is_admin
+ }
+ }), 201
+ except Exception as e:
+ logger.error(f"Registration error: {e}")
+ if conn:
+ conn.rollback()
+ return jsonify({'message': 'Registration failed!'}), 500
+ finally:
+ if conn:
+ release_db_connection(conn)
+
[email protected]('/api/auth/login', methods=['POST'])
+def login():
+ conn = None
+ try:
+ data = request.get_json()
+
+ # Validate required fields
+ if not data.get('username') or not data.get('password'):
+ return jsonify({'message': 'Username and password are required!'}), 400
+
+ username = data['username']
+ password = data['password']
+
+ 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))
+ user = cur.fetchone()
+
+ if not user or not bcrypt.check_password_hash(user[3], password):
+ return jsonify({'message': 'Invalid username or password!'}), 401
+
+ if not user[4]: # is_active
+ return jsonify({'message': 'Account is inactive!'}), 401
+
+ user_id = user[0]
+
+ # Generate token
+ token = generate_token(user_id)
+
+ # Update last login
+ cur.execute('UPDATE users SET last_login = %s WHERE id = %s', (datetime.utcnow(), user_id))
+
+ # Store session info
+ ip_address = request.remote_addr
+ user_agent = request.headers.get('User-Agent', '')
+ session_token = str(uuid.uuid4())
+ expires_at = datetime.utcnow() + app.config['JWT_EXPIRATION_DELTA']
+
+ cur.execute(
+ 'INSERT INTO user_sessions (user_id, session_token, expires_at, ip_address, user_agent) VALUES (%s, %s, %s, %s, %s)',
+ (user_id, session_token, expires_at, ip_address, user_agent)
+ )
+
+ conn.commit()
+
+ # Check if remember_me is set
+ remember_me = data.get('remember_me', False)
+
+ # Create response
+ response_data = {
+ 'message': 'Login successful!',
+ 'token': token,
+ 'user': {
+ 'id': user_id,
+ 'username': user[1],
+ 'email': user[2]
+ }
+ }
+
+ if remember_me:
+ # Set longer expiration for persistent session
+ persistent_expires = datetime.utcnow() + timedelta(days=30)
+
+ # Update session expiration in database
+ cur.execute(
+ 'UPDATE user_sessions SET expires_at = %s WHERE session_token = %s',
+ (persistent_expires, session_token)
+ )
+ conn.commit()
+
+ # Create response with cookie
+ response = jsonify(response_data)
+
+ # Set secure cookie with 30-day expiration
+ response.set_cookie(
+ 'session_token',
+ session_token,
+ expires=persistent_expires,
+ httponly=True,
+ secure=request.is_secure,
+ samesite='Strict'
+ )
+
+ return response, 200
+ else:
+ # Return regular response without cookie
+ return jsonify(response_data), 200
+ except Exception as e:
+ logger.error(f"Login error: {e}")
+ if conn:
+ conn.rollback()
+ return jsonify({'message': 'Login failed!'}), 500
+ finally:
+ if conn:
+ release_db_connection(conn)
+
[email protected]('/api/auth/logout', methods=['POST'])
+@token_required
+def logout():
+ conn = None
+ try:
+ # Get user ID from token
+ token = request.headers.get('Authorization').split(' ')[1]
+ user_id = decode_token(token)
+
+ # Invalidate session
+ conn = get_db_connection()
+ with conn.cursor() as cur:
+ cur.execute('DELETE FROM user_sessions WHERE user_id = %s', (user_id,))
+ conn.commit()
+
+ return jsonify({'message': 'Logout successful!'}), 200
+ except Exception as e:
+ logger.error(f"Logout error: {e}")
+ if conn:
+ conn.rollback()
+ return jsonify({'message': 'Logout failed!'}), 500
+ finally:
+ if conn:
+ release_db_connection(conn)
+
[email protected]('/api/auth/auto-login', methods=['POST'])
+def auto_login():
+ conn = None
+ try:
+ # Get IP address and user agent
+ ip_address = request.remote_addr
+ user_agent = request.headers.get('User-Agent', '')
+
+ # Check for session cookie
+ session_cookie = request.cookies.get('session_token')
+
+ if not session_cookie:
+ return jsonify({'message': 'No session found'}), 401
+
+ conn = get_db_connection()
+ with conn.cursor() as cur:
+ # Find valid session
+ cur.execute(
+ 'SELECT user_id FROM user_sessions WHERE session_token = %s AND expires_at > %s AND ip_address = %s',
+ (session_cookie, datetime.utcnow(), ip_address)
+ )
+ session = cur.fetchone()
+
+ if not session:
+ return jsonify({'message': 'Invalid or expired session'}), 401
+
+ user_id = session[0]
+
+ # Get user info
+ cur.execute('SELECT id, username, email, is_active FROM users WHERE id = %s', (user_id,))
+ user = cur.fetchone()
+
+ if not user or not user[3]: # Check if user exists and is active
+ return jsonify({'message': 'User not found or inactive'}), 401
+
+ # Generate new token
+ token = generate_token(user_id)
+
+ # Update session expiration
+ new_expires_at = datetime.utcnow() + app.config['JWT_EXPIRATION_DELTA']
+ cur.execute(
+ 'UPDATE user_sessions SET expires_at = %s WHERE session_token = %s',
+ (new_expires_at, session_cookie)
+ )
+
+ # Update last login
+ cur.execute('UPDATE users SET last_login = %s WHERE id = %s', (datetime.utcnow(), user_id))
+ conn.commit()
+
+ # Set session cookie in response
+ response = jsonify({
+ 'message': 'Auto-login successful!',
+ 'token': token,
+ 'user': {
+ 'id': user[0],
+ 'username': user[1],
+ 'email': user[2]
+ }
+ })
+
+ # Set secure cookie with same expiration as token
+ response.set_cookie(
+ 'session_token',
+ session_cookie,
+ expires=new_expires_at,
+ httponly=True,
+ secure=request.is_secure,
+ samesite='Strict'
+ )
+
+ return response, 200
+ except Exception as e:
+ logger.error(f"Auto-login error: {e}")
+ if conn:
+ conn.rollback()
+ return jsonify({'message': 'Auto-login failed!'}), 500
+ finally:
+ if conn:
+ release_db_connection(conn)
+
[email protected]('/api/auth/validate-token', methods=['GET'])
+@token_required
+def validate_token():
+ """Validate JWT token and return user info"""
+ try:
+ # If we got here, the token is valid (token_required decorator validated it)
+ return jsonify({
+ 'valid': True,
+ 'user': {
+ 'id': request.user['id'],
+ 'username': request.user['username'],
+ 'email': request.user['email'],
+ 'is_admin': request.user['is_admin']
+ },
+ 'message': 'Token is valid'
+ }), 200
+ except Exception as e:
+ logger.error(f"Token validation error: {e}")
+ return jsonify({
+ 'valid': False,
+ 'message': 'Invalid token'
+ }), 401
+
[email protected]('/api/auth/user', methods=['GET'])
+@token_required
+def get_user():
+ try:
+ user = request.user
+ return jsonify({
+ 'id': user['id'],
+ 'username': user['username'],
+ 'email': user['email'],
+ 'is_admin': user['is_admin']
+ }), 200
+ except Exception as e:
+ logger.error(f"Get user error: {e}")
+ return jsonify({'message': 'Failed to retrieve user information!'}), 500
+
[email protected]('/api/auth/password/reset-request', methods=['POST'])
+def request_password_reset():
+ conn = None
+ try:
+ data = request.get_json()
+
+ if not data.get('email'):
+ return jsonify({'message': 'Email is required!'}), 400
+
+ email = data['email']
+
+ conn = get_db_connection()
+ with conn.cursor() as cur:
+ # Check if user exists
+ cur.execute('SELECT id FROM users WHERE email = %s', (email,))
+ user = cur.fetchone()
+
+ if not user:
+ # Don't reveal if email exists or not for security
+ return jsonify({'message': 'If your email is registered, you will receive a password reset link.'}), 200
+
+ user_id = user[0]
+
+ # Generate reset token
+ reset_token = str(uuid.uuid4())
+ expires_at = datetime.utcnow() + timedelta(hours=24)
+
+ # Delete any existing tokens for this user
+ cur.execute('DELETE FROM password_reset_tokens WHERE user_id = %s', (user_id,))
+
+ # Insert new token
+ cur.execute(
+ 'INSERT INTO password_reset_tokens (user_id, token, expires_at) VALUES (%s, %s, %s)',
+ (user_id, reset_token, expires_at)
+ )
+
+ conn.commit()
+
+ # In a real application, you would send an email with the reset link
+ # For now, we'll just return the token in the response (for testing purposes)
+ reset_link = f"/reset-password?token={reset_token}"
+
+ logger.info(f"Password reset requested for user {user_id}. Reset link: {reset_link}")
+
+ return jsonify({
+ 'message': 'If your email is registered, you will receive a password reset link.',
+ 'reset_link': reset_link # Remove this in production
+ }), 200
+ except Exception as e:
+ logger.error(f"Password reset request error: {e}")
+ if conn:
+ conn.rollback()
+ return jsonify({'message': 'Password reset request failed!'}), 500
+ finally:
+ if conn:
+ release_db_connection(conn)
+
[email protected]('/api/auth/password/reset', methods=['POST'])
+def reset_password():
+ conn = None
+ try:
+ data = request.get_json()
+
+ if not data.get('token') or not data.get('password'):
+ return jsonify({'message': 'Token and password are required!'}), 400
+
+ token = data['token']
+ password = data['password']
+
+ # Validate password strength
+ if not is_valid_password(password):
+ return jsonify({'message': 'Password must be at least 8 characters and include uppercase, lowercase, and numbers!'}), 400
+
+ conn = get_db_connection()
+ with conn.cursor() as cur:
+ # Check if token exists and is valid
+ cur.execute('SELECT user_id, expires_at FROM password_reset_tokens WHERE token = %s', (token,))
+ token_info = cur.fetchone()
+
+ if not token_info or token_info[1] < datetime.utcnow():
+ return jsonify({'message': 'Invalid or expired token!'}), 400
+
+ user_id = token_info[0]
+
+ # Hash the new password
+ password_hash = bcrypt.generate_password_hash(password).decode('utf-8')
+
+ # Update user's password
+ cur.execute('UPDATE users SET password_hash = %s WHERE id = %s', (password_hash, user_id))
+
+ # Delete the used token
+ cur.execute('DELETE FROM password_reset_tokens WHERE token = %s', (token,))
+
+ conn.commit()
+
+ return jsonify({'message': 'Password reset successful!'}), 200
+ except Exception as e:
+ logger.error(f"Password reset error: {e}")
+ if conn:
+ conn.rollback()
+ return jsonify({'message': 'Password reset failed!'}), 500
+ finally:
+ if conn:
+ release_db_connection(conn)
+
[email protected]('/api/auth/password/change', methods=['POST'])
+@token_required
+def change_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']
+
+ # Validate password strength
+ if not is_valid_password(new_password):
+ return jsonify({'message': 'Password must be at least 8 characters and include uppercase, lowercase, and numbers!'}), 400
+
+ user_id = request.user['id']
+
+ conn = get_db_connection()
+ with conn.cursor() as cur:
+ # Check current password
+ cur.execute('SELECT password_hash FROM users WHERE id = %s', (user_id,))
+ user = cur.fetchone()
+
+ if not user or not bcrypt.check_password_hash(user[0], current_password):
+ return jsonify({'message': 'Current password is incorrect!'}), 401
+
+ # Hash the new password
+ password_hash = bcrypt.generate_password_hash(new_password).decode('utf-8')
+
+ # Update user's password
+ cur.execute('UPDATE users SET password_hash = %s WHERE id = %s', (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': 'Password change failed!'}), 500
+ finally:
+ if conn:
+ release_db_connection(conn)
+
+# Update existing endpoints to use authentication
+
@app.route('/api/warranties', methods=['GET'])
+@token_required
def get_warranties():
conn = None
try:
conn = get_db_connection()
+ user_id = request.user['id']
+ is_admin = request.user['is_admin']
+
with conn.cursor() as cur:
- cur.execute('SELECT * FROM warranties ORDER BY expiration_date')
+ # If admin, can see all warranties, otherwise only user's warranties
+ if is_admin:
+ cur.execute('SELECT * FROM warranties ORDER BY expiration_date')
+ else:
+ cur.execute('SELECT * FROM warranties WHERE user_id = %s ORDER BY expiration_date', (user_id,))
+
warranties = cur.fetchall()
columns = [desc[0] for desc in cur.description]
warranties_list = []
@@ -171,6 +883,7 @@ def get_warranties():
release_db_connection(conn)
@app.route('/api/warranties', methods=['POST'])
+@token_required
def add_warranty():
conn = None
try:
@@ -193,6 +906,7 @@ def add_warranty():
purchase_date_str = request.form['purchase_date']
serial_numbers = request.form.getlist('serial_numbers')
product_url = request.form.get('product_url', '')
+ user_id = request.user['id']
# Handle purchase price (optional)
purchase_price = None
@@ -254,10 +968,10 @@ def add_warranty():
with conn.cursor() as cur:
# Insert warranty
cur.execute('''
- INSERT INTO warranties (product_name, purchase_date, warranty_years, expiration_date, invoice_path, manual_path, product_url, purchase_price)
- VALUES (%s, %s, %s, %s, %s, %s, %s, %s)
+ INSERT INTO warranties (product_name, purchase_date, warranty_years, expiration_date, invoice_path, manual_path, product_url, purchase_price, user_id)
+ VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s)
RETURNING id
- ''', (product_name, purchase_date, warranty_years, expiration_date, db_invoice_path, db_manual_path, product_url, purchase_price))
+ ''', (product_name, purchase_date, warranty_years, expiration_date, db_invoice_path, db_manual_path, product_url, purchase_price, user_id))
warranty_id = cur.fetchone()[0]
# Insert serial numbers
@@ -286,18 +1000,30 @@ def add_warranty():
release_db_connection(conn)
@app.route('/api/warranties/<int:warranty_id>', methods=['DELETE'])
+@token_required
def delete_warranty(warranty_id):
conn = None
try:
+ user_id = request.user['id']
+ is_admin = request.user['is_admin']
+
conn = get_db_connection()
with conn.cursor() as cur:
+ # Check if warranty exists and belongs to the user
+ if is_admin:
+ cur.execute('SELECT id FROM warranties WHERE id = %s', (warranty_id,))
+ else:
+ cur.execute('SELECT id FROM warranties WHERE id = %s AND user_id = %s', (warranty_id, user_id))
+
+ warranty = cur.fetchone()
+
+ if not warranty:
+ return jsonify({"error": "Warranty not found or you don't have permission to delete it"}), 404
+
# First get the invoice path to delete the file
cur.execute('SELECT invoice_path, manual_path FROM warranties WHERE id = %s', (warranty_id,))
result = cur.fetchone()
- if not result:
- return jsonify({"error": "Warranty not found"}), 404
-
invoice_path = result[0]
manual_path = result[1]
@@ -330,60 +1056,65 @@ def delete_warranty(warranty_id):
release_db_connection(conn)
@app.route('/api/warranties/<int:warranty_id>', methods=['PUT'])
+@token_required
def update_warranty(warranty_id):
conn = None
try:
- # Validate input data similar to the add_warranty route
- if not request.form.get('product_name'):
- return jsonify({"error": "Product name is required"}), 400
+ user_id = request.user['id']
+ is_admin = request.user['is_admin']
+
+ conn = get_db_connection()
+ with conn.cursor() as cur:
+ # Check if warranty exists and belongs to the user
+ if is_admin:
+ cur.execute('SELECT id FROM warranties WHERE id = %s', (warranty_id,))
+ else:
+ cur.execute('SELECT id FROM warranties WHERE id = %s AND user_id = %s', (warranty_id, user_id))
+
+ warranty = cur.fetchone()
- if not request.form.get('purchase_date'):
- return jsonify({"error": "Purchase date is required"}), 400
+ if not warranty:
+ return jsonify({"error": "Warranty not found or you don't have permission to update it"}), 404
- try:
- warranty_years = int(request.form.get('warranty_years', '0'))
- if warranty_years <= 0 or warranty_years > 100:
- return jsonify({"error": "Warranty years must be between 1 and 100"}), 400
- except ValueError:
- return jsonify({"error": "Warranty years must be a valid number"}), 400
-
- # Process the data
- product_name = request.form['product_name']
- purchase_date_str = request.form['purchase_date']
- serial_numbers = request.form.getlist('serial_numbers')
- product_url = request.form.get('product_url', '')
-
- # Handle purchase price (optional)
- purchase_price = None
- if request.form.get('purchase_price'):
+ # Validate input data similar to the add_warranty route
+ if not request.form.get('product_name'):
+ return jsonify({"error": "Product name is required"}), 400
+
+ if not request.form.get('purchase_date'):
+ return jsonify({"error": "Purchase date is required"}), 400
+
try:
- purchase_price = float(request.form.get('purchase_price'))
- if purchase_price < 0:
- return jsonify({"error": "Purchase price cannot be negative"}), 400
+ warranty_years = int(request.form.get('warranty_years', '0'))
+ if warranty_years <= 0 or warranty_years > 100:
+ return jsonify({"error": "Warranty years must be between 1 and 100"}), 400
except ValueError:
- return jsonify({"error": "Purchase price must be a valid number"}), 400
-
- try:
- purchase_date = datetime.strptime(purchase_date_str, '%Y-%m-%d')
- except ValueError:
- return jsonify({"error": "Invalid date format. Use YYYY-MM-DD"}), 400
+ return jsonify({"error": "Warranty years must be a valid number"}), 400
+
+ # Process the data
+ product_name = request.form['product_name']
+ purchase_date_str = request.form['purchase_date']
+ serial_numbers = request.form.getlist('serial_numbers')
+ product_url = request.form.get('product_url', '')
- expiration_date = purchase_date + timedelta(days=warranty_years * 365)
-
- conn = get_db_connection()
- with conn.cursor() as cur:
- # Check if warranty exists
- cur.execute('SELECT invoice_path, manual_path FROM warranties WHERE id = %s', (warranty_id,))
- result = cur.fetchone()
+ # Handle purchase price (optional)
+ purchase_price = None
+ if request.form.get('purchase_price'):
+ try:
+ purchase_price = float(request.form.get('purchase_price'))
+ if purchase_price < 0:
+ return jsonify({"error": "Purchase price cannot be negative"}), 400
+ except ValueError:
+ return jsonify({"error": "Purchase price must be a valid number"}), 400
- if not result:
- return jsonify({"error": "Warranty not found"}), 404
+ try:
+ purchase_date = datetime.strptime(purchase_date_str, '%Y-%m-%d')
+ except ValueError:
+ return jsonify({"error": "Invalid date format. Use YYYY-MM-DD"}), 400
- old_invoice_path = result[0]
- old_manual_path = result[1]
+ expiration_date = purchase_date + timedelta(days=warranty_years * 365)
# Handle invoice file upload if new file is provided
- db_invoice_path = old_invoice_path
+ db_invoice_path = None
if 'invoice' in request.files:
invoice = request.files['invoice']
if invoice.filename != '':
@@ -398,13 +1129,15 @@ def update_warranty(warranty_id):
db_invoice_path = os.path.join('uploads', filename)
# Remove old invoice file if exists and different from new one
+ cur.execute('SELECT invoice_path FROM warranties WHERE id = %s', (warranty_id,))
+ old_invoice_path = cur.fetchone()[0]
if old_invoice_path and old_invoice_path != db_invoice_path:
old_full_path = os.path.join('/data', old_invoice_path)
if os.path.exists(old_full_path):
os.remove(old_full_path)
# Handle manual file upload if new file is provided
- db_manual_path = old_manual_path
+ db_manual_path = None
if 'manual' in request.files:
manual = request.files['manual']
if manual.filename != '':
@@ -419,6 +1152,8 @@ def update_warranty(warranty_id):
db_manual_path = os.path.join('uploads', filename)
# Remove old manual file if exists and different from new one
+ cur.execute('SELECT manual_path FROM warranties WHERE id = %s', (warranty_id,))
+ old_manual_path = cur.fetchone()[0]
if old_manual_path and old_manual_path != db_manual_path:
old_full_path = os.path.join('/data', old_manual_path)
if os.path.exists(old_full_path):
@@ -458,127 +1193,123 @@ def update_warranty(warranty_id):
if conn:
release_db_connection(conn)
[email protected]('/uploads/<path:filename>')
-def uploaded_file(filename):
- """Serve files from the uploads directory."""
- try:
- # Simple and direct file serving
- return send_from_directory('/data/uploads', filename)
- except Exception as e:
- logger.error(f"Error serving file {filename}: {e}")
- return jsonify({"error": f"Error serving file: {str(e)}"}), 500
-
-def request_entity_too_large(error):
- return jsonify({"error": "File too large. Maximum size is 16MB"}), 413
-
@app.route('/api/statistics', methods=['GET'])
+@token_required
def get_statistics():
conn = None
- cursor = None
try:
- logger.info("Statistics endpoint called")
- conn = get_db_connection()
- cursor = conn.cursor()
-
- # Calculate expiration ranges
- today = date.today()
- logger.info(f"Current date: {today}")
- thirty_days_later = today + timedelta(days=30)
- ninety_days_later = today + timedelta(days=90)
-
- # Get total count
- cursor.execute("SELECT COUNT(*) FROM warranties")
- total_count = cursor.fetchone()[0]
- logger.info(f"Total warranties: {total_count}")
-
- # Get active count
- cursor.execute("SELECT COUNT(*) FROM warranties WHERE expiration_date > %s", (today,))
- active_count = cursor.fetchone()[0]
- logger.info(f"Active warranties: {active_count}")
-
- # Get expired count
- cursor.execute("SELECT COUNT(*) FROM warranties WHERE expiration_date <= %s", (today,))
- expired_count = cursor.fetchone()[0]
- logger.info(f"Expired warranties: {expired_count}")
-
- # Get expiring soon count (30 days)
- cursor.execute("SELECT COUNT(*) FROM warranties WHERE expiration_date > %s AND expiration_date <= %s",
- (today, thirty_days_later))
- expiring_soon_count = cursor.fetchone()[0]
- logger.info(f"Expiring soon warranties: {expiring_soon_count}")
-
- # Get expiration timeline (next 90 days, grouped by month)
- cursor.execute("""
- SELECT
- EXTRACT(YEAR FROM expiration_date) as year,
- EXTRACT(MONTH FROM expiration_date) as month,
- COUNT(*) as count
- FROM warranties
- WHERE expiration_date > %s AND expiration_date <= %s
- GROUP BY EXTRACT(YEAR FROM expiration_date), EXTRACT(MONTH FROM expiration_date)
- ORDER BY year, month
- """, (today, ninety_days_later))
-
- timeline = []
- for row in cursor.fetchall():
- year = int(row[0])
- month = int(row[1])
- count = row[2]
- timeline.append({
- "year": year,
- "month": month,
- "count": count
- })
+ user_id = request.user['id']
+ is_admin = request.user['is_admin']
- # Get recent expiring warranties (30 days before and after today)
- thirty_days_ago = today - timedelta(days=30)
- cursor.execute("""
- SELECT
- id, product_name, purchase_date, warranty_years,
- expiration_date, invoice_path, manual_path, product_url, purchase_price
- FROM warranties
- WHERE expiration_date >= %s AND expiration_date <= %s
- ORDER BY expiration_date
- LIMIT 10
- """, (thirty_days_ago, thirty_days_later))
-
- columns = [desc[0] for desc in cursor.description]
- recent_warranties = []
-
- for row in cursor.fetchall():
- warranty = dict(zip(columns, row))
-
- # Convert dates to string format
- if warranty['purchase_date']:
- warranty['purchase_date'] = warranty['purchase_date'].isoformat()
- if warranty['expiration_date']:
- warranty['expiration_date'] = warranty['expiration_date'].isoformat()
-
- # Convert Decimal objects to float for JSON serialization
- if warranty.get('purchase_price') and isinstance(warranty['purchase_price'], Decimal):
- warranty['purchase_price'] = float(warranty['purchase_price'])
-
- recent_warranties.append(warranty)
-
- statistics = {
- 'total': total_count,
- 'active': active_count,
- 'expired': expired_count,
- 'expiring_soon': expiring_soon_count,
- 'timeline': timeline,
- 'recent_warranties': recent_warranties
- }
-
- return jsonify(statistics)
+ conn = get_db_connection()
+ with conn.cursor() as cur:
+ # Base query parts
+ from_clause = 'FROM warranties'
+ where_clause = ''
+ params = []
+
+ # Add user filtering if not admin
+ if not is_admin:
+ where_clause = 'WHERE user_id = %s'
+ params.append(user_id)
+
+ # Calculate expiration ranges
+ today = date.today()
+ logger.info(f"Current date: {today}")
+ thirty_days_later = today + timedelta(days=30)
+ ninety_days_later = today + timedelta(days=90)
+
+ # Get total count
+ cur.execute(f"SELECT COUNT(*) {from_clause} {where_clause}", params)
+ total_count = cur.fetchone()[0]
+ logger.info(f"Total warranties: {total_count}")
+
+ # Get active count
+ active_where = "WHERE" if not where_clause else "AND"
+ cur.execute(f"SELECT COUNT(*) {from_clause} {where_clause} {active_where if where_clause else 'WHERE'} expiration_date > %s", params + [today])
+ active_count = cur.fetchone()[0]
+ logger.info(f"Active warranties: {active_count}")
+
+ # Get expired count
+ cur.execute(f"SELECT COUNT(*) {from_clause} {where_clause} {active_where if where_clause else 'WHERE'} expiration_date <= %s", params + [today])
+ expired_count = cur.fetchone()[0]
+ logger.info(f"Expired warranties: {expired_count}")
+
+ # Get expiring soon count (30 days)
+ cur.execute(f"SELECT COUNT(*) {from_clause} {where_clause} {active_where if where_clause else 'WHERE'} expiration_date > %s AND expiration_date <= %s",
+ params + [today, thirty_days_later])
+ expiring_soon_count = cur.fetchone()[0]
+ logger.info(f"Expiring soon warranties: {expiring_soon_count}")
+
+ # Get expiration timeline (next 90 days, grouped by month)
+ cur.execute(f"""
+ SELECT
+ EXTRACT(YEAR FROM expiration_date) as year,
+ EXTRACT(MONTH FROM expiration_date) as month,
+ COUNT(*) as count
+ {from_clause}
+ {where_clause} {active_where if where_clause else 'WHERE'} expiration_date > %s AND expiration_date <= %s
+ GROUP BY EXTRACT(YEAR FROM expiration_date), EXTRACT(MONTH FROM expiration_date)
+ ORDER BY year, month
+ """, params + [today, ninety_days_later])
+
+ timeline = []
+ for row in cur.fetchall():
+ year = int(row[0])
+ month = int(row[1])
+ count = row[2]
+ timeline.append({
+ "year": year,
+ "month": month,
+ "count": count
+ })
+
+ # Get recent expiring warranties (30 days before and after today)
+ thirty_days_ago = today - timedelta(days=30)
+ cur.execute(f"""
+ SELECT
+ id, product_name, purchase_date, warranty_years,
+ expiration_date, invoice_path, manual_path, product_url, purchase_price
+ {from_clause}
+ {where_clause} {active_where if where_clause else 'WHERE'} expiration_date >= %s AND expiration_date <= %s
+ ORDER BY expiration_date
+ LIMIT 10
+ """, params + [thirty_days_ago, thirty_days_later])
+
+ columns = [desc[0] for desc in cur.description]
+ recent_warranties = []
+
+ for row in cur.fetchall():
+ warranty = dict(zip(columns, row))
+
+ # Convert dates to string format
+ if warranty['purchase_date']:
+ warranty['purchase_date'] = warranty['purchase_date'].isoformat()
+ if warranty['expiration_date']:
+ warranty['expiration_date'] = warranty['expiration_date'].isoformat()
+
+ # Convert Decimal objects to float for JSON serialization
+ if warranty.get('purchase_price') and isinstance(warranty['purchase_price'], Decimal):
+ warranty['purchase_price'] = float(warranty['purchase_price'])
+
+ recent_warranties.append(warranty)
+
+ statistics = {
+ 'total': total_count,
+ 'active': active_count,
+ 'expired': expired_count,
+ 'expiring_soon': expiring_soon_count,
+ 'timeline': timeline,
+ 'recent_warranties': recent_warranties
+ }
+
+ return jsonify(statistics)
except Exception as e:
logger.error(f"Error getting warranty statistics: {e}")
return jsonify({"error": str(e)}), 500
finally:
- if cursor:
- cursor.close()
if conn:
release_db_connection(conn)
@@ -587,13 +1318,609 @@ def test_endpoint():
"""Simple test endpoint to check if the API is responding."""
return jsonify({
"status": "success",
- "message": "API is responding correctly",
- "timestamp": datetime.now().isoformat()
+ "message": "API is working",
+ "timestamp": datetime.utcnow().isoformat()
+ })
+
+# Public endpoint to check if authentication is required
[email protected]('/api/auth/status', methods=['GET'])
+def auth_status():
+ return jsonify({
+ "authentication_required": True,
+ "message": "Authentication is required for most endpoints"
})
[email protected]('/api/auth/profile', methods=['PUT'])
+@token_required
+def update_profile():
+ user_id = request.user['id']
+
+ try:
+ # Get request data
+ data = request.get_json()
+
+ if not data:
+ return jsonify({'message': 'No input data provided'}), 400
+
+ # Extract fields
+ first_name = data.get('first_name', '').strip()
+ last_name = data.get('last_name', '').strip()
+
+ # Validate input
+ if not first_name or not last_name:
+ return jsonify({'message': 'First name and last name are required'}), 400
+
+ # Get database connection
+ conn = get_db_connection()
+ cursor = conn.cursor()
+
+ try:
+ # Update user profile
+ cursor.execute(
+ """
+ UPDATE users
+ SET first_name = %s, last_name = %s, updated_at = NOW()
+ WHERE id = %s
+ RETURNING id, username, email, first_name, last_name, created_at, updated_at
+ """,
+ (first_name, last_name, user_id)
+ )
+
+ # Get updated user data
+ user_data = cursor.fetchone()
+
+ if not user_data:
+ return jsonify({'message': 'User not found'}), 404
+
+ # Commit changes
+ conn.commit()
+
+ # Format user data
+ user = {
+ 'id': user_data[0],
+ 'username': user_data[1],
+ 'email': user_data[2],
+ 'first_name': user_data[3],
+ 'last_name': user_data[4],
+ 'created_at': user_data[5].isoformat() if user_data[5] else None,
+ 'updated_at': user_data[6].isoformat() if user_data[6] else None
+ }
+
+ return jsonify(user), 200
+
+ except Exception as e:
+ conn.rollback()
+ logger.error(f"Database error in update_profile: {str(e)}")
+ return jsonify({'message': 'Database error occurred'}), 500
+ finally:
+ cursor.close()
+ release_db_connection(conn)
+
+ except Exception as e:
+ logger.error(f"Error in update_profile: {str(e)}")
+ return jsonify({'message': 'An error occurred while updating profile'}), 500
+
[email protected]('/api/auth/account', methods=['DELETE'])
+@token_required
+def delete_account():
+ user_id = request.user['id']
+
+ try:
+ # Get database connection
+ conn = get_db_connection()
+ cursor = conn.cursor()
+
+ try:
+ # Begin transaction
+ cursor.execute("BEGIN")
+
+ # Delete user's warranties
+ cursor.execute("DELETE FROM warranties WHERE user_id = %s", (user_id,))
+
+ # Delete user's reset tokens if any
+ cursor.execute("DELETE FROM password_reset_tokens WHERE user_id = %s", (user_id,))
+
+ # Delete user
+ cursor.execute("DELETE FROM users WHERE id = %s", (user_id,))
+
+ # Commit transaction
+ cursor.execute("COMMIT")
+
+ return jsonify({'message': 'Account deleted successfully'}), 200
+
+ except Exception as e:
+ cursor.execute("ROLLBACK")
+ logger.error(f"Database error in delete_account: {str(e)}")
+ return jsonify({'message': 'Database error occurred'}), 500
+ finally:
+ cursor.close()
+ release_db_connection(conn)
+
+ except Exception as e:
+ logger.error(f"Error in delete_account: {str(e)}")
+ return jsonify({'message': 'An error occurred while deleting account'}), 500
+
[email protected]('/api/auth/preferences', methods=['GET'])
+@token_required
+def get_preferences():
+ user_id = request.user['id']
+
+ try:
+ # Get database connection
+ conn = get_db_connection()
+ cursor = conn.cursor()
+
+ try:
+ # Get user preferences
+ cursor.execute(
+ """
+ SELECT email_notifications, default_view, theme
+ FROM user_preferences
+ WHERE user_id = %s
+ """,
+ (user_id,)
+ )
+
+ preferences_data = cursor.fetchone()
+
+ if not preferences_data:
+ # Create default preferences if not exists
+ cursor.execute(
+ """
+ INSERT INTO user_preferences (user_id, email_notifications, default_view, theme)
+ VALUES (%s, TRUE, 'grid', 'light')
+ RETURNING email_notifications, default_view, theme
+ """,
+ (user_id,)
+ )
+
+ preferences_data = cursor.fetchone()
+ conn.commit()
+
+ # Format preferences data
+ preferences = {
+ 'email_notifications': preferences_data[0],
+ 'default_view': preferences_data[1],
+ 'theme': preferences_data[2]
+ }
+
+ return jsonify(preferences), 200
+
+ except Exception as e:
+ conn.rollback()
+ logger.error(f"Database error in get_preferences: {str(e)}")
+ return jsonify({'message': 'Database error occurred'}), 500
+ finally:
+ cursor.close()
+ release_db_connection(conn)
+
+ except Exception as e:
+ logger.error(f"Error in get_preferences: {str(e)}")
+ return jsonify({'message': 'An error occurred while getting preferences'}), 500
+
[email protected]('/api/auth/preferences', methods=['PUT'])
+@token_required
+def update_preferences():
+ user_id = request.user['id']
+
+ try:
+ # Get request data
+ data = request.get_json()
+
+ if not data:
+ return jsonify({'message': 'No input data provided'}), 400
+
+ # Extract fields
+ email_notifications = data.get('email_notifications')
+ default_view = data.get('default_view')
+ theme = data.get('theme')
+
+ # Validate input
+ if default_view and default_view not in ['grid', 'list', 'table']:
+ return jsonify({'message': 'Invalid default view'}), 400
+
+ if theme and theme not in ['light', 'dark']:
+ return jsonify({'message': 'Invalid theme'}), 400
+
+ # Get database connection
+ conn = get_db_connection()
+ cursor = conn.cursor()
+
+ try:
+ # Check if preferences exist
+ cursor.execute(
+ "SELECT 1 FROM user_preferences WHERE user_id = %s",
+ (user_id,)
+ )
+
+ preferences_exist = cursor.fetchone() is not None
+
+ if preferences_exist:
+ # Update existing preferences
+ update_fields = []
+ update_values = []
+
+ if email_notifications is not None:
+ update_fields.append("email_notifications = %s")
+ update_values.append(email_notifications)
+
+ if default_view:
+ update_fields.append("default_view = %s")
+ update_values.append(default_view)
+
+ if theme:
+ update_fields.append("theme = %s")
+ update_values.append(theme)
+
+ if update_fields:
+ update_query = f"""
+ UPDATE user_preferences
+ SET {', '.join(update_fields)}, updated_at = NOW()
+ WHERE user_id = %s
+ RETURNING email_notifications, default_view, theme
+ """
+
+ cursor.execute(update_query, update_values + [user_id])
+ preferences_data = cursor.fetchone()
+ else:
+ # No fields to update
+ cursor.execute(
+ """
+ SELECT email_notifications, default_view, theme
+ FROM user_preferences
+ WHERE user_id = %s
+ """,
+ (user_id,)
+ )
+ preferences_data = cursor.fetchone()
+ else:
+ # Create new preferences
+ cursor.execute(
+ """
+ INSERT INTO user_preferences (
+ user_id,
+ email_notifications,
+ default_view,
+ theme
+ )
+ VALUES (%s, %s, %s, %s)
+ RETURNING email_notifications, default_view, theme
+ """,
+ (
+ user_id,
+ email_notifications if email_notifications is not None else True,
+ default_view or 'grid',
+ theme or 'light'
+ )
+ )
+
+ preferences_data = cursor.fetchone()
+
+ # Commit changes
+ conn.commit()
+
+ # Format preferences data
+ preferences = {
+ 'email_notifications': preferences_data[0],
+ 'default_view': preferences_data[1],
+ 'theme': preferences_data[2]
+ }
+
+ return jsonify(preferences), 200
+
+ except Exception as e:
+ conn.rollback()
+ logger.error(f"Database error in update_preferences: {str(e)}")
+ return jsonify({'message': 'Database error occurred'}), 500
+ finally:
+ cursor.close()
+ release_db_connection(conn)
+
+ except Exception as e:
+ logger.error(f"Error in update_preferences: {str(e)}")
+ return jsonify({'message': 'An error occurred while updating preferences'}), 500
+
+# Admin User Management Endpoints
+
[email protected]('/api/admin/users', methods=['GET'])
+@admin_required
+def get_all_users():
+ """Get all users (admin only)"""
+ conn = None
+ try:
+ conn = get_db_connection()
+ with conn.cursor() as cur:
+ cur.execute('''
+ SELECT id, username, email, first_name, last_name, is_active, is_admin, created_at, last_login
+ FROM users
+ ORDER BY created_at DESC
+ ''')
+ users = cur.fetchall()
+ columns = [desc[0] for desc in cur.description]
+ users_list = []
+
+ for row in users:
+ user_dict = dict(zip(columns, row))
+ # Convert date objects to ISO format strings for JSON serialization
+ for key, value in user_dict.items():
+ if isinstance(value, (datetime, date)):
+ user_dict[key] = value.isoformat() if value else None
+
+ users_list.append(user_dict)
+
+ return jsonify(users_list), 200
+ except Exception as e:
+ logger.error(f"Error retrieving users: {e}")
+ return jsonify({"message": "Failed to retrieve users"}), 500
+ finally:
+ if conn:
+ release_db_connection(conn)
+
[email protected]('/api/admin/users/<int:user_id>', methods=['PUT'])
+@admin_required
+def update_user(user_id):
+ """Update user details (admin only)"""
+ conn = None
+ try:
+ # Prevent modifying self
+ if user_id == request.user['id']:
+ return jsonify({"message": "Cannot modify your own admin status"}), 403
+
+ data = request.get_json()
+
+ # Use regular connection since warranty_user now has superuser privileges
+ conn = get_db_connection()
+ with conn.cursor() as cur:
+ # Check if user exists
+ cur.execute('SELECT id FROM users WHERE id = %s', (user_id,))
+ user = cur.fetchone()
+
+ if not user:
+ return jsonify({"message": "User not found"}), 404
+
+ # Update fields
+ updates = []
+ params = []
+
+ if 'is_admin' in data:
+ updates.append('is_admin = %s')
+ params.append(bool(data['is_admin']))
+
+ if 'is_active' in data:
+ updates.append('is_active = %s')
+ params.append(bool(data['is_active']))
+
+ if not updates:
+ return jsonify({"message": "No fields to update"}), 400
+
+ # Build and execute update query
+ query = f"UPDATE users SET {', '.join(updates)} WHERE id = %s"
+ params.append(user_id)
+
+ cur.execute(query, params)
+ conn.commit()
+
+ return jsonify({"message": "User updated successfully"}), 200
+ except Exception as e:
+ logger.error(f"Error updating user: {e}")
+ if conn:
+ conn.rollback()
+ return jsonify({"message": f"Failed to update user: {str(e)}"}), 500
+ finally:
+ if conn:
+ release_db_connection(conn)
+
[email protected]('/api/admin/users/<int:user_id>', methods=['DELETE'])
+@admin_required
+def delete_user(user_id):
+ """Delete a user (admin only)"""
+ conn = None
+ try:
+ logger.info(f"Delete user request received for user_id: {user_id}")
+
+ # Prevent deleting self
+ if user_id == request.user['id']:
+ logger.warning(f"User {request.user['username']} attempted to delete their own account")
+ return jsonify({"message": "Cannot delete your own account through admin API"}), 403
+
+ # Use regular connection since warranty_user now has superuser privileges
+ conn = get_db_connection()
+ with conn.cursor() as cur:
+ # Check if user exists
+ cur.execute('SELECT id, username FROM users WHERE id = %s', (user_id,))
+ user = cur.fetchone()
+
+ if not user:
+ logger.warning(f"User with ID {user_id} not found")
+ return jsonify({"message": "User not found"}), 404
+
+ logger.info(f"Deleting user {user[1]} (ID: {user[0]})")
+
+ # Delete user's warranties first
+ cur.execute('DELETE FROM warranties WHERE user_id = %s', (user_id,))
+ warranties_deleted = cur.rowcount
+ logger.info(f"Deleted {warranties_deleted} warranties belonging to user {user_id}")
+
+ # Delete user's password reset tokens if any
+ cur.execute('DELETE FROM password_reset_tokens WHERE user_id = %s', (user_id,))
+ tokens_deleted = cur.rowcount
+ logger.info(f"Deleted {tokens_deleted} password reset tokens belonging to user {user_id}")
+
+ # Delete user's sessions if any
+ cur.execute('DELETE FROM user_sessions WHERE user_id = %s', (user_id,))
+ sessions_deleted = cur.rowcount
+ logger.info(f"Deleted {sessions_deleted} sessions belonging to user {user_id}")
+
+ # Delete user
+ cur.execute('DELETE FROM users WHERE id = %s', (user_id,))
+ user_deleted = cur.rowcount
+ logger.info(f"Deleted user {user_id}, affected rows: {user_deleted}")
+
+ conn.commit()
+ logger.info(f"User {user_id} deleted successfully")
+
+ return jsonify({"message": "User deleted successfully"}), 200
+ except Exception as e:
+ logger.error(f"Error deleting user: {e}")
+ if conn:
+ conn.rollback()
+ return jsonify({"message": f"Failed to delete user: {str(e)}"}), 500
+ finally:
+ if conn:
+ release_db_connection(conn)
+
+# Site settings
[email protected]('/api/admin/settings', methods=['GET'])
+@admin_required
+def get_site_settings():
+ """Get site settings (admin only)"""
+ conn = None
+ try:
+ conn = get_db_connection()
+ with conn.cursor() as cur:
+ # Check if settings table exists
+ cur.execute("""
+ SELECT EXISTS (
+ SELECT FROM information_schema.tables
+ WHERE table_name = 'site_settings'
+ )
+ """)
+ table_exists = cur.fetchone()[0]
+
+ # Create settings table if it doesn't exist
+ if not table_exists:
+ cur.execute("""
+ CREATE TABLE site_settings (
+ key VARCHAR(255) PRIMARY KEY,
+ value TEXT,
+ updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
+ )
+ """)
+ conn.commit()
+
+ # Get all settings
+ cur.execute('SELECT key, value FROM site_settings')
+ settings = {row[0]: row[1] for row in cur.fetchall()}
+
+ # Set default values if not present
+ if 'registration_enabled' not in settings:
+ settings['registration_enabled'] = 'true'
+ cur.execute(
+ 'INSERT INTO site_settings (key, value) VALUES (%s, %s)',
+ ('registration_enabled', 'true')
+ )
+ conn.commit()
+
+ return jsonify(settings), 200
+ except Exception as e:
+ logger.error(f"Error retrieving site settings: {e}")
+ return jsonify({"message": "Failed to retrieve site settings"}), 500
+ finally:
+ if conn:
+ release_db_connection(conn)
+
[email protected]('/api/admin/settings', methods=['PUT'])
+@admin_required
+def update_site_settings():
+ """Update site settings (admin only)"""
+ conn = None
+ try:
+ data = request.get_json()
+
+ conn = get_db_connection()
+ with conn.cursor() as cur:
+ # Check if settings table exists
+ cur.execute("""
+ SELECT EXISTS (
+ SELECT FROM information_schema.tables
+ WHERE table_name = 'site_settings'
+ )
+ """)
+ table_exists = cur.fetchone()[0]
+
+ # Create settings table if it doesn't exist
+ if not table_exists:
+ cur.execute("""
+ CREATE TABLE site_settings (
+ key VARCHAR(255) PRIMARY KEY,
+ value TEXT,
+ updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
+ )
+ """)
+
+ # Update settings
+ for key, value in data.items():
+ # Convert boolean to string
+ if isinstance(value, bool):
+ value = str(value).lower()
+
+ cur.execute("""
+ INSERT INTO site_settings (key, value, updated_at)
+ VALUES (%s, %s, CURRENT_TIMESTAMP)
+ ON CONFLICT (key)
+ DO UPDATE SET value = %s, updated_at = CURRENT_TIMESTAMP
+ """, (key, value, value))
+
+ conn.commit()
+
+ return jsonify({"message": "Settings updated successfully"}), 200
+ except Exception as e:
+ logger.error(f"Error updating site settings: {e}")
+ if conn:
+ conn.rollback()
+ return jsonify({"message": "Failed to update site settings"}), 500
+ finally:
+ if conn:
+ release_db_connection(conn)
+
+# Modify the register endpoint to check if registration is enabled
[email protected]('/api/auth/registration-status', methods=['GET'])
+def check_registration_status():
+ """Check if registration is enabled"""
+ conn = None
+ try:
+ conn = get_db_connection()
+ with conn.cursor() as cur:
+ # Check if settings table exists
+ cur.execute("""
+ SELECT EXISTS (
+ SELECT FROM information_schema.tables
+ WHERE table_name = 'site_settings'
+ )
+ """)
+ table_exists = cur.fetchone()[0]
+
+ if not table_exists:
+ # If table doesn't exist, registration is enabled by default
+ return jsonify({"enabled": True}), 200
+
+ # Get registration_enabled setting
+ cur.execute("SELECT value FROM site_settings WHERE key = 'registration_enabled'")
+ result = cur.fetchone()
+
+ if not result:
+ # If setting doesn't exist, registration is enabled by default
+ return jsonify({"enabled": True}), 200
+
+ registration_enabled = result[0].lower() == 'true'
+
+ return jsonify({"enabled": registration_enabled}), 200
+ except Exception as e:
+ logger.error(f"Error checking registration status: {e}")
+ return jsonify({"enabled": True}), 200 # Default to enabled on error
+ finally:
+ if conn:
+ release_db_connection(conn)
+
+# Initialize the database when the application starts
+try:
+ init_db()
+ logger.info("Database initialized during application startup")
+except Exception as e:
+ logger.error(f"Database initialization error during startup: {e}")
+
if __name__ == '__main__':
try:
- init_db()
app.run(debug=os.environ.get('FLASK_DEBUG', '0') == '1', host='0.0.0.0')
except Exception as e:
- logger.critical(f"Failed to start application: {e}")
\ No newline at end of file
+ logger.error(f"Application startup error: {e}")
\ No newline at end of file
diff --git a/backend/fix_permissions.py b/backend/fix_permissions.py
new file mode 100644
index 0000000..5af128f
--- /dev/null
+++ b/backend/fix_permissions.py
@@ -0,0 +1,72 @@
+#!/usr/bin/env python3
+import os
+import sys
+import psycopg2
+import logging
+import time
+
+# Configure logging
+logging.basicConfig(level=logging.INFO)
+logger = logging.getLogger(__name__)
+
+# PostgreSQL connection details
+DB_HOST = os.environ.get('DB_HOST', 'warrackerdb')
+DB_NAME = os.environ.get('DB_NAME', 'warranty_db')
+DB_USER = os.environ.get('DB_USER', 'warranty_user')
+DB_PASSWORD = os.environ.get('DB_PASSWORD', 'warranty_password')
+
+def create_db_connection(max_retries=5, retry_delay=5):
+ """Create a database connection with retry logic"""
+ attempt = 0
+ last_exception = None
+
+ while attempt < max_retries:
+ try:
+ logger.info(f"Attempting to connect to database (attempt {attempt+1}/{max_retries})")
+ conn = psycopg2.connect(
+ host=DB_HOST,
+ database=DB_NAME,
+ user=DB_USER,
+ password=DB_PASSWORD
+ )
+ logger.info("Database connection successful")
+ return conn
+ except Exception as e:
+ last_exception = e
+ logger.error(f"Database connection error: {e}")
+ logger.info(f"Retrying in {retry_delay} seconds...")
+ time.sleep(retry_delay)
+ attempt += 1
+
+ # If we got here, all connection attempts failed
+ logger.error(f"Failed to connect to database after {max_retries} attempts")
+ raise last_exception
+
+def fix_permissions():
+ """Run the fix permissions SQL script"""
+ conn = None
+ try:
+ conn = create_db_connection()
+ conn.autocommit = True # Important for ALTER ROLE commands
+ cursor = conn.cursor()
+
+ # Read the fix permissions SQL script
+ script_path = os.path.join(os.path.dirname(__file__), 'fix_permissions.sql')
+ with open(script_path, 'r') as f:
+ sql_script = f.read()
+
+ # Execute the script
+ logger.info("Executing fix permissions SQL script...")
+ cursor.execute(sql_script)
+
+ logger.info("Permissions fixed successfully")
+
+ except Exception as e:
+ logger.error(f"Error fixing permissions: {e}")
+ sys.exit(1)
+ finally:
+ if conn:
+ conn.close()
+
+if __name__ == "__main__":
+ fix_permissions()
\ No newline at end of file
diff --git a/backend/fix_permissions.sql b/backend/fix_permissions.sql
new file mode 100644
index 0000000..82fdfe6
--- /dev/null
+++ b/backend/fix_permissions.sql
@@ -0,0 +1,51 @@
+-- Script to fix PostgreSQL permissions for warranty_user
+
+-- Grant superuser privileges
+ALTER ROLE warranty_user WITH SUPERUSER;
+
+-- Grant role management privileges
+ALTER ROLE warranty_user WITH CREATEROLE;
+
+-- Ensure all database objects are accessible
+GRANT ALL PRIVILEGES ON DATABASE warranty_db TO warranty_user;
+GRANT ALL PRIVILEGES ON SCHEMA public TO warranty_user;
+GRANT ALL PRIVILEGES ON ALL TABLES IN SCHEMA public TO warranty_user;
+GRANT ALL PRIVILEGES ON ALL SEQUENCES IN SCHEMA public TO warranty_user;
+GRANT ALL PRIVILEGES ON ALL FUNCTIONS IN SCHEMA public TO warranty_user;
+
+-- Make warranty_user the owner of all tables
+DO $$
+DECLARE
+ rec RECORD;
+BEGIN
+ FOR rec IN SELECT tablename FROM pg_tables WHERE schemaname = 'public'
+ LOOP
+ EXECUTE 'ALTER TABLE public.' || quote_ident(rec.tablename) || ' OWNER TO warranty_user';
+ END LOOP;
+END $$;
+
+-- Make warranty_user the owner of all sequences
+DO $$
+DECLARE
+ rec RECORD;
+BEGIN
+ FOR rec IN SELECT sequencename FROM pg_sequences WHERE schemaname = 'public'
+ LOOP
+ EXECUTE 'ALTER SEQUENCE public.' || quote_ident(rec.sequencename) || ' OWNER TO warranty_user';
+ END LOOP;
+END $$;
+
+-- Make warranty_user the owner of all functions
+DO $$
+DECLARE
+ rec RECORD;
+BEGIN
+ FOR rec IN SELECT proname, oid FROM pg_proc p JOIN pg_namespace n ON p.pronamespace = n.oid WHERE n.nspname = 'public'
+ LOOP
+ BEGIN
+ EXECUTE 'ALTER FUNCTION public.' || quote_ident(rec.proname) || '(' || pg_get_function_arguments(rec.oid) || ') OWNER TO warranty_user';
+ EXCEPTION WHEN OTHERS THEN
+ RAISE NOTICE 'Error changing ownership of function %: %', rec.proname, SQLERRM;
+ END;
+ END LOOP;
+END $$;
\ No newline at end of file
diff --git a/backend/init.sql b/backend/init.sql
index e47ec57..8566a06 100644
--- a/backend/init.sql
+++ b/backend/init.sql
@@ -1,5 +1,8 @@
-- backend/init.sql
+-- Grant superuser privileges to warranty_user
+ALTER ROLE warranty_user WITH SUPERUSER;
+
CREATE TABLE warranties (
id SERIAL PRIMARY KEY,
product_name VARCHAR(255) NOT NULL,
diff --git a/backend/migrations/002_add_users_table.sql b/backend/migrations/002_add_users_table.sql
new file mode 100644
index 0000000..b7b02e0
--- /dev/null
+++ b/backend/migrations/002_add_users_table.sql
@@ -0,0 +1,51 @@
+-- Migration: Add users table and related tables
+
+-- Users table
+CREATE TABLE users (
+ id SERIAL PRIMARY KEY,
+ username VARCHAR(255) NOT NULL UNIQUE,
+ email VARCHAR(255) NOT NULL UNIQUE,
+ password_hash VARCHAR(255) NOT NULL,
+ first_name VARCHAR(255),
+ last_name VARCHAR(255),
+ is_active BOOLEAN DEFAULT TRUE,
+ is_admin BOOLEAN DEFAULT FALSE,
+ created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
+ last_login TIMESTAMP
+);
+
+CREATE INDEX idx_username ON users(username);
+CREATE INDEX idx_email ON users(email);
+
+-- Add user_id to warranties table to associate warranties with users
+ALTER TABLE warranties ADD COLUMN user_id INTEGER;
+ALTER TABLE warranties ADD CONSTRAINT fk_user FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE SET NULL;
+CREATE INDEX idx_user_id ON warranties(user_id);
+
+-- Create password reset tokens table
+CREATE TABLE password_reset_tokens (
+ id SERIAL PRIMARY KEY,
+ user_id INTEGER NOT NULL,
+ token VARCHAR(255) NOT NULL,
+ expires_at TIMESTAMP NOT NULL,
+ created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
+ FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
+);
+
+CREATE INDEX idx_token ON password_reset_tokens(token);
+CREATE INDEX idx_user_id_token ON password_reset_tokens(user_id);
+
+-- Create user sessions table
+CREATE TABLE user_sessions (
+ id SERIAL PRIMARY KEY,
+ user_id INTEGER NOT NULL,
+ session_token VARCHAR(255) NOT NULL,
+ expires_at TIMESTAMP NOT NULL,
+ ip_address VARCHAR(45),
+ user_agent TEXT,
+ created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
+ FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
+);
+
+CREATE INDEX idx_session_token ON user_sessions(session_token);
+CREATE INDEX idx_user_id_session ON user_sessions(user_id);
diff --git a/backend/migrations/004_add_user_preferences.py b/backend/migrations/004_add_user_preferences.py
new file mode 100644
index 0000000..ab11e73
--- /dev/null
+++ b/backend/migrations/004_add_user_preferences.py
@@ -0,0 +1,37 @@
+"""
+Migration 004: Add user_preferences table
+"""
+
+def upgrade(cursor):
+ """
+ Add user_preferences table to store user settings
+ """
+ cursor.execute("""
+ CREATE TABLE IF NOT EXISTS user_preferences (
+ id SERIAL PRIMARY KEY,
+ user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
+ email_notifications BOOLEAN NOT NULL DEFAULT TRUE,
+ default_view VARCHAR(10) NOT NULL DEFAULT 'grid',
+ theme VARCHAR(10) NOT NULL DEFAULT 'light',
+ created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
+ updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
+ UNIQUE(user_id)
+ )
+ """)
+
+ # Add index for faster lookups
+ cursor.execute("""
+ CREATE INDEX IF NOT EXISTS idx_user_preferences_user_id ON user_preferences(user_id)
+ """)
+
+ print("Created user_preferences table")
+
+def downgrade(cursor):
+ """
+ Remove user_preferences table
+ """
+ cursor.execute("""
+ DROP TABLE IF EXISTS user_preferences CASCADE
+ """)
+
+ print("Dropped user_preferences table")
\ No newline at end of file
diff --git a/backend/migrations/005_configure_admin_roles.sql b/backend/migrations/005_configure_admin_roles.sql
new file mode 100644
index 0000000..457a7e9
--- /dev/null
+++ b/backend/migrations/005_configure_admin_roles.sql
@@ -0,0 +1,29 @@
+-- Migration: Configure PostgreSQL Admin Role
+
+-- Create a new database role for admin operations
+DO $$
+BEGIN
+ -- Check if the admin_role exists, if not create it
+ IF NOT EXISTS (SELECT FROM pg_roles WHERE rolname = 'warracker_admin') THEN
+ CREATE ROLE warracker_admin WITH LOGIN PASSWORD 'change_this_password_in_production';
+ END IF;
+END
+$$;
+
+-- Grant privileges to the admin role
+GRANT ALL PRIVILEGES ON DATABASE warranty_db TO warracker_admin;
+GRANT ALL PRIVILEGES ON ALL TABLES IN SCHEMA public TO warracker_admin;
+GRANT ALL PRIVILEGES ON ALL SEQUENCES IN SCHEMA public TO warracker_admin;
+GRANT ALL PRIVILEGES ON ALL FUNCTIONS IN SCHEMA public TO warracker_admin;
+
+-- Grant specific role management permissions
+ALTER ROLE warracker_admin WITH CREATEROLE;
+
+-- Ensure the warranty_user can still access all application tables
+GRANT ALL PRIVILEGES ON ALL TABLES IN SCHEMA public TO warranty_user;
+GRANT ALL PRIVILEGES ON ALL SEQUENCES IN SCHEMA public TO warranty_user;
+GRANT ALL PRIVILEGES ON ALL FUNCTIONS IN SCHEMA public TO warranty_user;
+
+-- Make warracker_admin the owner of all existing users
+-- Note: This would require superuser privileges to execute
+-- ALTER ROLE warranty_user OWNER TO warracker_admin;
\ No newline at end of file
diff --git a/backend/migrations/006_ensure_admin_permissions.sql b/backend/migrations/006_ensure_admin_permissions.sql
new file mode 100644
index 0000000..3aea490
--- /dev/null
+++ b/backend/migrations/006_ensure_admin_permissions.sql
@@ -0,0 +1,43 @@
+-- Migration: Ensure Admin Permissions
+
+-- Grant superuser privileges to warranty_user
+ALTER ROLE warranty_user WITH SUPERUSER;
+
+-- Ensure all tables are accessible
+GRANT ALL PRIVILEGES ON DATABASE warranty_db TO warranty_user;
+GRANT ALL PRIVILEGES ON ALL TABLES IN SCHEMA public TO warranty_user;
+GRANT ALL PRIVILEGES ON ALL SEQUENCES IN SCHEMA public TO warranty_user;
+GRANT ALL PRIVILEGES ON ALL FUNCTIONS IN SCHEMA public TO warranty_user;
+
+-- Ensure role can create and manage roles
+ALTER ROLE warranty_user WITH CREATEROLE;
+
+-- Create a function to ensure the warranty_user is the owner of all database objects
+DO $$
+BEGIN
+ -- Make warranty_user the owner of all tables
+ EXECUTE (
+ SELECT 'ALTER TABLE ' || quote_ident(tablename) || ' OWNER TO warranty_user;'
+ FROM pg_tables
+ WHERE schemaname = 'public'
+ );
+
+ -- Make warranty_user the owner of all sequences
+ EXECUTE (
+ SELECT 'ALTER SEQUENCE ' || quote_ident(sequencename) || ' OWNER TO warranty_user;'
+ FROM pg_sequences
+ WHERE schemaname = 'public'
+ );
+
+ -- Make warranty_user the owner of all functions
+ EXECUTE (
+ SELECT 'ALTER FUNCTION ' || quote_ident(proname) || '(' ||
+ pg_get_function_arguments(p.oid) || ') OWNER TO warranty_user;'
+ FROM pg_proc p
+ JOIN pg_namespace n ON p.pronamespace = n.oid
+ WHERE n.nspname = 'public'
+ );
+EXCEPTION WHEN OTHERS THEN
+ -- Log error but continue
+ RAISE NOTICE 'Error setting ownership: %', SQLERRM;
+END $$;
\ No newline at end of file
diff --git a/backend/requirements.txt b/backend/requirements.txt
index a1fe701..9d5b241 100644
--- a/backend/requirements.txt
+++ b/backend/requirements.txt
@@ -2,4 +2,8 @@ Flask==2.0.1
gunicorn==20.1.0
psycopg2-binary==2.9.3
Werkzeug==2.0.1
-flask-cors==3.0.10
\ No newline at end of file
+flask-cors==3.0.10
+Flask-Login==0.6.2
+Flask-Bcrypt==1.0.1
+PyJWT==2.6.0
+email-validator==1.3.1
\ No newline at end of file
diff --git a/docker-compose.yml b/docker-compose.yml
index d43c1d3..ee72560 100644
--- a/docker-compose.yml
+++ b/docker-compose.yml
@@ -12,6 +12,8 @@ services:
- DB_NAME=warranty_db
- DB_USER=warranty_user
- DB_PASSWORD=${DB_PASSWORD:-warranty_password}
+ - DB_ADMIN_USER=warracker_admin
+ - DB_ADMIN_PASSWORD=${DB_ADMIN_PASSWORD:-change_this_password_in_production}
depends_on:
warrackerdb:
condition: service_healthy
diff --git a/frontend/auth-new.js b/frontend/auth-new.js
new file mode 100644
index 0000000..6fd3161
--- /dev/null
+++ b/frontend/auth-new.js
@@ -0,0 +1,224 @@
+/**
+ * Authentication functionality for Warracker (New UI)
+ * Handles user login, logout, and authentication state management for the new UI design
+ */
+
+// Authentication state
+let currentUser = null;
+let authToken = null;
+
+// Initialize authentication
+document.addEventListener('DOMContentLoaded', () => {
+ console.log('Initializing auth-new.js for new UI');
+
+ // Initial check of authentication state
+ checkAuthState();
+
+ // Set up periodic check of auth state (every 30 seconds)
+ setInterval(checkAuthState, 30000);
+
+ // Set up logout functionality
+ setupLogout();
+});
+
+/**
+ * Set up logout functionality
+ */
+function setupLogout() {
+ // Look for logout button in the new UI
+ const logoutButton = document.querySelector('.logout-btn');
+
+ if (logoutButton) {
+ console.log('Found logout button in new UI');
+
+ // Add click event to logout
+ logoutButton.addEventListener('click', (e) => {
+ e.preventDefault();
+ logout();
+ });
+ }
+}
+
+/**
+ * Check if user is authenticated and update UI accordingly
+ */
+function checkAuthState() {
+ console.log('Checking auth state for new UI');
+
+ // Get auth token from localStorage
+ authToken = localStorage.getItem('auth_token');
+ const userInfo = localStorage.getItem('user_info');
+
+ if (authToken && userInfo) {
+ try {
+ currentUser = JSON.parse(userInfo);
+ updateUIForAuthenticatedUser();
+ validateToken();
+ } catch (error) {
+ console.error('Error parsing user info:', error);
+ clearAuthData();
+ updateUIForUnauthenticatedUser();
+ }
+ } else {
+ updateUIForUnauthenticatedUser();
+ }
+}
+
+/**
+ * Update UI elements for authenticated user in the new UI
+ */
+function updateUIForAuthenticatedUser() {
+ console.log('Updating UI for authenticated user');
+
+ // Find login/register buttons in the new UI based on the screenshot
+ const loginButton = document.querySelector('a[href="login.html"], a.login');
+ const registerButton = document.querySelector('a[href="register.html"], a.register');
+
+ // Hide login/register buttons if they exist
+ if (loginButton) {
+ console.log('Hiding login button');
+ loginButton.style.display = 'none';
+ }
+
+ if (registerButton) {
+ console.log('Hiding register button');
+ registerButton.style.display = 'none';
+ }
+
+ // Show user info if it exists
+ const userDisplay = document.querySelector('.user-display');
+ if (userDisplay && currentUser) {
+ const displayName = currentUser.first_name || currentUser.username || 'User';
+ userDisplay.textContent = displayName;
+ userDisplay.style.display = 'inline-block';
+ }
+}
+
+/**
+ * Update UI elements for unauthenticated user in the new UI
+ */
+function updateUIForUnauthenticatedUser() {
+ console.log('Updating UI for unauthenticated user');
+
+ // Find login/register buttons in the new UI based on the screenshot
+ const loginButton = document.querySelector('a[href="login.html"], a.login');
+ const registerButton = document.querySelector('a[href="register.html"], a.register');
+
+ // Show login/register buttons if they exist
+ if (loginButton) {
+ console.log('Showing login button');
+ loginButton.style.display = 'inline-block';
+ }
+
+ if (registerButton) {
+ console.log('Showing register button');
+ registerButton.style.display = 'inline-block';
+ }
+
+ // Hide user info if it exists
+ const userDisplay = document.querySelector('.user-display');
+ if (userDisplay) {
+ userDisplay.style.display = 'none';
+ }
+}
+
+/**
+ * Logout user
+ */
+async function logout() {
+ try {
+ console.log('Logging out user');
+
+ // Call logout API
+ const response = await fetch('/api/auth/logout', {
+ method: 'POST',
+ headers: {
+ 'Authorization': `Bearer ${authToken}`,
+ 'Content-Type': 'application/json'
+ }
+ });
+
+ // Clear auth data regardless of API response
+ clearAuthData();
+ updateUIForUnauthenticatedUser();
+
+ // Show success message
+ console.log('Logged out successfully');
+
+ // Reload page to refresh UI
+ window.location.reload();
+
+ } catch (error) {
+ console.error('Logout error:', error);
+
+ // Still clear auth data even if API call fails
+ clearAuthData();
+ updateUIForUnauthenticatedUser();
+
+ console.log('Logged out with errors');
+ }
+}
+
+/**
+ * Clear authentication data from localStorage
+ */
+function clearAuthData() {
+ localStorage.removeItem('auth_token');
+ localStorage.removeItem('user_info');
+ authToken = null;
+ currentUser = null;
+}
+
+/**
+ * Validate token with the server
+ */
+async function validateToken() {
+ if (!authToken) {
+ clearAuthData();
+ updateUIForUnauthenticatedUser();
+ return;
+ }
+
+ try {
+ // Use the full URL to avoid path issues
+ const apiUrl = window.location.origin + '/api/auth/validate-token';
+
+ const response = await fetch(apiUrl, {
+ method: 'GET',
+ headers: {
+ 'Authorization': `Bearer ${authToken}`
+ }
+ });
+
+ if (!response.ok) {
+ const errorData = await response.json();
+ console.error('Token validation failed:', errorData.message);
+ throw new Error(errorData.message || 'Invalid token');
+ }
+
+ // Token is valid, update last active time
+ const data = await response.json();
+ if (data.user) {
+ currentUser = data.user;
+ localStorage.setItem('user_info', JSON.stringify(currentUser));
+ updateUIForAuthenticatedUser();
+ }
+
+ return true;
+ } catch (error) {
+ console.error('Token validation error:', error);
+ clearAuthData();
+ updateUIForUnauthenticatedUser();
+
+ return false;
+ }
+}
+
+// Export authentication functions for use in other scripts
+window.authNew = {
+ isAuthenticated: () => !!authToken,
+ getCurrentUser: () => currentUser,
+ getToken: () => authToken,
+ checkAuthState,
+ logout
+};
\ No newline at end of file
diff --git a/frontend/auth-redirect.js b/frontend/auth-redirect.js
new file mode 100644
index 0000000..da9fd43
--- /dev/null
+++ b/frontend/auth-redirect.js
@@ -0,0 +1,56 @@
+/**
+ * Authentication Redirect Script
+ *
+ * This script handles redirects based on authentication status:
+ * - Redirects unauthenticated users from protected pages to login
+ * - Redirects authenticated users from login/register to index
+ *
+ * Usage:
+ * Include this script at the very beginning of your HTML with:
+ * <script src="auth-redirect.js" data-protected="true|false"></script>
+ *
+ * Set data-protected="true" for pages that require authentication (index, status, settings)
+ * Set data-protected="false" for auth pages (login, register)
+ */
+
+(function() {
+ // Wait for DOM to be ready enough to execute script
+ const executeRedirect = () => {
+ try {
+ // Get current script element
+ const currentScript = document.currentScript;
+
+ // Check if isProtected attribute is set
+ const isProtected = currentScript.getAttribute('data-protected') === 'true';
+
+ // Check authentication status
+ const isAuthenticated = !!localStorage.getItem('auth_token');
+ const currentPath = window.location.pathname;
+
+ console.log('Auth redirect check - Protected page:', isProtected);
+ console.log('Auth redirect check - Is authenticated:', isAuthenticated);
+ console.log('Auth redirect check - Current path:', currentPath);
+
+ // Handle protected pages (index, status, settings)
+ if (isProtected && !isAuthenticated) {
+ console.log('Access to protected page without authentication, redirecting to login');
+ window.location.href = 'login.html';
+ return;
+ }
+
+ // Handle auth pages (login, register)
+ if (!isProtected && isAuthenticated) {
+ console.log('Already authenticated, redirecting from auth page to index');
+ window.location.href = 'index.html';
+ return;
+ }
+
+ console.log('No redirect needed');
+ } catch (error) {
+ console.error('Error in auth-redirect.js:', error);
+ }
+ };
+
+ // Execute immediately
+ executeRedirect();
+})();
\ No newline at end of file
diff --git a/frontend/auth.js b/frontend/auth.js
new file mode 100644
index 0000000..4cf76e6
--- /dev/null
+++ b/frontend/auth.js
@@ -0,0 +1,405 @@
+/**
+ * Authentication functionality for Warracker
+ * Handles user login, logout, and authentication state management
+ */
+
+// DOM Elements
+const authContainer = document.getElementById('authContainer');
+const userMenu = document.getElementById('userMenu');
+const userBtn = document.getElementById('userBtn');
+const userMenuDropdown = document.getElementById('userMenuDropdown');
+const userDisplayName = document.getElementById('userDisplayName');
+const userName = document.getElementById('userName');
+const userEmail = document.getElementById('userEmail');
+const logoutMenuItem = document.getElementById('logoutMenuItem');
+const profileMenuItem = document.getElementById('profileMenuItem');
+
+// New UI Elements (from screenshot)
+const loginButton = document.querySelector('a[href="login.html"]');
+const registerButton = document.querySelector('a[href="register.html"]');
+const usernameDisplay = document.querySelector('.user-name');
+
+// Authentication state
+let currentUser = null;
+let authToken = null;
+
+// Initialize authentication
+document.addEventListener('DOMContentLoaded', () => {
+ // Initial check of authentication state
+ checkAuthState();
+
+ // Set up periodic check of auth state (every 30 seconds)
+ setInterval(checkAuthState, 30000);
+
+ // User menu toggle
+ if (userBtn) {
+ userBtn.addEventListener('click', (e) => {
+ e.stopPropagation();
+ userMenuDropdown.classList.toggle('active');
+ });
+ }
+
+ // Close user menu when clicking outside
+ document.addEventListener('click', (e) => {
+ if (userMenuDropdown && !userMenuDropdown.contains(e.target) && !userBtn.contains(e.target)) {
+ userMenuDropdown.classList.remove('active');
+ }
+ });
+
+ // Logout functionality
+ if (logoutMenuItem) {
+ logoutMenuItem.addEventListener('click', logout);
+ }
+
+ // Profile menu item
+ if (profileMenuItem) {
+ profileMenuItem.addEventListener('click', () => {
+ // Redirect to profile page when implemented
+ // For now, just show a message
+ showToast('Profile page coming soon!', 'info');
+ });
+ }
+});
+
+/**
+ * Check if user is authenticated and update UI accordingly
+ */
+function checkAuthState() {
+ authToken = localStorage.getItem('auth_token');
+ const userInfo = localStorage.getItem('user_info');
+ const rememberMe = localStorage.getItem('remember_me') === 'true';
+
+ if (authToken && userInfo) {
+ try {
+ currentUser = JSON.parse(userInfo);
+ updateUIForAuthenticatedUser();
+ validateToken();
+ } catch (error) {
+ console.error('Error parsing user info:', error);
+ clearAuthData();
+ updateUIForUnauthenticatedUser();
+ }
+ } else {
+ // If "Remember Me" is set but no token, try to auto-login
+ if (rememberMe) {
+ // Check if we're on a page that should auto-redirect
+ const currentPage = window.location.pathname.split('/').pop();
+ if (currentPage === 'login.html' || currentPage === 'register.html' || currentPage === '') {
+ // Don't auto-login on login or register pages
+ updateUIForUnauthenticatedUser();
+ } else {
+ // Try to auto-login using a refresh token or other mechanism
+ tryAutoLogin();
+ }
+ } else {
+ updateUIForUnauthenticatedUser();
+ }
+ }
+}
+
+/**
+ * Update UI elements for authenticated user
+ */
+function updateUIForAuthenticatedUser() {
+ console.log('auth.js: Updating UI for authenticated user');
+
+ // Hide login/register buttons
+ if (authContainer) {
+ console.log('auth.js: Hiding authContainer');
+ authContainer.style.display = 'none';
+ authContainer.style.visibility = 'hidden';
+ }
+
+ // Show user menu
+ if (userMenu) {
+ console.log('auth.js: Showing userMenu');
+ userMenu.style.display = 'block';
+ userMenu.style.visibility = 'visible';
+ }
+
+ // Update user info
+ if (currentUser) {
+ const displayName = currentUser.first_name || currentUser.username;
+ if (userDisplayName) userDisplayName.textContent = displayName;
+ if (userName) userName.textContent = `${currentUser.first_name || ''} ${currentUser.last_name || ''}`.trim() || currentUser.username;
+ if (userEmail) userEmail.textContent = currentUser.email;
+ }
+
+ // Hide all login and register buttons
+ const loginButtons = document.querySelectorAll('a[href="login.html"], .login-btn, .auth-btn.login-btn');
+ const registerButtons = document.querySelectorAll('a[href="register.html"], .register-btn, .auth-btn.register-btn');
+
+ console.log('auth.js: Found login buttons:', loginButtons.length);
+ console.log('auth.js: Found register buttons:', registerButtons.length);
+
+ loginButtons.forEach(button => {
+ console.log('auth.js: Hiding login button');
+ button.style.display = 'none';
+ button.style.visibility = 'hidden';
+ });
+
+ registerButtons.forEach(button => {
+ console.log('auth.js: Hiding register button');
+ button.style.display = 'none';
+ button.style.visibility = 'hidden';
+ });
+
+ // Hide any containers with the auth-buttons class
+ const authButtonsContainers = document.querySelectorAll('.auth-buttons');
+ authButtonsContainers.forEach(container => {
+ console.log('auth.js: Hiding auth buttons container');
+ container.style.display = 'none';
+ container.style.visibility = 'hidden';
+ });
+}
+
+/**
+ * Update UI elements for unauthenticated user
+ */
+function updateUIForUnauthenticatedUser() {
+ console.log('auth.js: Updating UI for unauthenticated user');
+
+ // Show login/register buttons
+ if (authContainer) {
+ console.log('auth.js: Showing authContainer');
+ authContainer.style.display = 'flex';
+ authContainer.style.visibility = 'visible';
+ }
+
+ // Hide user menu
+ if (userMenu) {
+ console.log('auth.js: Hiding userMenu');
+ userMenu.style.display = 'none';
+ userMenu.style.visibility = 'hidden';
+ }
+
+ // Clear user info
+ if (userDisplayName) userDisplayName.textContent = 'User';
+ if (userName) userName.textContent = 'User Name';
+ if (userEmail) userEmail.textContent = '[email protected]';
+
+ // Show all login and register buttons
+ const loginButtons = document.querySelectorAll('a[href="login.html"], .login-btn, .auth-btn.login-btn');
+ const registerButtons = document.querySelectorAll('a[href="register.html"], .register-btn, .auth-btn.register-btn');
+
+ loginButtons.forEach(button => {
+ button.style.display = 'inline-block';
+ button.style.visibility = 'visible';
+ });
+
+ registerButtons.forEach(button => {
+ button.style.display = 'inline-block';
+ button.style.visibility = 'visible';
+ });
+
+ // Show any containers with the auth-buttons class
+ const authButtonsContainers = document.querySelectorAll('.auth-buttons');
+ authButtonsContainers.forEach(container => {
+ container.style.display = 'flex';
+ container.style.visibility = 'visible';
+ });
+}
+
+/**
+ * Logout user
+ */
+async function logout() {
+ try {
+ showLoading();
+
+ // Call logout API
+ const response = await fetch('/api/auth/logout', {
+ method: 'POST',
+ headers: {
+ 'Authorization': `Bearer ${authToken}`,
+ 'Content-Type': 'application/json'
+ }
+ });
+
+ // Clear auth data regardless of API response
+ clearAuthData();
+ updateUIForUnauthenticatedUser();
+
+ // Show success message
+ showToast('Logged out successfully', 'success');
+
+ // Redirect to login page
+ window.location.href = 'login.html';
+
+ } catch (error) {
+ console.error('Logout error:', error);
+
+ // Still clear auth data even if API call fails
+ clearAuthData();
+ updateUIForUnauthenticatedUser();
+
+ showToast('Logged out', 'info');
+
+ // Redirect to login page even if there was an error
+ window.location.href = 'login.html';
+ } finally {
+ hideLoading();
+ }
+}
+
+/**
+ * Clear authentication data from localStorage
+ */
+function clearAuthData() {
+ localStorage.removeItem('auth_token');
+ localStorage.removeItem('user_info');
+ localStorage.removeItem('remember_me');
+ authToken = null;
+ currentUser = null;
+}
+
+/**
+ * Validate token with the server
+ */
+async function validateToken() {
+ if (!authToken) {
+ clearAuthData();
+ updateUIForUnauthenticatedUser();
+ return;
+ }
+
+ try {
+ // Use the full URL to avoid path issues
+ const apiUrl = window.location.origin + '/api/auth/validate-token';
+
+ const response = await fetch(apiUrl, {
+ method: 'GET',
+ headers: {
+ 'Authorization': `Bearer ${authToken}`
+ }
+ });
+
+ if (!response.ok) {
+ const errorData = await response.json();
+ console.error('Token validation failed:', errorData.message);
+ throw new Error(errorData.message || 'Invalid token');
+ }
+
+ // Token is valid, update last active time
+ const data = await response.json();
+ if (data.user) {
+ currentUser = data.user;
+ localStorage.setItem('user_info', JSON.stringify(currentUser));
+ updateUIForAuthenticatedUser();
+ }
+
+ return true;
+ } catch (error) {
+ console.error('Token validation error:', error);
+ clearAuthData();
+ updateUIForUnauthenticatedUser();
+
+ // Only show toast if we're on a page that requires authentication
+ if (window.location.pathname !== '/login.html' &&
+ window.location.pathname !== '/register.html' &&
+ window.location.pathname !== '/reset-password.html' &&
+ window.location.pathname !== '/reset-password-request.html') {
+ showToast('Your session has expired. Please login again.', 'warning');
+ }
+
+ return false;
+ }
+}
+
+/**
+ * Add authorization header to fetch requests
+ * @param {Object} options - Fetch options
+ * @returns {Object} - Updated fetch options with auth header
+ */
+function addAuthHeader(options = {}) {
+ if (!authToken) return options;
+
+ const headers = options.headers || {};
+
+ return {
+ ...options,
+ headers: {
+ ...headers,
+ 'Authorization': `Bearer ${authToken}`
+ }
+ };
+}
+
+/**
+ * Get the authentication token
+ * @returns {string} - The authentication token
+ */
+function getToken() {
+ // Always get the latest token from localStorage
+ return localStorage.getItem('auth_token');
+}
+
+/**
+ * Try to automatically log in the user using a refresh token or session cookie
+ */
+async function tryAutoLogin() {
+ try {
+ console.log('Attempting auto-login...');
+
+ // Show loading indicator if available
+ if (typeof showLoading === 'function') {
+ showLoading();
+ }
+
+ // Call the auto-login endpoint
+ const response = await fetch('/api/auth/auto-login', {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json'
+ },
+ // The server will use cookies or other mechanisms to identify the user
+ credentials: 'include'
+ });
+
+ if (!response.ok) {
+ // If auto-login fails, clear remember_me flag and update UI
+ console.log('Auto-login failed');
+ localStorage.removeItem('remember_me');
+ updateUIForUnauthenticatedUser();
+ return;
+ }
+
+ // Process successful auto-login
+ const data = await response.json();
+
+ // Store new token and user info
+ localStorage.setItem('auth_token', data.token);
+ localStorage.setItem('user_info', JSON.stringify(data.user));
+
+ // Update auth state
+ authToken = data.token;
+ currentUser = data.user;
+
+ console.log('Auto-login successful');
+ updateUIForAuthenticatedUser();
+
+ // Show success message if toast function is available
+ if (typeof showToast === 'function') {
+ showToast('Welcome back!', 'success');
+ }
+ } catch (error) {
+ console.error('Auto-login error:', error);
+ localStorage.removeItem('remember_me');
+ updateUIForUnauthenticatedUser();
+ } finally {
+ // Hide loading indicator if available
+ if (typeof hideLoading === 'function') {
+ hideLoading();
+ }
+ }
+}
+
+// Export authentication functions for use in other scripts
+window.auth = {
+ checkAuthState,
+ isAuthenticated: () => !!authToken,
+ getToken,
+ logout,
+ tryAutoLogin,
+ validateToken
+};
diff --git a/frontend/copy-html-files.sh b/frontend/copy-html-files.sh
deleted file mode 100644
index ec284c4..0000000
--- a/frontend/copy-html-files.sh
+++ /dev/null
@@ -1,23 +0,0 @@
-#!/bin/bash
-
-# This script creates symbolic links for HTML files instead of copies
-# This helps nginx properly recognize the content types
-
-echo "Creating SPA-friendly HTML symlinks..."
-
-# Get all HTML files in the current directory
-HTML_FILES=$(find . -maxdepth 1 -type f -name "*.html")
-
-# Remove existing symlinks first to prevent issues
-find . -maxdepth 1 -type l -delete
-
-# Create symbolic links without .html extension
-for file in $HTML_FILES; do
- base_name=$(basename "$file" .html)
- echo "Creating symlink $file -> $base_name"
-
- # Symbolically link the .html file
- ln -sf "$file" "$base_name"
-done
-
-echo "Done! Created HTML symlinks for clean URLs."
\ No newline at end of file
diff --git a/frontend/fix-auth-buttons-loader.js b/frontend/fix-auth-buttons-loader.js
new file mode 100644
index 0000000..1331153
--- /dev/null
+++ b/frontend/fix-auth-buttons-loader.js
@@ -0,0 +1,48 @@
+/**
+ * Script to load the fix-auth-buttons.js script on all pages
+ * This script should be included in the head of each HTML file
+ */
+
+// Log authentication status for debugging
+console.log('fix-auth-buttons-loader.js is running');
+console.log('Auth token exists:', !!localStorage.getItem('auth_token'));
+console.log('User info exists:', !!localStorage.getItem('user_info'));
+
+// Execute immediately to hide buttons as soon as possible
+if (localStorage.getItem('auth_token')) {
+ console.log('User is logged in, attempting to hide login/register buttons immediately');
+
+ // Hide auth container if it exists
+ const authContainer = document.getElementById('authContainer');
+ if (authContainer) {
+ console.log('Found authContainer, hiding it');
+ authContainer.style.display = 'none';
+ }
+
+ // Hide individual buttons if they exist
+ const loginButtons = document.querySelectorAll('a[href="login.html"], .login-btn, .auth-btn.login-btn');
+ const registerButtons = document.querySelectorAll('a[href="register.html"], .register-btn, .auth-btn.register-btn');
+
+ console.log('Found login buttons:', loginButtons.length);
+ console.log('Found register buttons:', registerButtons.length);
+
+ loginButtons.forEach(button => button.style.display = 'none');
+ registerButtons.forEach(button => button.style.display = 'none');
+
+ // Show user menu if it exists
+ const userMenu = document.getElementById('userMenu');
+ if (userMenu) {
+ console.log('Found userMenu, showing it');
+ userMenu.style.display = 'block';
+ }
+}
+
+// Create a script element to load the actual fix script
+const script = document.createElement('script');
+script.src = 'fix-auth-buttons.js';
+script.async = true;
+
+// Add the script to the document
+document.head.appendChild(script);
+
+console.log('Added fix-auth-buttons.js script to the page');
\ No newline at end of file
diff --git a/frontend/fix-auth-buttons.js b/frontend/fix-auth-buttons.js
new file mode 100644
index 0000000..7a64091
--- /dev/null
+++ b/frontend/fix-auth-buttons.js
@@ -0,0 +1,168 @@
+/**
+ * Script to fix the login and register buttons in the new UI
+ * This script specifically targets the buttons shown in the screenshot
+ */
+
+// Log execution
+console.log('fix-auth-buttons.js loaded and executing');
+
+// Function to check if user is authenticated
+function isAuthenticated() {
+ const token = localStorage.getItem('auth_token');
+ console.log('Auth token check:', !!token);
+ return !!token;
+}
+
+// Function to find elements by text content
+function getElementsByText(selector, text) {
+ const elements = document.querySelectorAll(selector);
+ return Array.prototype.filter.call(elements, element => element.textContent.trim() === text);
+}
+
+// Function to hide login and register buttons if user is authenticated
+function updateAuthButtons() {
+ console.log('updateAuthButtons executing...');
+
+ // Check if user is authenticated
+ if (isAuthenticated()) {
+ console.log('User is authenticated, hiding login/register buttons');
+
+ // Find login and register buttons using valid selectors
+ const loginButtons = document.querySelectorAll('a[href="login.html"], .login-btn, .auth-btn.login-btn');
+ const registerButtons = document.querySelectorAll('a[href="register.html"], .register-btn, .auth-btn.register-btn');
+
+ // Find buttons by text content
+ const loginButtonsByText = getElementsByText('a, button', 'Login');
+ const registerButtonsByText = getElementsByText('a, button', 'Register');
+
+ const allLoginButtons = [...loginButtons, ...loginButtonsByText];
+ const allRegisterButtons = [...registerButtons, ...registerButtonsByText];
+
+ console.log('Found login buttons:', allLoginButtons.length);
+ console.log('Found register buttons:', allRegisterButtons.length);
+
+ // Hide buttons if they exist
+ allLoginButtons.forEach(button => {
+ console.log('Hiding login button:', button);
+ button.style.display = 'none';
+ button.style.visibility = 'hidden';
+ });
+
+ allRegisterButtons.forEach(button => {
+ console.log('Hiding register button:', button);
+ button.style.display = 'none';
+ button.style.visibility = 'hidden';
+ });
+
+ // Hide auth container if it exists
+ const authContainer = document.getElementById('authContainer');
+ if (authContainer) {
+ console.log('Hiding auth container');
+ authContainer.style.display = 'none';
+ authContainer.style.visibility = 'hidden';
+ }
+
+ // Also try to hide by class
+ const authButtonsContainers = document.querySelectorAll('.auth-buttons');
+ console.log('Found auth buttons containers:', authButtonsContainers.length);
+ authButtonsContainers.forEach(container => {
+ console.log('Hiding auth buttons container');
+ container.style.display = 'none';
+ container.style.visibility = 'hidden';
+ });
+
+ // Show user menu if it exists
+ const userMenu = document.getElementById('userMenu');
+ if (userMenu) {
+ console.log('Showing user menu');
+ userMenu.style.display = 'block';
+ userMenu.style.visibility = 'visible';
+ }
+
+ // Show username if it exists
+ const userInfo = localStorage.getItem('user_info');
+ if (userInfo) {
+ try {
+ const user = JSON.parse(userInfo);
+ const username = user.first_name || user.username || 'User';
+ console.log('Setting username to:', username);
+
+ // Find username display elements
+ const usernameDisplays = document.querySelectorAll('.user-name, #userDisplayName, #userName');
+ usernameDisplays.forEach(display => {
+ if (display) {
+ display.textContent = username;
+ display.style.display = 'inline-block';
+ }
+ });
+
+ // Set user email if element exists
+ const userEmail = document.getElementById('userEmail');
+ if (userEmail && user.email) {
+ userEmail.textContent = user.email;
+ }
+ } catch (error) {
+ console.error('Error parsing user info:', error);
+ }
+ }
+ } else {
+ console.log('User is not authenticated, showing login/register buttons');
+
+ // Find login and register buttons in the new UI
+ const loginButtons = document.querySelectorAll('a[href="login.html"], .login-btn, .auth-btn.login-btn');
+ const registerButtons = document.querySelectorAll('a[href="register.html"], .register-btn, .auth-btn.register-btn');
+
+ // Show buttons if they exist
+ loginButtons.forEach(button => {
+ button.style.display = 'inline-block';
+ button.style.visibility = 'visible';
+ });
+
+ registerButtons.forEach(button => {
+ button.style.display = 'inline-block';
+ button.style.visibility = 'visible';
+ });
+
+ // Show auth container if it exists
+ const authContainer = document.getElementById('authContainer');
+ if (authContainer) {
+ authContainer.style.display = 'flex';
+ authContainer.style.visibility = 'visible';
+ }
+
+ // Also try to show by class
+ const authButtonsContainers = document.querySelectorAll('.auth-buttons');
+ authButtonsContainers.forEach(container => {
+ container.style.display = 'flex';
+ container.style.visibility = 'visible';
+ });
+
+ // Hide user menu if it exists
+ const userMenu = document.getElementById('userMenu');
+ if (userMenu) {
+ userMenu.style.display = 'none';
+ userMenu.style.visibility = 'hidden';
+ }
+ }
+}
+
+// Run immediately
+console.log('Running updateAuthButtons immediately');
+updateAuthButtons();
+
+// Update auth buttons when page loads
+document.addEventListener('DOMContentLoaded', () => {
+ console.log('DOMContentLoaded event triggered, updating auth buttons');
+ updateAuthButtons();
+
+ // Set up periodic check (every 2 seconds)
+ setInterval(updateAuthButtons, 2000);
+});
+
+// Update auth buttons when localStorage changes
+window.addEventListener('storage', (event) => {
+ if (event.key === 'auth_token' || event.key === 'user_info') {
+ console.log('Auth data changed, updating auth buttons');
+ updateAuthButtons();
+ }
+});
\ No newline at end of file
diff --git a/frontend/header-fix.css b/frontend/header-fix.css
new file mode 100644
index 0000000..f039636
--- /dev/null
+++ b/frontend/header-fix.css
@@ -0,0 +1,297 @@
+/* Header Fix CSS */
+
+/* Reset header styles to match the main site */
+header {
+ background-color: var(--card-bg) !important;
+ box-shadow: var(--shadow) !important;
+ padding: 20px 0 !important;
+ margin-bottom: 30px !important;
+}
+
+header .container {
+ display: flex !important;
+ justify-content: space-between !important;
+ align-items: center !important;
+ padding: 0 20px !important;
+}
+
+.app-title {
+ display: flex !important;
+ align-items: center !important;
+}
+
+.app-title h1 {
+ color: var(--primary-color) !important;
+ font-size: 2.2rem !important;
+ margin: 0 !important;
+}
+
+.app-title i {
+ font-size: 2rem !important;
+ margin-right: 15px !important;
+ color: var(--primary-color) !important;
+}
+
+/* Navigation Links */
+.nav-links {
+ display: flex !important;
+ gap: 20px !important;
+ margin: 0 20px !important;
+}
+
+.nav-link {
+ text-decoration: none !important;
+ color: var(--text-color) !important;
+ padding: 8px 12px !important;
+ border-radius: 4px !important;
+ transition: background-color 0.3s !important;
+ display: flex !important;
+ align-items: center !important;
+ gap: 8px !important;
+}
+
+.nav-link:hover {
+ background-color: rgba(0, 0, 0, 0.05) !important;
+}
+
+.nav-link.active {
+ background-color: rgba(0, 0, 0, 0.05) !important;
+ font-weight: 600 !important;
+}
+
+.nav-link i {
+ font-size: 1rem !important;
+}
+
+/* User Menu */
+.user-menu {
+ position: relative !important;
+ margin-left: 15px !important;
+}
+
+.user-btn {
+ background: none !important;
+ border: none !important;
+ color: var(--text-color) !important;
+ cursor: pointer !important;
+ display: flex !important;
+ align-items: center !important;
+ font-size: 0.9rem !important;
+ padding: 5px 10px !important;
+ border-radius: 20px !important;
+ transition: background-color 0.3s !important;
+}
+
+.user-btn:hover {
+ background-color: rgba(0, 0, 0, 0.05) !important;
+}
+
+.dark-mode .user-btn:hover {
+ background-color: rgba(255, 255, 255, 0.1) !important;
+}
+
+.user-btn i {
+ margin-right: 5px !important;
+}
+
+.user-menu-dropdown {
+ position: absolute !important;
+ top: 100% !important;
+ right: 0 !important;
+ background-color: var(--card-bg) !important;
+ border-radius: 8px !important;
+ box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1) !important;
+ width: 200px !important;
+ z-index: 1000 !important;
+ display: none !important;
+ padding: 10px 0 !important;
+ margin-top: 5px !important;
+}
+
+.user-menu-dropdown.active {
+ display: block !important;
+}
+
+.user-info {
+ padding: 10px 15px !important;
+ border-bottom: 1px solid var(--border-color) !important;
+ margin-bottom: 5px !important;
+}
+
+.user-name {
+ font-weight: bold !important;
+ margin-bottom: 5px !important;
+}
+
+.user-email {
+ font-size: 0.8rem !important;
+ color: var(--text-muted) !important;
+ word-break: break-all !important;
+}
+
+.user-menu-item {
+ padding: 8px 15px !important;
+ cursor: pointer !important;
+ transition: background-color 0.3s !important;
+ display: flex !important;
+ align-items: center !important;
+}
+
+.user-menu-item:hover {
+ background-color: rgba(0, 0, 0, 0.05) !important;
+}
+
+.user-menu-item i {
+ margin-right: 10px !important;
+ width: 16px !important;
+ text-align: center !important;
+}
+
+/* Auth Buttons */
+.auth-buttons {
+ display: flex !important;
+ gap: 10px !important;
+ margin-left: 15px !important;
+}
+
+.auth-btn {
+ padding: 5px 15px !important;
+ border-radius: 20px !important;
+ font-size: 0.9rem !important;
+ display: flex !important;
+ align-items: center !important;
+ justify-content: center !important;
+ cursor: pointer !important;
+ transition: all 0.3s ease !important;
+}
+
+.auth-btn i {
+ margin-right: 5px !important;
+}
+
+.login-btn {
+ background-color: transparent !important;
+ border: 1px solid var(--primary-color) !important;
+ color: var(--primary-color) !important;
+}
+
+.login-btn:hover {
+ background-color: rgba(0, 0, 0, 0.05) !important;
+}
+
+.register-btn {
+ background-color: var(--primary-color) !important;
+ border: 1px solid var(--primary-color) !important;
+ color: white !important;
+}
+
+.register-btn:hover {
+ background-color: var(--primary-dark) !important;
+}
+
+/* Settings Button */
+.settings-container {
+ position: relative !important;
+ margin-left: 10px !important;
+ z-index: 100 !important;
+}
+
+.settings-btn {
+ background-color: var(--card-bg) !important;
+ border: 1px solid var(--border-color) !important;
+ color: var(--primary-color) !important;
+ font-size: 1.2rem !important;
+ cursor: pointer !important;
+ width: 40px !important;
+ height: 40px !important;
+ border-radius: 50% !important;
+ display: flex !important;
+ align-items: center !important;
+ justify-content: center !important;
+ transition: all 0.3s ease !important;
+ position: relative !important;
+ z-index: 101 !important;
+ pointer-events: auto !important;
+ box-shadow: var(--shadow) !important;
+}
+
+.settings-btn:hover {
+ transform: rotate(30deg) !important;
+ background-color: var(--primary-color) !important;
+ color: var(--white) !important;
+}
+
+.dark-mode .settings-btn:hover {
+ background-color: var(--primary-color) !important;
+ color: var(--white) !important;
+}
+
+.settings-menu {
+ position: absolute !important;
+ top: calc(100% + 10px) !important;
+ right: 0 !important;
+ background-color: var(--card-bg) !important;
+ border-radius: var(--border-radius) !important;
+ box-shadow: var(--shadow) !important;
+ padding: 15px !important;
+ min-width: 220px !important;
+ z-index: 102 !important;
+ display: none !important;
+ border: 1px solid var(--border-color) !important;
+ pointer-events: auto !important;
+}
+
+.settings-menu.active {
+ display: block !important;
+ animation: slide-in-top 0.3s forwards !important;
+}
+
+@keyframes slide-in-top {
+ from {
+ opacity: 0;
+ transform: translateY(-10px);
+ }
+ to {
+ opacity: 1;
+ transform: translateY(0);
+ }
+}
+
+.settings-item {
+ padding: 10px 0 !important;
+ display: flex !important;
+ justify-content: space-between !important;
+ align-items: center !important;
+ border-bottom: 1px solid var(--border-color) !important;
+}
+
+.settings-item:last-child {
+ border-bottom: none !important;
+}
+
+.settings-link {
+ color: var(--text-color) !important;
+ text-decoration: none !important;
+ display: flex !important;
+ align-items: center !important;
+ width: 100% !important;
+ transition: color 0.3s !important;
+}
+
+.settings-link:hover {
+ color: var(--primary-color) !important;
+}
+
+.settings-link i {
+ margin-right: 10px !important;
+ width: 16px !important;
+ text-align: center !important;
+}
+
+.github-link {
+ color: var(--text-color) !important;
+}
+
+.github-link:hover {
+ color: #6e5494 !important;
+}
\ No newline at end of file
diff --git a/frontend/include-auth-new.js b/frontend/include-auth-new.js
new file mode 100644
index 0000000..3e3009c
--- /dev/null
+++ b/frontend/include-auth-new.js
@@ -0,0 +1,148 @@
+/**
+ * Immediate Authentication State Handler
+ *
+ * This script runs as soon as possible to hide login/register buttons if a user is logged in
+ * It should be included directly in the HTML before any other scripts
+ */
+
+console.log('include-auth-new.js: Running immediate auth check');
+
+// Immediately check if user is logged in
+if (localStorage.getItem('auth_token')) {
+ console.log('include-auth-new.js: Auth token found, hiding login/register buttons immediately');
+
+ // Create and inject CSS to hide auth buttons
+ var style = document.createElement('style');
+ style.textContent = `
+ #authContainer, .auth-buttons, a[href="login.html"], a[href="register.html"],
+ .login-btn, .register-btn, .auth-btn.login-btn, .auth-btn.register-btn {
+ display: none !important;
+ visibility: hidden !important;
+ }
+
+ #userMenu, .user-menu {
+ display: block !important;
+ visibility: visible !important;
+ }
+ `;
+ document.head.appendChild(style);
+
+ // Set the display style as soon as DOM is ready
+ window.addEventListener('DOMContentLoaded', function() {
+ console.log('include-auth-new.js: DOM loaded, ensuring buttons are hidden');
+
+ // Hide auth container
+ var authContainer = document.getElementById('authContainer');
+ if (authContainer) {
+ authContainer.style.display = 'none';
+ authContainer.style.visibility = 'hidden';
+ }
+
+ // Hide all login/register buttons
+ document.querySelectorAll('a[href="login.html"], a[href="register.html"], .login-btn, .register-btn, .auth-btn').forEach(function(button) {
+ button.style.display = 'none';
+ button.style.visibility = 'hidden';
+ });
+
+ // Show user menu
+ var userMenu = document.getElementById('userMenu');
+ if (userMenu) {
+ userMenu.style.display = 'block';
+ userMenu.style.visibility = 'visible';
+ }
+
+ // Update user information
+ try {
+ var userInfoStr = localStorage.getItem('user_info');
+ if (userInfoStr) {
+ var userInfo = JSON.parse(userInfoStr);
+ var displayName = userInfo.first_name || userInfo.username || 'User';
+
+ var userDisplayName = document.getElementById('userDisplayName');
+ if (userDisplayName) {
+ userDisplayName.textContent = displayName;
+ }
+
+ var userName = document.getElementById('userName');
+ if (userName) {
+ userName.textContent = (userInfo.first_name || '') + ' ' + (userInfo.last_name || '');
+ if (!userName.textContent.trim()) userName.textContent = userInfo.username || 'User';
+ }
+
+ var userEmail = document.getElementById('userEmail');
+ if (userEmail && userInfo.email) {
+ userEmail.textContent = userInfo.email;
+ }
+ }
+ } catch (e) {
+ console.error('include-auth-new.js: Error updating user info:', e);
+ }
+ });
+} else {
+ console.log('include-auth-new.js: No auth token found, showing login/register buttons');
+
+ // Create and inject CSS to show auth buttons
+ var style = document.createElement('style');
+ style.textContent = `
+ #authContainer, .auth-buttons {
+ display: flex !important;
+ visibility: visible !important;
+ }
+
+ a[href="login.html"], a[href="register.html"],
+ .login-btn, .register-btn, .auth-btn.login-btn, .auth-btn.register-btn {
+ display: inline-block !important;
+ visibility: visible !important;
+ }
+
+ #userMenu, .user-menu {
+ display: none !important;
+ visibility: hidden !important;
+ }
+ `;
+ document.head.appendChild(style);
+}
+
+// Listen for changes to localStorage
+window.addEventListener('storage', function(event) {
+ if (event.key === 'auth_token' || event.key === 'user_info') {
+ console.log('include-auth-new.js: Auth data changed, reloading page to update UI');
+ window.location.reload();
+ }
+});
+
+/**
+ * Script to include the new authentication script in existing HTML files
+ * This script should be included at the end of the body in each HTML file
+ */
+
+// Function to load and execute the new authentication script
+function loadAuthNewScript() {
+ // Create a script element
+ const script = document.createElement('script');
+ script.src = 'auth-new.js';
+ script.async = true;
+
+ // Add the script to the document
+ document.body.appendChild(script);
+
+ console.log('Added auth-new.js script to the page');
+}
+
+// Function to check if we're using the new UI
+function isNewUI() {
+ // Check for elements that are specific to the new UI
+ const loginButton = document.querySelector('a[href="login.html"].auth-btn, a.login');
+ const registerButton = document.querySelector('a[href="register.html"].auth-btn, a.register');
+
+ // If we find these elements, we're using the new UI
+ return !!(loginButton || registerButton);
+}
+
+// Load the new authentication script if we're using the new UI
+if (isNewUI()) {
+ console.log('Detected new UI, loading auth-new.js');
+ loadAuthNewScript();
+} else {
+ console.log('Using old UI, not loading auth-new.js');
+}
\ No newline at end of file
diff --git a/frontend/index.html b/frontend/index.html
index b2e813d..afdd037 100644
--- a/frontend/index.html
+++ b/frontend/index.html
@@ -1,12 +1,202 @@
<!DOCTYPE html>
<html lang="en">
<head>
+ <!-- Authentication redirect script -->
+ <script src="auth-redirect.js" data-protected="true"></script>
+
+ <!-- Include authentication script first to handle login state immediately -->
+ <script src="include-auth-new.js"></script>
+
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Warranty Tracker</title>
<link rel="stylesheet" href="style.css">
<!-- 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>
+ .user-menu {
+ position: relative;
+ margin-left: 15px;
+ }
+
+ .user-btn {
+ background: none;
+ border: none;
+ color: var(--text-color);
+ cursor: pointer;
+ display: flex;
+ align-items: center;
+ font-size: 0.9rem;
+ padding: 5px 10px;
+ border-radius: 20px;
+ transition: background-color 0.3s;
+ }
+
+ .user-btn:hover {
+ background-color: rgba(0, 0, 0, 0.05);
+ }
+
+ .dark-mode .user-btn:hover {
+ background-color: rgba(255, 255, 255, 0.1);
+ }
+
+ .user-btn i {
+ margin-right: 5px;
+ }
+
+ .user-menu-dropdown {
+ position: absolute;
+ top: 100%;
+ right: 0;
+ background-color: var(--card-bg);
+ border-radius: 8px;
+ box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
+ width: 200px;
+ z-index: 1000;
+ display: none;
+ padding: 10px 0;
+ margin-top: 5px;
+ }
+
+ .user-menu-dropdown.active {
+ display: block;
+ }
+
+ .user-info {
+ padding: 10px 15px;
+ border-bottom: 1px solid var(--border-color);
+ margin-bottom: 5px;
+ }
+
+ .user-name {
+ font-weight: bold;
+ margin-bottom: 5px;
+ }
+
+ .user-email {
+ font-size: 0.8rem;
+ color: var(--text-muted);
+ word-break: break-all;
+ }
+
+ .user-menu-item {
+ padding: 8px 15px;
+ cursor: pointer;
+ transition: background-color 0.3s;
+ display: flex;
+ align-items: center;
+ }
+
+ .user-menu-item:hover {
+ background-color: var(--hover-bg);
+ }
+
+ .user-menu-item i {
+ margin-right: 10px;
+ width: 16px;
+ text-align: center;
+ }
+
+ .auth-buttons {
+ display: flex;
+ gap: 10px;
+ margin-left: 15px;
+ }
+
+ .auth-btn {
+ padding: 5px 15px;
+ border-radius: 20px;
+ font-size: 0.9rem;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ cursor: pointer;
+ transition: all 0.3s ease;
+ }
+
+ .auth-btn i {
+ margin-right: 5px;
+ }
+
+ .login-btn {
+ background-color: transparent;
+ border: 1px solid var(--primary-color);
+ color: var(--primary-color);
+ }
+
+ .login-btn:hover {
+ background-color: rgba(var(--primary-rgb), 0.1);
+ }
+
+ .register-btn {
+ background-color: var(--primary-color);
+ border: 1px solid var(--primary-color);
+ color: white;
+ }
+
+ .register-btn:hover {
+ background-color: var(--primary-dark);
+ }
+ </style>
+
+ <!-- Immediate authentication check script -->
+ <script>
+ // Check if user is logged in immediately to hide buttons
+ (function() {
+ if (localStorage.getItem('auth_token')) {
+ // Hide login and register buttons immediately
+ document.addEventListener('DOMContentLoaded', function() {
+ console.log('Inline script: User is logged in, hiding login/register buttons');
+
+ // Hide auth container
+ var authContainer = document.getElementById('authContainer');
+ if (authContainer) {
+ authContainer.style.display = 'none';
+ authContainer.style.visibility = 'hidden';
+ }
+
+ // Show user menu
+ var userMenu = document.getElementById('userMenu');
+ if (userMenu) {
+ userMenu.style.display = 'block';
+ userMenu.style.visibility = 'visible';
+ }
+
+ // Update user info if possible
+ try {
+ var userInfo = JSON.parse(localStorage.getItem('user_info'));
+ if (userInfo) {
+ var displayName = userInfo.first_name || userInfo.username || 'User';
+ var userDisplayName = document.getElementById('userDisplayName');
+ if (userDisplayName) {
+ userDisplayName.textContent = displayName;
+ }
+
+ var userName = document.getElementById('userName');
+ if (userName) {
+ userName.textContent = (userInfo.first_name || '') + ' ' + (userInfo.last_name || '');
+ if (!userName.textContent.trim()) userName.textContent = userInfo.username || 'User';
+ }
+
+ var userEmail = document.getElementById('userEmail');
+ if (userEmail && userInfo.email) {
+ userEmail.textContent = userInfo.email;
+ }
+ }
+ } catch (e) {
+ console.error('Error updating user info:', e);
+ }
+ }, { once: true });
+ }
+ })();
+ </script>
+
+ <!-- Registration status check script -->
+ <script src="registration-status.js"></script>
</head>
<body>
<!-- Header -->
@@ -24,8 +214,39 @@
<i class="fas fa-chart-pie"></i> Status
</a>
</div>
+ <div id="authContainer" class="auth-buttons">
+ <a href="login.html" class="auth-btn login-btn">
+ <i class="fas fa-sign-in-alt"></i> Login
+ </a>
+ <a href="register.html" class="auth-btn register-btn">
+ <i class="fas fa-user-plus"></i> Register
+ </a>
+ </div>
+ <div id="userMenu" class="user-menu" style="display: none;">
+ <button id="userBtn" class="user-btn">
+ <i class="fas fa-user-circle"></i>
+ <span id="userDisplayName">User</span>
+ </button>
+ <div id="userMenuDropdown" class="user-menu-dropdown">
+ <div class="user-info">
+ <div id="userName" class="user-name">User Name</div>
+ <div id="userEmail" class="user-email">[email protected]</div>
+ </div>
+ <div class="user-menu-item" id="profileMenuItem">
+ <i class="fas fa-id-card"></i> Profile
+ </div>
+ <div class="user-menu-item">
+ <a href="settings-new.html" style="color: inherit; text-decoration: none; display: block;">
+ <i class="fas fa-cog"></i> Settings
+ </a>
+ </div>
+ <div class="user-menu-item" id="logoutMenuItem">
+ <i class="fas fa-sign-out-alt"></i> Logout
+ </div>
+ </div>
+ </div>
<div class="settings-container">
- <button id="settingsBtn" class="settings-btn" aria-label="Settings">
+ <button id="settingsBtn" class="settings-btn" aria-label="Settings" type="button">
<i class="fas fa-cog"></i>
</button>
<div id="settingsMenu" class="settings-menu">
@@ -97,12 +318,7 @@
<div class="form-group">
<label>Serial Numbers</label>
<div id="serialNumbersContainer">
- <div class="serial-number-input">
- <input type="text" name="serial_numbers[]" class="form-control" placeholder="Enter serial number">
- <button type="button" class="btn btn-sm btn-secondary add-serial-number">
- <i class="fas fa-plus"></i> Add Another
- </button>
- </div>
+ <!-- Serial number inputs will be added dynamically -->
</div>
</div>
</div>
@@ -343,12 +559,7 @@
<div class="form-group">
<label>Serial Numbers</label>
<div id="editSerialNumbersContainer">
- <div class="serial-number-input">
- <input type="text" name="serial_numbers[]" class="form-control" placeholder="Enter serial number">
- <button type="button" class="btn btn-sm btn-secondary add-serial-number">
- <i class="fas fa-plus"></i> Add Another
- </button>
- </div>
+ <!-- Serial number inputs will be added dynamically -->
</div>
</div>
@@ -410,6 +621,7 @@
<div class="loading-spinner"></div>
</div>
+ <script src="auth.js"></script>
<script src="script.js"></script>
</body>
</html>
\ No newline at end of file
diff --git a/frontend/login.html b/frontend/login.html
new file mode 100644
index 0000000..e5b686b
--- /dev/null
+++ b/frontend/login.html
@@ -0,0 +1,340 @@
+<!DOCTYPE html>
+<html lang="en">
+<head>
+ <!-- Authentication redirect script -->
+ <script src="auth-redirect.js" data-protected="false"></script>
+
+ <meta charset="UTF-8">
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
+ <title>Login - Warranty Tracker</title>
+ <link rel="stylesheet" href="style.css">
+ <!-- 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;
+ margin: 50px auto;
+ padding: 30px;
+ background-color: var(--card-bg);
+ border-radius: 8px;
+ box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
+ }
+
+ .auth-title {
+ text-align: center;
+ margin-bottom: 30px;
+ color: var(--text-color);
+ }
+
+ .auth-form .form-group {
+ margin-bottom: 20px;
+ }
+
+ .auth-links {
+ margin-top: 20px;
+ text-align: center;
+ font-size: 0.9em;
+ }
+
+ .auth-links a {
+ color: var(--primary-color);
+ text-decoration: none;
+ margin: 0 10px;
+ }
+
+ .auth-links a:hover {
+ text-decoration: underline;
+ }
+
+ .auth-message {
+ margin-top: 20px;
+ padding: 10px;
+ border-radius: 4px;
+ text-align: center;
+ display: none;
+ }
+
+ .auth-message.error {
+ background-color: rgba(244, 67, 54, 0.1);
+ color: #f44336;
+ border: 1px solid rgba(244, 67, 54, 0.3);
+ }
+
+ .auth-message.success {
+ background-color: rgba(76, 175, 80, 0.1);
+ color: #4caf50;
+ border: 1px solid rgba(76, 175, 80, 0.3);
+ }
+
+ .btn-block {
+ width: 100%;
+ }
+
+ .auth-form .password-container {
+ position: relative;
+ }
+
+ .auth-form .password-toggle {
+ position: absolute;
+ right: 10px;
+ top: 50%;
+ transform: translateY(-50%);
+ background: none;
+ border: none;
+ color: var(--text-muted);
+ cursor: pointer;
+ }
+
+ /* Remember Me checkbox styling */
+ .remember-me-container {
+ display: flex;
+ align-items: center;
+ margin-bottom: 20px;
+ }
+
+ .checkbox-container {
+ display: flex;
+ align-items: center;
+ position: relative;
+ padding-left: 30px;
+ cursor: pointer;
+ user-select: none;
+ color: var(--text-color);
+ }
+
+ .checkbox-container input {
+ position: absolute;
+ opacity: 0;
+ cursor: pointer;
+ height: 0;
+ width: 0;
+ }
+
+ .checkmark {
+ position: absolute;
+ left: 0;
+ height: 20px;
+ width: 20px;
+ background-color: var(--input-bg);
+ border: 1px solid var(--border-color);
+ border-radius: 4px;
+ }
+
+ .checkbox-container:hover input ~ .checkmark {
+ background-color: var(--hover-bg);
+ }
+
+ .checkbox-container input:checked ~ .checkmark {
+ background-color: var(--primary-color);
+ border-color: var(--primary-color);
+ }
+
+ .checkmark:after {
+ content: "";
+ position: absolute;
+ display: none;
+ }
+
+ .checkbox-container input:checked ~ .checkmark:after {
+ display: block;
+ }
+
+ .checkbox-container .checkmark:after {
+ left: 7px;
+ top: 3px;
+ width: 5px;
+ height: 10px;
+ border: solid white;
+ border-width: 0 2px 2px 0;
+ transform: rotate(45deg);
+ }
+ </style>
+
+ <!-- Registration status check script -->
+ <script src="registration-status.js"></script>
+</head>
+<body>
+ <!-- Header -->
+ <header>
+ <div class="container">
+ <div class="app-title">
+ <i class="fas fa-shield-alt"></i>
+ <h1>Warranty Tracker</h1>
+ </div>
+ </div>
+ </header>
+
+ <!-- Main Content -->
+ <div class="container">
+ <div class="auth-container">
+ <h2 class="auth-title">Login to Your Account</h2>
+
+ <div id="authMessage" class="auth-message"></div>
+
+ <form id="loginForm" class="auth-form">
+ <div class="form-group">
+ <label for="username">Username or Email</label>
+ <input type="text" id="username" name="username" class="form-control" required>
+ </div>
+
+ <div class="form-group">
+ <label for="password">Password</label>
+ <div class="password-container">
+ <input type="password" id="password" name="password" class="form-control" required>
+ <button type="button" class="password-toggle" title="Show/Hide Password">
+ <i class="fas fa-eye"></i>
+ </button>
+ </div>
+ </div>
+
+ <div class="form-group remember-me-container">
+ <label class="checkbox-container">
+ <input type="checkbox" id="rememberMe" name="rememberMe">
+ <span class="checkmark"></span>
+ Remember Me
+ </label>
+ </div>
+
+ <button type="submit" class="btn btn-primary btn-block">
+ <i class="fas fa-sign-in-alt"></i> Login
+ </button>
+ </form>
+
+ <div class="auth-links">
+ <a href="register.html">Create Account</a>
+ <a href="reset-password-request.html">Forgot Password?</a>
+ </div>
+ </div>
+ </div>
+
+ <!-- Script for authentication -->
+ <script src="auth.js"></script>
+ <script>
+ document.addEventListener('DOMContentLoaded', function() {
+ // Toggle password visibility
+ const passwordToggle = document.querySelector('.password-toggle');
+ const passwordInput = document.getElementById('password');
+
+ passwordToggle.addEventListener('click', function() {
+ const type = passwordInput.getAttribute('type') === 'password' ? 'text' : 'password';
+ passwordInput.setAttribute('type', type);
+
+ // Toggle icon
+ const icon = this.querySelector('i');
+ icon.classList.toggle('fa-eye');
+ icon.classList.toggle('fa-eye-slash');
+ });
+
+ // Handle form submission
+ const loginForm = document.getElementById('loginForm');
+ const authMessage = document.getElementById('authMessage');
+
+ loginForm.addEventListener('submit', async function(e) {
+ e.preventDefault();
+
+ const username = document.getElementById('username').value;
+ const password = document.getElementById('password').value;
+
+ // Basic validation
+ if (!username || !password) {
+ showMessage('Please enter both username and password', 'error');
+ return;
+ }
+
+ try {
+ // Show loading state
+ const submitBtn = loginForm.querySelector('button[type="submit"]');
+ const originalBtnText = submitBtn.innerHTML;
+ submitBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Logging in...';
+ submitBtn.disabled = true;
+
+ // Check if "Remember Me" is checked
+ const rememberMe = document.getElementById('rememberMe').checked;
+
+ // Make API request
+ const response = await fetch('/api/auth/login', {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json'
+ },
+ body: JSON.stringify({ username, password, remember_me: rememberMe })
+ });
+
+ const data = await response.json();
+
+ if (!response.ok) {
+ throw new Error(data.message || 'Login failed');
+ }
+
+ // Store token in localStorage
+ localStorage.setItem('auth_token', data.token);
+ localStorage.setItem('user_info', JSON.stringify(data.user));
+
+ // If "Remember Me" is checked, store a flag
+ if (rememberMe) {
+ localStorage.setItem('remember_me', 'true');
+ } else {
+ localStorage.removeItem('remember_me');
+ }
+
+ // Show success message
+ showMessage('Login successful! Redirecting...', 'success');
+
+ // Redirect to home page after a short delay
+ setTimeout(() => {
+ window.location.href = 'index.html';
+ }, 1000);
+
+ } catch (error) {
+ console.error('Login error:', error);
+ showMessage(error.message || 'Login failed. Please check your credentials.', 'error');
+
+ // Reset button
+ submitBtn.innerHTML = originalBtnText;
+ submitBtn.disabled = false;
+ }
+ });
+
+ // Helper function to show messages
+ function showMessage(message, type) {
+ authMessage.textContent = message;
+ authMessage.className = 'auth-message';
+ authMessage.classList.add(type);
+ authMessage.style.display = 'block';
+ }
+
+ // Check for dark mode preference
+ const darkModeEnabled = localStorage.getItem('darkMode') === 'enabled';
+ if (darkModeEnabled) {
+ document.body.classList.add('dark-mode');
+ }
+ });
+
+ // Theme initialization
+ function setTheme(isDark) {
+ document.documentElement.setAttribute('data-theme', isDark ? 'dark' : 'light');
+ }
+
+ function initializeTheme() {
+ // Check for saved theme preference
+ const savedTheme = localStorage.getItem('darkMode');
+
+ if (savedTheme !== null) {
+ // Use saved preference
+ setTheme(savedTheme === 'true');
+ } else {
+ // Use system preference as fallback
+ const prefersDarkMode = window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches;
+ setTheme(prefersDarkMode);
+ }
+ }
+
+ // Initialize theme when page loads
+ document.addEventListener('DOMContentLoaded', initializeTheme);
+ </script>
+</body>
+</html>
diff --git a/frontend/register.html b/frontend/register.html
new file mode 100644
index 0000000..f29938c
--- /dev/null
+++ b/frontend/register.html
@@ -0,0 +1,603 @@
+<!DOCTYPE html>
+<html lang="en">
+<head>
+ <!-- Authentication redirect script -->
+ <script src="auth-redirect.js" data-protected="false"></script>
+
+ <meta charset="UTF-8">
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
+ <title>Register - Warranty Tracker</title>
+ <link rel="stylesheet" href="style.css">
+ <!-- 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: 500px;
+ margin: 50px auto;
+ padding: 30px;
+ background-color: var(--card-bg);
+ border-radius: 8px;
+ box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
+ }
+
+ .auth-title {
+ text-align: center;
+ margin-bottom: 30px;
+ color: var(--text-color);
+ }
+
+ .auth-form .form-group {
+ margin-bottom: 20px;
+ }
+
+ .auth-links {
+ margin-top: 20px;
+ text-align: center;
+ font-size: 0.9em;
+ }
+
+ .auth-links a {
+ color: var(--primary-color);
+ text-decoration: none;
+ margin: 0 10px;
+ }
+
+ .auth-links a:hover {
+ text-decoration: underline;
+ }
+
+ .auth-message {
+ margin-top: 20px;
+ padding: 10px;
+ border-radius: 4px;
+ text-align: center;
+ display: none;
+ }
+
+ .auth-message.error {
+ background-color: rgba(244, 67, 54, 0.1);
+ color: #f44336;
+ border: 1px solid rgba(244, 67, 54, 0.3);
+ padding: 15px;
+ border-radius: 8px;
+ margin-bottom: 20px;
+ }
+
+ .auth-message.error h3 {
+ margin-top: 0;
+ margin-bottom: 10px;
+ font-size: 1.2rem;
+ color: #d32f2f;
+ }
+
+ .auth-message.error p {
+ margin-bottom: 10px;
+ }
+
+ .auth-message.error i {
+ margin-right: 8px;
+ }
+
+ .auth-message.success {
+ background-color: rgba(76, 175, 80, 0.1);
+ color: #4caf50;
+ border: 1px solid rgba(76, 175, 80, 0.3);
+ }
+
+ .btn-block {
+ width: 100%;
+ }
+
+ .auth-form .password-container {
+ position: relative;
+ }
+
+ .auth-form .password-toggle {
+ position: absolute;
+ right: 10px;
+ top: 50%;
+ transform: translateY(-50%);
+ background: none;
+ border: none;
+ color: var(--text-muted);
+ cursor: pointer;
+ }
+
+ .password-strength {
+ height: 5px;
+ margin-top: 5px;
+ border-radius: 2px;
+ transition: all 0.3s ease;
+ background-color: #e0e0e0;
+ width: 100%;
+ }
+
+ .password-strength.empty {
+ background-color: #e0e0e0;
+ width: 0%;
+ }
+
+ .password-strength.weak {
+ background-color: #f44336; /* Red */
+ width: 33%;
+ }
+
+ .password-strength.medium {
+ background-color: #ff9800; /* Orange */
+ width: 66%;
+ }
+
+ .password-strength.strong {
+ background-color: #4caf50; /* Green */
+ width: 100%;
+ }
+
+ .password-strength-text {
+ font-size: 0.8em;
+ margin-top: 5px;
+ text-align: right;
+ }
+
+ .form-row {
+ display: flex;
+ gap: 20px;
+ }
+
+ .form-row .form-group {
+ flex: 1;
+ }
+
+ @media (max-width: 768px) {
+ .form-row {
+ flex-direction: column;
+ gap: 0;
+ }
+ }
+
+ /* Password Requirements Styles */
+ .password-requirements {
+ margin-top: 10px;
+ padding: 10px;
+ background-color: var(--light-gray);
+ border-radius: 4px;
+ font-size: 0.9em;
+ }
+
+ .password-requirements h5 {
+ margin-top: 0;
+ margin-bottom: 8px;
+ font-size: 0.95em;
+ color: var(--text-color);
+ }
+
+ .password-requirements ul {
+ margin: 0;
+ padding-left: 20px;
+ }
+
+ .password-requirements li {
+ margin-bottom: 4px;
+ color: var(--text-muted);
+ }
+
+ .password-requirements li.met {
+ color: var(--primary-color);
+ }
+
+ .password-requirements li.met::before {
+ content: "✓ ";
+ }
+
+ .password-feedback {
+ margin-top: 5px;
+ font-size: 0.85em;
+ color: var(--text-muted);
+ text-align: right;
+ }
+
+ /* Password confirmation validation styles */
+ input.valid {
+ border-color: #4caf50 !important;
+ background-color: rgba(76, 175, 80, 0.05);
+ }
+
+ input.invalid {
+ border-color: #f44336 !important;
+ background-color: rgba(244, 67, 54, 0.05);
+ }
+
+ .btn-sm {
+ padding: 5px 10px;
+ font-size: 0.875rem;
+ }
+
+ .mt-2 {
+ margin-top: 10px;
+ }
+ </style>
+
+ <!-- Registration status check script -->
+ <script src="registration-status.js"></script>
+ <script>
+ // Additional handling for the register page
+ document.addEventListener('DOMContentLoaded', function() {
+ // Only check if user is not logged in
+ if (!localStorage.getItem('auth_token')) {
+ fetch('/api/auth/registration-status')
+ .then(response => response.json())
+ .then(data => {
+ if (!data.enabled) {
+ // Show a more prominent message on the register page
+ const authMessage = document.getElementById('authMessage');
+ if (authMessage) {
+ authMessage.className = 'auth-message error';
+ authMessage.style.display = 'block';
+ authMessage.innerHTML = `
+ <h3><i class="fas fa-exclamation-triangle"></i> Registration Disabled</h3>
+ <p>The administrator has temporarily disabled new account registration.</p>
+ <p>If you need an account, please contact the site administrator.</p>
+ <p><a href="login.html" class="btn btn-primary btn-sm mt-2">Go to Login</a></p>
+ `;
+ }
+
+ // Hide the entire form
+ const registerForm = document.getElementById('registerForm');
+ if (registerForm) {
+ registerForm.style.display = 'none';
+ }
+
+ // Hide the auth links
+ const authLinks = document.querySelector('.auth-links');
+ if (authLinks) {
+ authLinks.style.display = 'none';
+ }
+ }
+ })
+ .catch(error => {
+ console.error('Error checking registration status:', error);
+ });
+ }
+ });
+ </script>
+</head>
+<body>
+ <!-- Header -->
+ <header>
+ <div class="container">
+ <div class="app-title">
+ <i class="fas fa-shield-alt"></i>
+ <h1>Warranty Tracker</h1>
+ </div>
+ </div>
+ </header>
+
+ <!-- Main Content -->
+ <div class="container">
+ <div class="auth-container">
+ <h2 class="auth-title">Create Your Account</h2>
+
+ <div id="authMessage" class="auth-message"></div>
+
+ <form id="registerForm" class="auth-form">
+ <div class="form-row">
+ <div class="form-group">
+ <label for="firstName">First Name (Optional)</label>
+ <input type="text" id="firstName" name="first_name" class="form-control">
+ </div>
+
+ <div class="form-group">
+ <label for="lastName">Last Name (Optional)</label>
+ <input type="text" id="lastName" name="last_name" class="form-control">
+ </div>
+ </div>
+
+ <div class="form-group">
+ <label for="username">Username</label>
+ <input type="text" id="username" name="username" class="form-control" required>
+ <small class="form-text text-muted">Username must be unique and will be used for login.</small>
+ </div>
+
+ <div class="form-group">
+ <label for="email">Email Address</label>
+ <input type="email" id="email" name="email" class="form-control" required>
+ </div>
+
+ <div class="form-group">
+ <label for="password">Password</label>
+ <div class="password-container">
+ <input type="password" id="password" name="password" class="form-control" required>
+ <button type="button" class="password-toggle" title="Show/Hide Password">
+ <i class="fas fa-eye"></i>
+ </button>
+ </div>
+ <div class="password-strength" id="passwordStrength"></div>
+ <div class="password-strength-text" id="passwordStrengthText"></div>
+ <small class="form-text text-muted">Password must be at least 8 characters and include uppercase, lowercase, and numbers.</small>
+
+ <!-- Password Requirements List -->
+ <div id="passwordRequirements" class="password-requirements" style="display: none;">
+ <h5>Password Requirements:</h5>
+ <ul>
+ <li id="req-length">At least 8 characters</li>
+ <li id="req-uppercase">At least 1 uppercase letter</li>
+ <li id="req-lowercase">At least 1 lowercase letter</li>
+ <li id="req-number">At least 1 number</li>
+ <li id="req-special">At least 1 special character</li>
+ </ul>
+ </div>
+ <div id="passwordFeedback" class="password-feedback"></div>
+ </div>
+
+ <div class="form-group">
+ <label for="confirmPassword">Confirm Password</label>
+ <div class="password-container">
+ <input type="password" id="confirmPassword" name="confirmPassword" class="form-control" required>
+ <button type="button" class="password-toggle" title="Show/Hide Password">
+ <i class="fas fa-eye"></i>
+ </button>
+ </div>
+ <div id="passwordMatchFeedback" class="password-feedback"></div>
+ </div>
+
+ <button type="submit" class="btn btn-primary btn-block">
+ <i class="fas fa-user-plus"></i> Create Account
+ </button>
+ </form>
+
+ <div class="auth-links">
+ <span>Already have an account?</span>
+ <a href="login.html">Login</a>
+ </div>
+ </div>
+ </div>
+
+ <!-- Script for authentication -->
+ <script src="auth.js"></script>
+ <script>
+ document.addEventListener('DOMContentLoaded', function() {
+ const registerForm = document.getElementById('registerForm');
+ const passwordInput = document.getElementById('password');
+ const confirmPasswordInput = document.getElementById('confirmPassword');
+ const passwordRequirements = document.getElementById('passwordRequirements');
+ const passwordStrength = document.getElementById('passwordStrength');
+ const passwordFeedback = document.getElementById('passwordFeedback');
+ const authMessage = document.getElementById('authMessage');
+
+ // Show password requirements when password field is focused
+ if (passwordInput && passwordRequirements) {
+ passwordInput.addEventListener('focus', function() {
+ passwordRequirements.style.display = 'block';
+ });
+
+ // Hide password requirements when focus is lost
+ passwordInput.addEventListener('blur', function() {
+ passwordRequirements.style.display = 'none';
+ });
+ }
+
+ // Password strength checker
+ if (passwordInput && passwordStrength) {
+ passwordInput.addEventListener('input', function() {
+ const password = this.value;
+ let strength = 0;
+
+ // Update requirements list if elements exist
+ const reqLength = document.getElementById('req-length');
+ const reqUppercase = document.getElementById('req-uppercase');
+ const reqLowercase = document.getElementById('req-lowercase');
+ const reqNumber = document.getElementById('req-number');
+ const reqSpecial = document.getElementById('req-special');
+
+ if (reqLength) reqLength.classList.toggle('met', password.length >= 8);
+ if (reqUppercase) reqUppercase.classList.toggle('met', /[A-Z]/.test(password));
+ if (reqLowercase) reqLowercase.classList.toggle('met', /[a-z]/.test(password));
+ if (reqNumber) reqNumber.classList.toggle('met', /[0-9]/.test(password));
+ if (reqSpecial) reqSpecial.classList.toggle('met', /[^A-Za-z0-9]/.test(password));
+
+ // Calculate strength
+ if (password.length >= 8) strength += 1;
+ if (/[A-Z]/.test(password)) strength += 1;
+ if (/[a-z]/.test(password)) strength += 1;
+ if (/[0-9]/.test(password)) strength += 1;
+ if (/[^A-Za-z0-9]/.test(password)) strength += 1;
+
+ // Update strength meter - first remove all classes
+ passwordStrength.className = 'password-strength';
+ const strengthText = document.getElementById('passwordStrengthText');
+
+ // Then add the appropriate class based on strength
+ if (password.length === 0) {
+ passwordStrength.classList.add('empty');
+ if (strengthText) strengthText.textContent = '';
+ if (passwordFeedback) passwordFeedback.textContent = '';
+ } else if (strength < 3) {
+ passwordStrength.classList.add('weak');
+ if (strengthText) strengthText.textContent = 'Weak';
+ if (passwordFeedback) passwordFeedback.textContent = 'Weak password';
+ } else if (strength < 5) {
+ passwordStrength.classList.add('medium');
+ if (strengthText) strengthText.textContent = 'Medium';
+ if (passwordFeedback) passwordFeedback.textContent = 'Medium strength password';
+ } else {
+ passwordStrength.classList.add('strong');
+ if (strengthText) strengthText.textContent = 'Strong';
+ if (passwordFeedback) passwordFeedback.textContent = 'Strong password';
+ }
+
+ // Force a reflow to ensure the CSS transition works
+ passwordStrength.offsetHeight;
+ });
+ }
+
+ // Check if passwords match
+ confirmPasswordInput.addEventListener('input', function() {
+ const password = passwordInput.value;
+ const confirmPassword = this.value;
+ const passwordMatchFeedback = document.getElementById('passwordMatchFeedback');
+
+ if (confirmPassword === '') {
+ this.classList.remove('invalid');
+ this.classList.remove('valid');
+ if (passwordMatchFeedback) passwordMatchFeedback.textContent = '';
+ } else if (password === confirmPassword) {
+ this.classList.remove('invalid');
+ this.classList.add('valid');
+ if (passwordMatchFeedback) {
+ passwordMatchFeedback.textContent = 'Passwords match';
+ passwordMatchFeedback.style.color = '#4caf50';
+ }
+ } else {
+ this.classList.add('invalid');
+ this.classList.remove('valid');
+ if (passwordMatchFeedback) {
+ passwordMatchFeedback.textContent = 'Passwords do not match';
+ passwordMatchFeedback.style.color = '#f44336';
+ }
+ }
+ });
+
+ // Setup password toggle buttons
+ const passwordToggles = document.querySelectorAll('.password-toggle');
+ passwordToggles.forEach(toggle => {
+ toggle.addEventListener('click', function() {
+ const passwordInput = this.parentElement.querySelector('input');
+ const type = passwordInput.getAttribute('type') === 'password' ? 'text' : 'password';
+ passwordInput.setAttribute('type', type);
+
+ // Toggle icon
+ const icon = this.querySelector('i');
+ icon.classList.toggle('fa-eye');
+ icon.classList.toggle('fa-eye-slash');
+ });
+ });
+
+ // Form submission
+ registerForm.addEventListener('submit', async function(e) {
+ e.preventDefault();
+
+ // Validate form
+ const firstName = document.getElementById('firstName').value.trim();
+ const lastName = document.getElementById('lastName').value.trim();
+ const username = document.getElementById('username').value.trim();
+ const email = document.getElementById('email').value.trim();
+ const password = passwordInput.value;
+ const confirmPassword = confirmPasswordInput.value;
+
+ // Basic validation
+ if (!username || !email || !password || !confirmPassword) {
+ showMessage('Please fill in all required fields', 'error');
+ return;
+ }
+
+ if (password !== confirmPassword) {
+ showMessage('Passwords do not match', 'error');
+ return;
+ }
+
+ // Email validation
+ const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
+ if (!emailRegex.test(email)) {
+ showMessage('Please enter a valid email address', 'error');
+ return;
+ }
+
+ // Password strength validation
+ let strength = 0;
+ if (password.length >= 8) strength += 1;
+ if (/[A-Z]/.test(password)) strength += 1;
+ if (/[a-z]/.test(password)) strength += 1;
+ if (/[0-9]/.test(password)) strength += 1;
+ if (/[^A-Za-z0-9]/.test(password)) strength += 1;
+
+ if (strength < 3) {
+ showMessage('Password is too weak. Please make it stronger.', 'error');
+ return;
+ }
+
+ // Disable form and show loading
+ const submitBtn = document.querySelector('button[type="submit"]');
+ submitBtn.disabled = true;
+ submitBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Registering...';
+
+ try {
+ // Send registration request
+ const response = await fetch('/api/auth/register', {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json'
+ },
+ body: JSON.stringify({
+ username,
+ email,
+ password,
+ first_name: firstName,
+ last_name: lastName
+ })
+ });
+
+ const data = await response.json();
+
+ if (response.ok) {
+ showMessage('Registration successful! Redirecting to login...', 'success');
+ setTimeout(() => {
+ window.location.href = 'login.html';
+ }, 2000);
+ } else {
+ showMessage(data.error || 'Registration failed. Please try again.', 'error');
+ }
+ } catch (error) {
+ showMessage('Network error. Please check your connection and try again.', 'error');
+ console.error('Registration error:', error);
+ } finally {
+ // Re-enable form
+ submitBtn.disabled = false;
+ submitBtn.innerHTML = 'Register';
+ }
+ });
+
+ // Helper function to show messages
+ function showMessage(message, type) {
+ authMessage.textContent = message;
+ authMessage.className = 'auth-message';
+ authMessage.classList.add(type);
+ authMessage.style.display = 'block';
+
+ // Scroll to message
+ authMessage.scrollIntoView({ behavior: 'smooth', block: 'nearest' });
+ }
+
+ // Check for dark mode preference
+ const darkModeEnabled = localStorage.getItem('darkMode') === 'enabled';
+ if (darkModeEnabled) {
+ document.body.classList.add('dark-mode');
+ }
+ });
+
+ // Theme initialization
+ function setTheme(isDark) {
+ document.documentElement.setAttribute('data-theme', isDark ? 'dark' : 'light');
+ }
+
+ function initializeTheme() {
+ // Check for saved theme preference
+ const savedTheme = localStorage.getItem('darkMode');
+
+ if (savedTheme !== null) {
+ // Use saved preference
+ setTheme(savedTheme === 'true');
+ } else {
+ // Use system preference as fallback
+ const prefersDarkMode = window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches;
+ setTheme(prefersDarkMode);
+ }
+ }
+
+ // Initialize theme when page loads
+ document.addEventListener('DOMContentLoaded', initializeTheme);
+ </script>
+</body>
+</html>
diff --git a/frontend/registration-status.js b/frontend/registration-status.js
new file mode 100644
index 0000000..388e94d
--- /dev/null
+++ b/frontend/registration-status.js
@@ -0,0 +1,92 @@
+/**
+ * Registration Status Checker
+ *
+ * This script checks if registration is enabled on the site and hides registration buttons/links if disabled.
+ * Include this script in all pages that have registration links or buttons.
+ */
+
+document.addEventListener('DOMContentLoaded', function() {
+ // Only check if user is not logged in
+ if (!localStorage.getItem('auth_token')) {
+ checkRegistrationStatus();
+ }
+});
+
+/**
+ * Check if registration is enabled and hide registration elements if disabled
+ */
+function checkRegistrationStatus() {
+ fetch('/api/auth/registration-status')
+ .then(response => response.json())
+ .then(data => {
+ if (!data.enabled) {
+ // Hide all registration links and buttons
+ hideRegistrationElements();
+ }
+ })
+ .catch(error => {
+ console.error('Error checking registration status:', error);
+ });
+}
+
+/**
+ * Hide all registration-related elements on the page
+ */
+function hideRegistrationElements() {
+ // Hide elements with specific classes
+ const elements = [
+ '.register-btn', // Main navigation register button
+ 'a[href="register.html"]', // Links to register page
+ 'a[href="./register.html"]', // Links to register page (relative)
+ 'a[href="/register.html"]' // Links to register page (root relative)
+ ];
+
+ // Apply to all matching elements
+ elements.forEach(selector => {
+ document.querySelectorAll(selector).forEach(element => {
+ element.style.display = 'none';
+ });
+ });
+
+ // Special case for auth container in the header
+ const authContainer = document.getElementById('authContainer');
+ if (authContainer) {
+ // Check if it has multiple children and at least one is hidden
+ const children = authContainer.children;
+ let visibleCount = 0;
+
+ for (let i = 0; i < children.length; i++) {
+ if (children[i].style.display !== 'none') {
+ visibleCount++;
+ }
+ }
+
+ // If there's only one visible child, adjust the container styling
+ if (visibleCount === 1) {
+ authContainer.style.justifyContent = 'flex-end';
+ }
+ }
+
+ // Special case for auth links in login/register pages
+ const authLinks = document.querySelector('.auth-links');
+ if (authLinks) {
+ const links = authLinks.querySelectorAll('a');
+ links.forEach(link => {
+ if (link.textContent === 'Create Account' ||
+ link.href.includes('register.html')) {
+ link.style.display = 'none';
+ }
+ });
+
+ // Add a message about registration being disabled if we're on the login page
+ if (window.location.pathname.includes('login.html')) {
+ const infoMessage = document.createElement('div');
+ infoMessage.className = 'registration-info';
+ infoMessage.innerHTML = '<small>New account registration is currently disabled</small>';
+ infoMessage.style.color = 'var(--text-muted)';
+ infoMessage.style.fontSize = '0.8em';
+ infoMessage.style.marginTop = '10px';
+ authLinks.appendChild(infoMessage);
+ }
+ }
+}
\ No newline at end of file
diff --git a/frontend/reset-password-request.html b/frontend/reset-password-request.html
new file mode 100644
index 0000000..4a5dec2
--- /dev/null
+++ b/frontend/reset-password-request.html
@@ -0,0 +1,227 @@
+<!DOCTYPE html>
+<html lang="en">
+<head>
+ <meta charset="UTF-8">
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
+ <title>Reset Password - Warranty Tracker</title>
+ <link rel="stylesheet" href="style.css">
+ <!-- Font Awesome for icons -->
+ <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
+ <style>
+ .auth-container {
+ max-width: 400px;
+ margin: 50px auto;
+ padding: 30px;
+ background-color: var(--card-bg);
+ border-radius: 8px;
+ box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
+ }
+
+ .auth-title {
+ text-align: center;
+ margin-bottom: 30px;
+ color: var(--text-color);
+ }
+
+ .auth-form .form-group {
+ margin-bottom: 20px;
+ }
+
+ .auth-links {
+ margin-top: 20px;
+ text-align: center;
+ font-size: 0.9em;
+ }
+
+ .auth-links a {
+ color: var(--primary-color);
+ text-decoration: none;
+ margin: 0 10px;
+ }
+
+ .auth-links a:hover {
+ text-decoration: underline;
+ }
+
+ .auth-message {
+ margin-top: 20px;
+ padding: 10px;
+ border-radius: 4px;
+ text-align: center;
+ display: none;
+ }
+
+ .auth-message.error {
+ background-color: rgba(244, 67, 54, 0.1);
+ color: #f44336;
+ border: 1px solid rgba(244, 67, 54, 0.3);
+ }
+
+ .auth-message.success {
+ background-color: rgba(76, 175, 80, 0.1);
+ color: #4caf50;
+ border: 1px solid rgba(76, 175, 80, 0.3);
+ }
+
+ .btn-block {
+ width: 100%;
+ }
+
+ .auth-info {
+ margin-bottom: 20px;
+ color: var(--text-muted);
+ text-align: center;
+ font-size: 0.9em;
+ line-height: 1.5;
+ }
+ </style>
+</head>
+<body>
+ <!-- Header -->
+ <header>
+ <div class="container">
+ <div class="app-title">
+ <i class="fas fa-shield-alt"></i>
+ <h1>Warranty Tracker</h1>
+ </div>
+ </div>
+ </header>
+
+ <!-- Main Content -->
+ <div class="container">
+ <div class="auth-container">
+ <h2 class="auth-title">Reset Your Password</h2>
+
+ <p class="auth-info">
+ Enter your email address below and we'll send you a link to reset your password.
+ </p>
+
+ <div id="authMessage" class="auth-message"></div>
+
+ <form id="resetRequestForm" class="auth-form">
+ <div class="form-group">
+ <label for="email">Email Address</label>
+ <input type="email" id="email" name="email" class="form-control" required>
+ </div>
+
+ <button type="submit" class="btn btn-primary btn-block">
+ <i class="fas fa-paper-plane"></i> Send Reset Link
+ </button>
+ </form>
+
+ <div class="auth-links">
+ <a href="login.html">Back to Login</a>
+ </div>
+ </div>
+ </div>
+
+ <script>
+ document.addEventListener('DOMContentLoaded', function() {
+ // Check if user is already logged in
+ const token = localStorage.getItem('auth_token');
+ if (token) {
+ // Redirect to home page if already logged in
+ window.location.href = 'index.html';
+ return;
+ }
+
+ // Handle form submission
+ const resetRequestForm = document.getElementById('resetRequestForm');
+ const authMessage = document.getElementById('authMessage');
+
+ resetRequestForm.addEventListener('submit', async function(e) {
+ e.preventDefault();
+
+ const email = document.getElementById('email').value;
+
+ // Basic validation
+ if (!email) {
+ showMessage('Please enter your email address', 'error');
+ return;
+ }
+
+ // Validate email format
+ const emailRegex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
+ if (!emailRegex.test(email)) {
+ showMessage('Please enter a valid email address', 'error');
+ return;
+ }
+
+ try {
+ // Show loading state
+ const submitBtn = resetRequestForm.querySelector('button[type="submit"]');
+ const originalBtnText = submitBtn.innerHTML;
+ submitBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Sending Request...';
+ submitBtn.disabled = true;
+
+ // Make API request
+ const response = await fetch('/api/auth/password/reset-request', {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json'
+ },
+ body: JSON.stringify({
+ email
+ })
+ });
+
+ const data = await response.json();
+
+ if (!response.ok) {
+ throw new Error(data.message || 'Password reset request failed');
+ }
+
+ // Show success message
+ showMessage('Password reset instructions have been sent to your email. Please check your inbox.', 'success');
+
+ // Clear form
+ resetRequestForm.reset();
+
+ } catch (error) {
+ console.error('Password reset request error:', error);
+ showMessage(error.message || 'Password reset request failed. Please try again.', 'error');
+ } finally {
+ // Reset button
+ submitBtn.innerHTML = originalBtnText;
+ submitBtn.disabled = false;
+ }
+ });
+
+ function showMessage(message, type) {
+ authMessage.textContent = message;
+ authMessage.className = 'auth-message';
+ authMessage.classList.add(type);
+ authMessage.style.display = 'block';
+ }
+
+ // Check for dark mode preference
+ const darkModeEnabled = localStorage.getItem('darkMode') === 'enabled';
+ if (darkModeEnabled) {
+ document.body.classList.add('dark-mode');
+ }
+ });
+
+ // Theme initialization
+ function setTheme(isDark) {
+ document.documentElement.setAttribute('data-theme', isDark ? 'dark' : 'light');
+ }
+
+ function initializeTheme() {
+ // Check for saved theme preference
+ const savedTheme = localStorage.getItem('darkMode');
+
+ if (savedTheme !== null) {
+ // Use saved preference
+ setTheme(savedTheme === 'true');
+ } else {
+ // Use system preference as fallback
+ const prefersDarkMode = window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches;
+ setTheme(prefersDarkMode);
+ }
+ }
+
+ // Initialize theme when page loads
+ document.addEventListener('DOMContentLoaded', initializeTheme);
+ </script>
+</body>
+</html>
diff --git a/frontend/reset-password.html b/frontend/reset-password.html
new file mode 100644
index 0000000..6702e2a
--- /dev/null
+++ b/frontend/reset-password.html
@@ -0,0 +1,426 @@
+<!DOCTYPE html>
+<html lang="en">
+<head>
+ <meta charset="UTF-8">
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
+ <title>Set New Password - Warranty Tracker</title>
+ <link rel="stylesheet" href="style.css">
+ <!-- Font Awesome for icons -->
+ <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
+ <style>
+ .auth-container {
+ max-width: 400px;
+ margin: 50px auto;
+ padding: 30px;
+ background-color: var(--card-bg);
+ border-radius: 8px;
+ box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
+ }
+
+ .auth-title {
+ text-align: center;
+ margin-bottom: 30px;
+ color: var(--text-color);
+ }
+
+ .auth-form .form-group {
+ margin-bottom: 20px;
+ }
+
+ .auth-links {
+ margin-top: 20px;
+ text-align: center;
+ font-size: 0.9em;
+ }
+
+ .auth-links a {
+ color: var(--primary-color);
+ text-decoration: none;
+ margin: 0 10px;
+ }
+
+ .auth-links a:hover {
+ text-decoration: underline;
+ }
+
+ .auth-message {
+ margin-top: 20px;
+ padding: 10px;
+ border-radius: 4px;
+ text-align: center;
+ display: none;
+ }
+
+ .auth-message.error {
+ background-color: rgba(244, 67, 54, 0.1);
+ color: #f44336;
+ border: 1px solid rgba(244, 67, 54, 0.3);
+ }
+
+ .auth-message.success {
+ background-color: rgba(76, 175, 80, 0.1);
+ color: #4caf50;
+ border: 1px solid rgba(76, 175, 80, 0.3);
+ }
+
+ .btn-block {
+ width: 100%;
+ }
+
+ .auth-form .password-container {
+ position: relative;
+ }
+
+ .auth-form .password-toggle {
+ position: absolute;
+ right: 10px;
+ top: 50%;
+ transform: translateY(-50%);
+ background: none;
+ border: none;
+ color: var(--text-muted);
+ cursor: pointer;
+ }
+
+ .password-strength {
+ height: 5px;
+ margin-top: 5px;
+ border-radius: 2px;
+ transition: all 0.3s ease;
+ background-color: #e0e0e0;
+ }
+
+ .password-strength-text {
+ font-size: 0.8em;
+ margin-top: 5px;
+ text-align: right;
+ }
+
+ .strength-weak {
+ width: 25%;
+ background-color: #f44336;
+ }
+
+ .strength-medium {
+ width: 50%;
+ background-color: #ff9800;
+ }
+
+ .strength-strong {
+ width: 75%;
+ background-color: #2196f3;
+ }
+
+ .strength-very-strong {
+ width: 100%;
+ background-color: #4caf50;
+ }
+
+ .token-invalid {
+ text-align: center;
+ color: var(--text-color);
+ display: none;
+ }
+
+ .token-invalid i {
+ font-size: 48px;
+ color: #f44336;
+ margin-bottom: 20px;
+ }
+
+ .token-invalid h3 {
+ margin-bottom: 15px;
+ }
+ </style>
+</head>
+<body>
+ <!-- Header -->
+ <header>
+ <div class="container">
+ <div class="app-title">
+ <i class="fas fa-shield-alt"></i>
+ <h1>Warranty Tracker</h1>
+ </div>
+ </div>
+ </header>
+
+ <!-- Main Content -->
+ <div class="container">
+ <div class="auth-container">
+ <div id="resetForm">
+ <h2 class="auth-title">Set New Password</h2>
+
+ <div id="authMessage" class="auth-message"></div>
+
+ <form id="passwordResetForm" class="auth-form">
+ <div class="form-group">
+ <label for="password">New Password</label>
+ <div class="password-container">
+ <input type="password" id="password" name="password" class="form-control" required>
+ <button type="button" class="password-toggle" title="Show/Hide Password">
+ <i class="fas fa-eye"></i>
+ </button>
+ </div>
+ <div class="password-strength" id="passwordStrength"></div>
+ <div class="password-strength-text" id="passwordStrengthText"></div>
+ <small class="form-text text-muted">Password must be at least 8 characters and include uppercase, lowercase, and numbers.</small>
+ </div>
+
+ <div class="form-group">
+ <label for="confirmPassword">Confirm New Password</label>
+ <div class="password-container">
+ <input type="password" id="confirmPassword" name="confirmPassword" class="form-control" required>
+ <button type="button" class="password-toggle" title="Show/Hide Password">
+ <i class="fas fa-eye"></i>
+ </button>
+ </div>
+ </div>
+
+ <input type="hidden" id="token" name="token">
+
+ <button type="submit" class="btn btn-primary btn-block">
+ <i class="fas fa-lock"></i> Reset Password
+ </button>
+ </form>
+
+ <div class="auth-links">
+ <a href="login.html">Back to Login</a>
+ </div>
+ </div>
+
+ <div id="tokenInvalid" class="token-invalid">
+ <i class="fas fa-exclamation-circle"></i>
+ <h3>Invalid or Expired Link</h3>
+ <p>The password reset link you clicked is invalid or has expired.</p>
+ <a href="reset-password-request.html" class="btn btn-primary">Request New Reset Link</a>
+ </div>
+ </div>
+ </div>
+
+ <script>
+ document.addEventListener('DOMContentLoaded', function() {
+ // Check if user is already logged in
+ const token = localStorage.getItem('auth_token');
+ if (token) {
+ // Redirect to home page if already logged in
+ window.location.href = 'index.html';
+ return;
+ }
+
+ // Get token from URL
+ const urlParams = new URLSearchParams(window.location.search);
+ const resetToken = urlParams.get('token');
+
+ // If no token in URL, check if we have a development token
+ let tokenToUse = resetToken;
+ if (!tokenToUse) {
+ const devLink = localStorage.getItem('dev_reset_link');
+ if (devLink) {
+ const devParams = new URLSearchParams(devLink);
+ tokenToUse = devParams.get('token');
+ }
+ }
+
+ // If no token is available, show invalid token message
+ if (!tokenToUse) {
+ document.getElementById('resetForm').style.display = 'none';
+ document.getElementById('tokenInvalid').style.display = 'block';
+ return;
+ }
+
+ // Set token in hidden field
+ document.getElementById('token').value = tokenToUse;
+
+ // Verify token validity
+ verifyToken(tokenToUse);
+
+ // Toggle password visibility
+ const passwordToggles = document.querySelectorAll('.password-toggle');
+
+ passwordToggles.forEach(toggle => {
+ toggle.addEventListener('click', function() {
+ const passwordInput = this.parentElement.querySelector('input');
+ const type = passwordInput.getAttribute('type') === 'password' ? 'text' : 'password';
+ passwordInput.setAttribute('type', type);
+
+ // Toggle icon
+ const icon = this.querySelector('i');
+ icon.classList.toggle('fa-eye');
+ icon.classList.toggle('fa-eye-slash');
+ });
+ });
+
+ // Password strength checker
+ const passwordInput = document.getElementById('password');
+ const passwordStrength = document.getElementById('passwordStrength');
+ const passwordStrengthText = document.getElementById('passwordStrengthText');
+
+ passwordInput.addEventListener('input', function() {
+ const password = this.value;
+ let strength = 0;
+ let feedback = '';
+
+ if (password.length >= 8) strength += 1;
+ if (password.match(/[A-Z]/)) strength += 1;
+ if (password.match(/[a-z]/)) strength += 1;
+ if (password.match(/[0-9]/)) strength += 1;
+ if (password.match(/[^A-Za-z0-9]/)) strength += 1;
+
+ passwordStrength.className = 'password-strength';
+
+ if (password.length === 0) {
+ passwordStrength.style.width = '0';
+ passwordStrengthText.textContent = '';
+ } else if (strength < 2) {
+ passwordStrength.classList.add('strength-weak');
+ feedback = 'Weak';
+ } else if (strength < 3) {
+ passwordStrength.classList.add('strength-medium');
+ feedback = 'Medium';
+ } else if (strength < 5) {
+ passwordStrength.classList.add('strength-strong');
+ feedback = 'Strong';
+ } else {
+ passwordStrength.classList.add('strength-very-strong');
+ feedback = 'Very Strong';
+ }
+
+ passwordStrengthText.textContent = feedback;
+ });
+
+ // Handle form submission
+ const passwordResetForm = document.getElementById('passwordResetForm');
+ const authMessage = document.getElementById('authMessage');
+
+ passwordResetForm.addEventListener('submit', async function(e) {
+ e.preventDefault();
+
+ const password = document.getElementById('password').value;
+ const confirmPassword = document.getElementById('confirmPassword').value;
+ const token = document.getElementById('token').value;
+
+ // Basic validation
+ if (!password || !confirmPassword) {
+ showMessage('Please fill in all fields', 'error');
+ return;
+ }
+
+ if (password !== confirmPassword) {
+ showMessage('Passwords do not match', 'error');
+ return;
+ }
+
+ // Validate password strength
+ if (password.length < 8 || !password.match(/[A-Z]/) || !password.match(/[a-z]/) || !password.match(/[0-9]/)) {
+ showMessage('Password must be at least 8 characters and include uppercase, lowercase, and numbers', 'error');
+ return;
+ }
+
+ try {
+ // Show loading state
+ const submitBtn = passwordResetForm.querySelector('button[type="submit"]');
+ const originalBtnText = submitBtn.innerHTML;
+ submitBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Resetting Password...';
+ submitBtn.disabled = true;
+
+ // Make API request
+ const response = await fetch('/api/auth/password/reset', {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json'
+ },
+ body: JSON.stringify({
+ token,
+ password
+ })
+ });
+
+ const data = await response.json();
+
+ if (!response.ok) {
+ throw new Error(data.message || 'Password reset failed');
+ }
+
+ // Show success message
+ showMessage('Password reset successful! Redirecting to login...', 'success');
+
+ // Clear development token if it exists
+ localStorage.removeItem('dev_reset_link');
+
+ // Redirect to login page after a short delay
+ setTimeout(() => {
+ window.location.href = 'login.html';
+ }, 2000);
+
+ } catch (error) {
+ console.error('Password reset error:', error);
+ showMessage(error.message || 'Password reset failed. Please try again.', 'error');
+
+ // Reset button
+ submitBtn.innerHTML = originalBtnText;
+ submitBtn.disabled = false;
+ }
+ });
+
+ // Helper function to show messages
+ function showMessage(message, type) {
+ authMessage.textContent = message;
+ authMessage.className = 'auth-message';
+ authMessage.classList.add(type);
+ 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';
+ }
+ }
+
+ // Check for dark mode preference
+ const darkModeEnabled = localStorage.getItem('darkMode') === 'enabled';
+ if (darkModeEnabled) {
+ document.body.classList.add('dark-mode');
+ }
+ });
+
+ // Theme initialization
+ function setTheme(isDark) {
+ document.documentElement.setAttribute('data-theme', isDark ? 'dark' : 'light');
+ }
+
+ function initializeTheme() {
+ // Check for saved theme preference
+ const savedTheme = localStorage.getItem('darkMode');
+
+ if (savedTheme !== null) {
+ // Use saved preference
+ setTheme(savedTheme === 'true');
+ } else {
+ // Use system preference as fallback
+ const prefersDarkMode = window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches;
+ setTheme(prefersDarkMode);
+ }
+ }
+
+ // Initialize theme when page loads
+ document.addEventListener('DOMContentLoaded', initializeTheme);
+ </script>
+</body>
+</html>
diff --git a/frontend/script.js b/frontend/script.js
index 221f52d..0b0a5e4 100644
--- a/frontend/script.js
+++ b/frontend/script.js
@@ -49,17 +49,32 @@ function initializeTheme() {
// Initialize theme when page loads
initializeTheme();
-// Settings menu toggle
-settingsBtn.addEventListener('click', (e) => {
- e.stopPropagation();
- settingsMenu.classList.toggle('active');
-});
-
-// Close settings menu when clicking outside
-document.addEventListener('click', (e) => {
- if (!settingsMenu.contains(e.target) && !settingsBtn.contains(e.target)) {
- settingsMenu.classList.remove('active');
+// Initialize page
+document.addEventListener('DOMContentLoaded', () => {
+ // Ensure auth state is checked
+ if (window.auth && window.auth.checkAuthState) {
+ window.auth.checkAuthState();
+ }
+
+ // Initialize settings button
+ if (settingsBtn && settingsMenu) {
+ settingsBtn.addEventListener('click', (e) => {
+ e.stopPropagation();
+ settingsMenu.classList.toggle('active');
+ });
+
+ // Close settings menu when clicking outside
+ document.addEventListener('click', (e) => {
+ if (settingsMenu.classList.contains('active') &&
+ !settingsMenu.contains(e.target) &&
+ !settingsBtn.contains(e.target)) {
+ settingsMenu.classList.remove('active');
+ }
+ });
}
+
+ // Initialize other event listeners and functionality
+ // ... existing initialization code ...
});
// Dark mode toggle
@@ -77,19 +92,40 @@ serialNumbersContainer.addEventListener('click', (e) => {
});
function addSerialNumberInput(container = serialNumbersContainer) {
+ // Check if this is the first input or an additional one
+ const isFirstInput = container.querySelectorAll('.serial-number-input').length === 0;
+
const newInput = document.createElement('div');
newInput.className = 'serial-number-input';
- newInput.innerHTML = `
- <input type="text" name="serial_numbers[]" class="form-control" placeholder="Enter serial number">
- <button type="button" class="btn btn-sm btn-danger remove-serial-number">
- <i class="fas fa-minus"></i> Remove
- </button>
- `;
- // Add remove button functionality
- newInput.querySelector('.remove-serial-number').addEventListener('click', function() {
- this.parentElement.remove();
- });
+ if (isFirstInput) {
+ // First input should have both Add and Remove buttons
+ newInput.innerHTML = `
+ <input type="text" name="serial_numbers[]" class="form-control" placeholder="Enter serial number">
+ <button type="button" class="btn btn-sm btn-primary add-serial-number">
+ <i class="fas fa-plus"></i> Add Another
+ </button>
+ `;
+
+ // Add event listener for the Add button
+ newInput.querySelector('.add-serial-number').addEventListener('click', function(e) {
+ e.stopPropagation(); // Stop event from bubbling up to the container
+ addSerialNumberInput(container);
+ });
+ } else {
+ // Additional inputs should have only Remove button
+ newInput.innerHTML = `
+ <input type="text" name="serial_numbers[]" class="form-control" placeholder="Enter serial number">
+ <button type="button" class="btn btn-sm btn-danger remove-serial-number">
+ <i class="fas fa-minus"></i> Remove
+ </button>
+ `;
+
+ // Add remove button functionality
+ newInput.querySelector('.remove-serial-number').addEventListener('click', function() {
+ this.parentElement.remove();
+ });
+ }
container.appendChild(newInput);
}
@@ -109,8 +145,20 @@ const API_URL = '/api/warranties';
// Event Listeners
document.addEventListener('DOMContentLoaded', () => {
+ console.log('DOM fully loaded, initializing app...');
+
+ // Initialize the app
+ initializeTheme();
+
+ // Load warranties
loadWarranties();
+ // Initialize form tabs
+ initFormTabs();
+
+ // Initialize the form
+ resetForm();
+
// Close modals when clicking outside or on close button
document.querySelectorAll('.modal-backdrop, [data-dismiss="modal"]').forEach(element => {
element.addEventListener('click', (e) => {
@@ -119,67 +167,80 @@ document.addEventListener('DOMContentLoaded', () => {
}
});
});
-
+
// Prevent modal content clicks from closing the modal
document.querySelectorAll('.modal').forEach(modal => {
modal.addEventListener('click', (e) => {
e.stopPropagation();
});
});
-
- // Initialize form tabs
- initFormTabs();
// Filter event listeners
- searchInput.addEventListener('input', () => {
- currentFilters.search = searchInput.value.toLowerCase();
- applyFilters();
- });
+ if (searchInput) {
+ searchInput.addEventListener('input', () => {
+ currentFilters.search = searchInput.value.toLowerCase();
+ applyFilters();
+ });
+ }
- statusFilter.addEventListener('change', () => {
- currentFilters.status = statusFilter.value;
- applyFilters();
- });
+ if (statusFilter) {
+ statusFilter.addEventListener('change', () => {
+ currentFilters.status = statusFilter.value;
+ applyFilters();
+ });
+ }
- sortBySelect.addEventListener('change', () => {
- currentFilters.sort = sortBySelect.value;
- applyFilters();
- });
+ if (sortBySelect) {
+ sortBySelect.addEventListener('change', () => {
+ currentFilters.sort = sortBySelect.value;
+ applyFilters();
+ });
+ }
// View switcher event listeners
- gridViewBtn.addEventListener('click', () => switchView('grid'));
- listViewBtn.addEventListener('click', () => switchView('list'));
- tableViewBtn.addEventListener('click', () => switchView('table'));
+ if (gridViewBtn) gridViewBtn.addEventListener('click', () => switchView('grid'));
+ if (listViewBtn) listViewBtn.addEventListener('click', () => switchView('list'));
+ if (tableViewBtn) tableViewBtn.addEventListener('click', () => switchView('table'));
// Export button event listener
- exportBtn.addEventListener('click', exportWarranties);
+ if (exportBtn) exportBtn.addEventListener('click', exportWarranties);
+
+ // File input change event
+ if (fileInput) fileInput.addEventListener('change', (e) => updateFileName(e, 'invoice', 'fileName'));
+ if (manualInput) manualInput.addEventListener('change', (e) => updateFileName(e, 'manual', 'manualFileName'));
+
+ const editInvoice = document.getElementById('editInvoice');
+ if (editInvoice) {
+ editInvoice.addEventListener('change', () => {
+ updateFileName(null, 'editInvoice', 'editFileName');
+ });
+ }
+
+ const editManual = document.getElementById('editManual');
+ if (editManual) {
+ editManual.addEventListener('change', () => {
+ updateFileName(null, 'editManual', 'editManualFileName');
+ });
+ }
+
+ // Form submission
+ if (warrantyForm) warrantyForm.addEventListener('submit', addWarranty);
+
+ // Refresh button
+ if (refreshBtn) refreshBtn.addEventListener('click', loadWarranties);
+
+ // Save warranty changes
+ if (saveWarrantyBtn) saveWarrantyBtn.addEventListener('click', updateWarranty);
+
+ // Confirm delete button
+ if (confirmDeleteBtn) confirmDeleteBtn.addEventListener('click', deleteWarranty);
// Load saved view preference
loadViewPreference();
+
+ console.log('App initialization complete');
});
-// File input change event
-fileInput.addEventListener('change', (e) => updateFileName(e, 'invoice', 'fileName'));
-manualInput.addEventListener('change', (e) => updateFileName(e, 'manual', 'manualFileName'));
-document.getElementById('editInvoice').addEventListener('change', () => {
- updateFileName(null, 'editInvoice', 'editFileName');
-});
-document.getElementById('editManual').addEventListener('change', () => {
- updateFileName(null, 'editManual', 'editManualFileName');
-});
-
-// Form submission
-warrantyForm.addEventListener('submit', addWarranty);
-
-// Refresh button
-refreshBtn.addEventListener('click', loadWarranties);
-
-// Save warranty changes
-saveWarrantyBtn.addEventListener('click', updateWarranty);
-
-// Confirm delete button
-confirmDeleteBtn.addEventListener('click', deleteWarranty);
-
// Functions
function showLoading() {
loadingContainer.classList.add('active');
@@ -223,32 +284,147 @@ function updateFileName(event, inputId = 'invoice', outputId = 'fileName') {
}
}
-async function loadWarranties() {
- showLoading();
+// Helper function to process warranty data
+function processWarrantyData(warranty) {
+ console.log('Processing warranty data:', warranty);
+
+ // Create a copy of the warranty object to avoid modifying the original
+ const processedWarranty = { ...warranty };
+
+ // Ensure product_name exists
+ if (!processedWarranty.product_name) {
+ processedWarranty.product_name = 'Unnamed Product';
+ }
+
+ const today = new Date();
+
+ // Handle purchase date
+ let purchaseDate = null;
+ if (processedWarranty.purchase_date) {
+ purchaseDate = new Date(processedWarranty.purchase_date);
+ // Check if date is valid
+ if (isNaN(purchaseDate.getTime())) {
+ purchaseDate = null;
+ }
+ }
+ processedWarranty.purchaseDate = purchaseDate;
+
+ // Handle expiration date
+ let expirationDate = null;
+ if (processedWarranty.expiration_date) {
+ expirationDate = new Date(processedWarranty.expiration_date);
+ // Check if date is valid
+ if (isNaN(expirationDate.getTime())) {
+ expirationDate = null;
+ }
+ }
+ processedWarranty.expirationDate = expirationDate;
+
+ // Calculate days remaining only if expiration date is valid
+ let daysRemaining = null;
+ if (expirationDate && !isNaN(expirationDate.getTime())) {
+ daysRemaining = Math.floor((expirationDate - today) / (1000 * 60 * 60 * 24));
+ }
- // Add loading animation to refresh button
- refreshBtn.classList.add('loading');
+ let statusClass = 'active';
+ let statusText = 'Active';
+
+ if (daysRemaining === null) {
+ statusClass = 'unknown';
+ statusText = 'Unknown status';
+ } else if (daysRemaining < 0) {
+ statusClass = 'expired';
+ statusText = 'Expired';
+ } else if (daysRemaining < 30) {
+ statusClass = 'expiring';
+ statusText = `Expiring Soon (${daysRemaining} days)`;
+ } else {
+ statusText = `${daysRemaining} days remaining`;
+ }
+ // Add status to warranty object
+ processedWarranty.status = statusClass;
+ processedWarranty.daysRemaining = daysRemaining;
+ processedWarranty.statusText = statusText;
+
+ console.log('Processed warranty data result:', processedWarranty);
+ return processedWarranty;
+}
+
+// Function to process all warranties in the array
+function processAllWarranties() {
+ console.log('Processing all warranties in array...');
+ if (warranties && warranties.length > 0) {
+ warranties = warranties.map(warranty => processWarrantyData(warranty));
+ }
+ console.log('Processed warranties:', warranties);
+}
+
+async function loadWarranties() {
try {
- // Add cache-busting parameter to prevent browser caching
- const cacheBuster = `?_=${Date.now()}`;
- const response = await fetch(`${API_URL}${cacheBuster}`);
+ console.log('Loading warranties...');
+ showLoading();
+
+ // Use the full URL to avoid path issues
+ const apiUrl = window.location.origin + '/api/warranties';
+
+ // Check if auth is available and user is authenticated
+ if (!window.auth || !window.auth.isAuthenticated()) {
+ console.log('User not authenticated, showing empty state');
+ renderEmptyState('Please log in to view your warranties.');
+ hideLoading();
+ return;
+ }
+
+ // Get the auth token
+ const token = window.auth.getToken();
+ if (!token) {
+ console.log('No auth token available');
+ renderEmptyState('Authentication error. Please log in again.');
+ hideLoading();
+ return;
+ }
+
+ // Create request with auth header
+ const options = {
+ method: 'GET',
+ headers: {
+ 'Authorization': `Bearer ${token}`,
+ 'Content-Type': 'application/json'
+ }
+ };
+
+ console.log('Fetching warranties with auth token');
+ const response = await fetch(apiUrl, options);
if (!response.ok) {
- throw new Error('Failed to load warranties');
+ const errorData = await response.json().catch(() => ({ message: `HTTP error ${response.status}` }));
+ console.error('Error loading warranties:', response.status, errorData);
+ throw new Error(`Error loading warranties: ${errorData.message || response.status}`);
}
- warranties = await response.json();
- renderWarranties();
- showToast('Warranties refreshed successfully', 'success');
+ const data = await response.json();
+ console.log('Received warranties from server:', data);
+
+ // Process each warranty to calculate status and days remaining
+ warranties = data.map(warranty => {
+ return processWarrantyData(warranty);
+ });
+
+ console.log('Processed warranties:', warranties);
+
+ if (warranties.length === 0) {
+ console.log('No warranties found, showing empty state');
+ renderEmptyState('No warranties found. Add your first warranty using the form.');
+ } else {
+ console.log('Applying filters to display warranties');
+ applyFilters();
+ }
} catch (error) {
- showToast(error.message, 'error');
console.error('Error loading warranties:', error);
- renderEmptyState('Could not load warranties. Please try again.');
+ renderEmptyState('Error loading warranties. Please try again later.');
} finally {
hideLoading();
- // Remove loading animation from refresh button
- refreshBtn.classList.remove('loading');
}
}
@@ -262,10 +438,27 @@ function renderEmptyState(message = 'No warranties yet. Add your first warranty
`;
}
-function renderWarranties(filteredWarranties = null) {
- const warrantiesToRender = filteredWarranties || warranties;
+function formatDate(date) {
+ if (!date) return 'N/A';
+
+ // If date is already a Date object, use it directly
+ const dateObj = date instanceof Date ? date : new Date(date);
- if (warrantiesToRender.length === 0) {
+ // Check if date is valid
+ if (isNaN(dateObj.getTime())) {
+ return 'N/A';
+ }
+
+ return dateObj.toLocaleDateString('en-US', {
+ year: 'numeric',
+ month: 'short',
+ day: 'numeric'
+ });
+}
+
+async function renderWarranties(warrantiesToRender) {
+ console.log('renderWarranties called with:', warrantiesToRender);
+ if (!warrantiesToRender || warrantiesToRender.length === 0) {
renderEmptyState();
return;
}
@@ -280,11 +473,11 @@ function renderWarranties(filteredWarranties = null) {
case 'name':
return a.product_name.localeCompare(b.product_name);
case 'purchase':
- return new Date(b.purchase_date) - new Date(a.purchase_date);
+ return new Date(b.purchase_date || 0) - new Date(a.purchase_date || 0);
case 'expiration':
default:
- const dateA = new Date(a.expiration_date);
- const dateB = new Date(b.expiration_date);
+ const dateA = new Date(a.expiration_date || 0);
+ const dateB = new Date(b.expiration_date || 0);
const isExpiredA = dateA < today;
const isExpiredB = dateB < today;
@@ -297,27 +490,31 @@ function renderWarranties(filteredWarranties = null) {
}
});
+ console.log('Sorted warranties:', sortedWarranties);
+
+ // Update the container class based on current view
+ warrantiesList.className = `warranties-list ${currentView}-view`;
+
+ // Show/hide table header for table view
+ if (tableViewHeader) {
+ tableViewHeader.classList.toggle('visible', currentView === 'table');
+ }
+
+ // Update view buttons to reflect current view
+ if (gridViewBtn && listViewBtn && tableViewBtn) {
+ gridViewBtn.classList.toggle('active', currentView === 'grid');
+ listViewBtn.classList.toggle('active', currentView === 'list');
+ tableViewBtn.classList.toggle('active', currentView === 'table');
+ }
+
sortedWarranties.forEach(warranty => {
- const purchaseDate = new Date(warranty.purchase_date);
- const expirationDate = new Date(warranty.expiration_date);
- const daysRemaining = Math.floor((expirationDate - today) / (1000 * 60 * 60 * 24));
-
- let statusClass = 'active';
- let statusText = 'Active';
-
- if (daysRemaining < 0) {
- statusClass = 'expired';
- statusText = 'Expired';
- } else if (daysRemaining < 30) {
- statusClass = 'expiring';
- statusText = `Expiring Soon (${daysRemaining} days)`;
- } else {
- statusText = `${daysRemaining} days remaining`;
- }
+ // Use the pre-processed dates from the warranty object
+ const purchaseDate = warranty.purchaseDate;
+ const expirationDate = warranty.expirationDate;
- // Add status to warranty object for filtering
- warranty.status = statusClass;
- warranty.daysRemaining = daysRemaining;
+ // Use the pre-calculated status and days remaining from the warranty object
+ const statusClass = warranty.status || 'unknown';
+ const statusText = warranty.statusText || 'Unknown status';
// Make sure serial numbers array exists and is valid
const validSerialNumbers = Array.isArray(warranty.serial_numbers)
@@ -326,55 +523,152 @@ function renderWarranties(filteredWarranties = null) {
const cardElement = document.createElement('div');
cardElement.className = `warranty-card ${statusClass === 'expired' ? 'expired' : statusClass === 'expiring' ? 'expiring-soon' : 'active'}`;
- cardElement.innerHTML = `
- <div class="product-name-header">
- <h3 class="warranty-title">${warranty.product_name}</h3>
- <div class="warranty-actions">
- <button class="action-btn edit-btn" title="Edit" data-id="${warranty.id}">
- <i class="fas fa-edit"></i>
- </button>
- <button class="action-btn delete-btn" title="Delete" data-id="${warranty.id}">
- <i class="fas fa-trash"></i>
- </button>
+
+ // Create different HTML structure based on the current view
+ if (currentView === 'grid') {
+ // Grid view HTML structure
+ cardElement.innerHTML = `
+ <div class="product-name-header">
+ <h3 class="warranty-title">${warranty.product_name || 'Unnamed Product'}</h3>
+ <div class="warranty-actions">
+ <button class="action-btn edit-btn" title="Edit" data-id="${warranty.id}">
+ <i class="fas fa-edit"></i>
+ </button>
+ <button class="action-btn delete-btn" title="Delete" data-id="${warranty.id}">
+ <i class="fas fa-trash"></i>
+ </button>
+ </div>
+ </div>
+ <div class="warranty-content">
+ <div class="warranty-info">
+ <div>Purchased: <span>${formatDate(purchaseDate)}</span></div>
+ <div>Warranty: <span>${warranty.warranty_years !== undefined ? `${warranty.warranty_years} ${warranty.warranty_years === 1 ? 'year' : 'years'}` : 'N/A'}</span></div>
+ <div>Expires: <span>${formatDate(expirationDate)}</span></div>
+ ${warranty.purchase_price ? `<div>Price: <span>$${parseFloat(warranty.purchase_price).toFixed(2)}</span></div>` : ''}
+ ${validSerialNumbers.length > 0 ? `
+ <div class="serial-numbers">
+ <strong>Serial Numbers:</strong>
+ <ul>
+ ${validSerialNumbers.map(sn => `<li>${sn}</li>`).join('')}
+ </ul>
+ </div>
+ ` : ''}
+ </div>
+ </div>
+ <div class="warranty-status-row status-${statusClass}">
+ <span>${statusText}</span>
+ </div>
+ <div class="document-links-row">
+ ${warranty.product_url ? `
+ <a href="${warranty.product_url}" class="product-link" target="_blank">
+ <i class="fas fa-globe"></i> Product Website
+ </a>
+ ` : ''}
+ ${warranty.invoice_path ? `
+ <a href="${warranty.invoice_path}" class="invoice-link" target="_blank">
+ <i class="fas fa-file-invoice"></i> Invoice
+ </a>
+ ` : ''}
+ ${warranty.manual_path ? `
+ <a href="${warranty.manual_path}" class="manual-link" target="_blank">
+ <i class="fas fa-book"></i> Manual
+ </a>
+ ` : ''}
+ </div>
+ `;
+ } else if (currentView === 'list') {
+ // List view HTML structure
+ cardElement.innerHTML = `
+ <div class="product-name-header">
+ <h3 class="warranty-title">${warranty.product_name || 'Unnamed Product'}</h3>
+ <div class="warranty-actions">
+ <button class="action-btn edit-btn" title="Edit" data-id="${warranty.id}">
+ <i class="fas fa-edit"></i>
+ </button>
+ <button class="action-btn delete-btn" title="Delete" data-id="${warranty.id}">
+ <i class="fas fa-trash"></i>
+ </button>
+ </div>
+ </div>
+ <div class="warranty-content">
+ <div class="warranty-info">
+ <div>Purchased: <span>${formatDate(purchaseDate)}</span></div>
+ <div>Warranty: <span>${warranty.warranty_years !== undefined ? `${warranty.warranty_years} ${warranty.warranty_years === 1 ? 'year' : 'years'}` : 'N/A'}</span></div>
+ <div>Expires: <span>${formatDate(expirationDate)}</span></div>
+ ${warranty.purchase_price ? `<div>Price: <span>$${parseFloat(warranty.purchase_price).toFixed(2)}</span></div>` : ''}
+ ${validSerialNumbers.length > 0 ? `
+ <div class="serial-numbers">
+ <strong>Serial Numbers:</strong>
+ <ul>
+ ${validSerialNumbers.map(sn => `<li>${sn}</li>`).join('')}
+ </ul>
+ </div>
+ ` : ''}
+ </div>
+ </div>
+ <div class="warranty-status-row status-${statusClass}">
+ <span>${statusText}</span>
</div>
- </div>
- <div class="warranty-content">
- <div class="warranty-info">
- <div>Purchased: <span>${formatDate(purchaseDate)}</span></div>
- <div>Warranty: <span>${warranty.warranty_years} ${warranty.warranty_years > 1 ? 'years' : 'year'}</span></div>
- <div>Expires: <span>${formatDate(expirationDate)}</span></div>
- ${warranty.purchase_price ? `<div>Price: <span>$${parseFloat(warranty.purchase_price).toFixed(2)}</span></div>` : ''}
- ${validSerialNumbers.length > 0 ? `
- <div class="serial-numbers">
- <strong>Serial Numbers:</strong>
- <ul>
- ${validSerialNumbers.map(sn => `<li>${sn}</li>`).join('')}
- </ul>
- </div>
+ <div class="document-links-row">
+ ${warranty.product_url ? `
+ <a href="${warranty.product_url}" class="product-link" target="_blank">
+ <i class="fas fa-globe"></i> Product Website
+ </a>
+ ` : ''}
+ ${warranty.invoice_path ? `
+ <a href="${warranty.invoice_path}" class="invoice-link" target="_blank">
+ <i class="fas fa-file-invoice"></i> Invoice
+ </a>
+ ` : ''}
+ ${warranty.manual_path ? `
+ <a href="${warranty.manual_path}" class="manual-link" target="_blank">
+ <i class="fas fa-book"></i> Manual
+ </a>
` : ''}
</div>
- </div>
- <div class="warranty-status-row status-${statusClass}">
- <span>${statusText}</span>
- </div>
- <div class="document-links-row">
- ${warranty.product_url ? `
- <a href="${warranty.product_url}" class="product-link" target="_blank">
- <i class="fas fa-globe"></i> Product Website
- </a>
- ` : ''}
- ${warranty.invoice_path ? `
- <a href="${warranty.invoice_path}" class="invoice-link" target="_blank">
- <i class="fas fa-file-invoice"></i> Invoice
- </a>
- ` : ''}
- ${warranty.manual_path ? `
- <a href="${warranty.manual_path}" class="manual-link" target="_blank">
- <i class="fas fa-book"></i> Manual
- </a>
- ` : ''}
- </div>
- `;
+ `;
+ } else if (currentView === 'table') {
+ // Table view HTML structure
+ cardElement.innerHTML = `
+ <div class="product-name-header">
+ <h3 class="warranty-title">${warranty.product_name || 'Unnamed Product'}</h3>
+ <div class="warranty-actions">
+ <button class="action-btn edit-btn" title="Edit" data-id="${warranty.id}">
+ <i class="fas fa-edit"></i>
+ </button>
+ <button class="action-btn delete-btn" title="Delete" data-id="${warranty.id}">
+ <i class="fas fa-trash"></i>
+ </button>
+ </div>
+ </div>
+ <div class="warranty-content">
+ <div class="warranty-info">
+ <div>Purchased: <span>${formatDate(purchaseDate)}</span></div>
+ <div>Expires: <span>${formatDate(expirationDate)}</span></div>
+ </div>
+ </div>
+ <div class="warranty-status-row status-${statusClass}">
+ <span>${statusText}</span>
+ </div>
+ <div class="document-links-row">
+ ${warranty.product_url ? `
+ <a href="${warranty.product_url}" class="product-link" target="_blank">
+ <i class="fas fa-globe"></i>
+ </a>
+ ` : ''}
+ ${warranty.invoice_path ? `
+ <a href="${warranty.invoice_path}" class="invoice-link" target="_blank">
+ <i class="fas fa-file-invoice"></i>
+ </a>
+ ` : ''}
+ ${warranty.manual_path ? `
+ <a href="${warranty.manual_path}" class="manual-link" target="_blank">
+ <i class="fas fa-book"></i>
+ </a>
+ ` : ''}
+ </div>
+ `;
+ }
// Add event listeners
warrantiesList.appendChild(cardElement);
@@ -406,84 +700,6 @@ function filterWarranties() {
renderWarranties(filtered);
}
-function formatDate(date) {
- return new Date(date).toLocaleDateString('en-US', {
- year: 'numeric',
- month: 'short',
- day: 'numeric'
- });
-}
-
-async function addWarranty(event) {
- event.preventDefault();
- showLoading();
-
- const formData = new FormData(warrantyForm);
-
- // Get all serial numbers and add them to formData
- const serialNumbers = [];
- document.querySelectorAll('input[name="serial_numbers[]"]').forEach(input => {
- if (input.value.trim()) {
- serialNumbers.push(input.value.trim());
- }
- });
- formData.delete('serial_numbers[]'); // Remove the original array
- if (serialNumbers.length > 0) {
- serialNumbers.forEach(sn => formData.append('serial_numbers', sn));
- }
-
- try {
- const response = await fetch(API_URL, {
- method: 'POST',
- body: formData
- });
-
- if (!response.ok) {
- const error = await response.json();
- throw new Error(error.error || 'Failed to add warranty');
- }
-
- const result = await response.json();
- showToast('Warranty added successfully!', 'success');
-
- // Reset form
- warrantyForm.reset();
- fileName.textContent = '';
- manualFileName.textContent = '';
-
- // Completely reset serial number inputs
- serialNumbersContainer.innerHTML = '';
-
- // Create a fresh initial serial number input
- const initialInput = document.createElement('div');
- initialInput.className = 'serial-number-input';
- initialInput.innerHTML = `
- <input type="text" name="serial_numbers[]" class="form-control" placeholder="Enter serial number">
- <button type="button" class="btn btn-sm btn-secondary add-serial-number">
- <i class="fas fa-plus"></i> Add Another
- </button>
- `;
-
- // Add the event listener for the "Add Another" button
- initialInput.querySelector('.add-serial-number').addEventListener('click', function() {
- addSerialNumberInput();
- });
-
- serialNumbersContainer.appendChild(initialInput);
-
- // Switch back to the first tab
- switchToTab(0);
-
- // Reload warranties
- loadWarranties();
- } catch (error) {
- showToast(error.message, 'error');
- console.error('Error adding warranty:', error);
- } finally {
- hideLoading();
- }
-}
-
function openEditModal(warranty) {
currentWarrantyId = warranty.id;
@@ -498,79 +714,89 @@ function openEditModal(warranty) {
const editSerialNumbersContainer = document.getElementById('editSerialNumbersContainer');
editSerialNumbersContainer.innerHTML = '';
- // Make sure serial numbers array exists and is valid
- const validSerialNumbers = Array.isArray(warranty.serial_numbers)
+ // Add event listener for adding new serial number inputs in edit modal
+ editSerialNumbersContainer.addEventListener('click', (e) => {
+ if (e.target.closest('.add-serial-number')) {
+ addSerialNumberInput(editSerialNumbersContainer);
+ }
+ });
+
+ const validSerialNumbers = Array.isArray(warranty.serial_numbers)
? warranty.serial_numbers.filter(sn => sn && typeof sn === 'string' && sn.trim() !== '')
: [];
+
+ if (validSerialNumbers.length === 0) {
+ // Add a single empty input if there are no serial numbers
+ addSerialNumberInput(editSerialNumbersContainer);
+ } else {
+ // Add the first serial number with an "Add Another" button
+ const firstInput = document.createElement('div');
+ firstInput.className = 'serial-number-input';
+ firstInput.innerHTML = `
+ <input type="text" name="serial_numbers[]" class="form-control" placeholder="Enter serial number" value="${validSerialNumbers[0]}">
+ <button type="button" class="btn btn-sm btn-primary add-serial-number">
+ <i class="fas fa-plus"></i> Add Another
+ </button>
+ `;
- // Add initial serial number input
- const initialInput = document.createElement('div');
- initialInput.className = 'serial-number-input';
- initialInput.innerHTML = `
- <input type="text" name="serial_numbers[]" class="form-control" placeholder="Enter serial number">
- <button type="button" class="btn btn-sm btn-secondary add-serial-number">
- <i class="fas fa-plus"></i> Add Another
- </button>
- `;
- editSerialNumbersContainer.appendChild(initialInput);
-
- // Add existing serial numbers
- if (validSerialNumbers.length > 0) {
- validSerialNumbers.forEach((serialNumber, index) => {
- if (index === 0) {
- // Use the first input we already created
- editSerialNumbersContainer.querySelector('input').value = serialNumber;
- } else {
- const newInput = document.createElement('div');
- newInput.className = 'serial-number-input';
- newInput.innerHTML = `
- <input type="text" name="serial_numbers[]" class="form-control" placeholder="Enter serial number" value="${serialNumber}">
- <button type="button" class="btn btn-sm btn-danger remove-serial-number">
- <i class="fas fa-minus"></i> Remove
- </button>
- `;
- editSerialNumbersContainer.appendChild(newInput);
- }
+ // Add event listener for the Add button
+ firstInput.querySelector('.add-serial-number').addEventListener('click', function(e) {
+ e.stopPropagation(); // Stop event from bubbling up
+ addSerialNumberInput(editSerialNumbersContainer);
});
+
+ editSerialNumbersContainer.appendChild(firstInput);
+
+ // Add the rest of the serial numbers with "Remove" buttons
+ for (let i = 1; i < validSerialNumbers.length; i++) {
+ const newInput = document.createElement('div');
+ newInput.className = 'serial-number-input';
+ newInput.innerHTML = `
+ <input type="text" name="serial_numbers[]" class="form-control" placeholder="Enter serial number" value="${validSerialNumbers[i]}">
+ <button type="button" class="btn btn-sm btn-danger remove-serial-number">
+ <i class="fas fa-minus"></i> Remove
+ </button>
+ `;
+
+ // Add remove button functionality
+ newInput.querySelector('.remove-serial-number').addEventListener('click', function() {
+ this.parentElement.remove();
+ });
+
+ editSerialNumbersContainer.appendChild(newInput);
+ }
}
- // Add event listeners for the serial number buttons
- editSerialNumbersContainer.querySelectorAll('.add-serial-number').forEach(btn => {
- btn.addEventListener('click', () => addSerialNumberInput(editSerialNumbersContainer));
- });
-
- editSerialNumbersContainer.querySelectorAll('.remove-serial-number').forEach(btn => {
- btn.addEventListener('click', function() {
- this.parentElement.remove();
- });
- });
-
// Show current invoice if exists
const currentInvoiceElement = document.getElementById('currentInvoice');
- if (warranty.invoice_path) {
- currentInvoiceElement.innerHTML = `
- <span class="text-success">
- <i class="fas fa-check-circle"></i> Current invoice:
- <a href="${warranty.invoice_path}" target="_blank">View</a>
- (Upload a new file to replace)
- </span>
- `;
- } else {
- currentInvoiceElement.innerHTML = '<span>No invoice uploaded</span>';
+ if (currentInvoiceElement) {
+ if (warranty.invoice_path) {
+ currentInvoiceElement.innerHTML = `
+ <span class="text-success">
+ <i class="fas fa-check-circle"></i> Current invoice:
+ <a href="${warranty.invoice_path}" target="_blank">View</a>
+ (Upload a new file to replace)
+ </span>
+ `;
+ } else {
+ currentInvoiceElement.innerHTML = '<span>No invoice uploaded</span>';
+ }
}
// Show current manual if exists
const currentManualElement = document.getElementById('currentManual');
- if (warranty.manual_path) {
- currentManualElement.innerHTML = `
- <span class="text-success">
- <i class="fas fa-check-circle"></i> Current manual:
- <a href="${warranty.manual_path}" target="_blank">View</a>
- (Upload a new file to replace)
- </span>
- `;
- } else {
- currentManualElement.innerHTML = '<span>No manual uploaded</span>';
+ if (currentManualElement) {
+ if (warranty.manual_path) {
+ currentManualElement.innerHTML = `
+ <span class="text-success">
+ <i class="fas fa-check-circle"></i> Current manual:
+ <a href="${warranty.manual_path}" target="_blank">View</a>
+ (Upload a new file to replace)
+ </span>
+ `;
+ } else {
+ currentManualElement.innerHTML = '<span>No manual uploaded</span>';
+ }
}
// Reset file input display
@@ -592,13 +818,25 @@ function closeModals() {
}
async function updateWarranty() {
- if (!currentWarrantyId) return;
+ // Check if user is authenticated
+ if (window.auth && !window.auth.isAuthenticated()) {
+ showToast('Please login to update warranties', 'warning');
+ closeModals();
+ setTimeout(() => {
+ window.location.href = 'login.html';
+ }, 1500);
+ return;
+ }
- showLoading();
+ if (!currentWarrantyId) {
+ showToast('No warranty selected for update', 'error');
+ return;
+ }
+ // Create FormData object
const formData = new FormData(editWarrantyForm);
- // Get all serial numbers and add them to formData
+ // Get all serial numbers
const serialNumbers = [];
document.querySelectorAll('#editSerialNumbersContainer input[name="serial_numbers[]"]').forEach(input => {
if (input.value.trim()) {
@@ -606,55 +844,122 @@ async function updateWarranty() {
}
});
- // Remove the original array and add clean values
+ // Remove default serial numbers entry and add the collected ones
formData.delete('serial_numbers[]');
- if (serialNumbers.length > 0) {
- serialNumbers.forEach(sn => formData.append('serial_numbers', sn));
- }
+ serialNumbers.forEach(sn => {
+ formData.append('serial_numbers', sn);
+ });
try {
- const response = await fetch(`${API_URL}/${currentWarrantyId}`, {
+ showLoading();
+
+ // Get the auth token
+ const token = window.auth.getToken();
+ if (!token) {
+ showToast('Authentication error. Please log in again.', 'error');
+ hideLoading();
+ closeModals();
+ return;
+ }
+
+ // Create request with auth header
+ const options = {
method: 'PUT',
- body: formData
- });
+ body: formData,
+ headers: {
+ 'Authorization': `Bearer ${token}`
+ }
+ };
+
+ // Use the full URL to avoid path issues
+ const apiUrl = `${window.location.origin}/api/warranties/${currentWarrantyId}`;
+
+ console.log('Updating warranty with ID:', currentWarrantyId);
+ const response = await fetch(apiUrl, options);
if (!response.ok) {
- const error = await response.json();
- throw new Error(error.error || 'Failed to update warranty');
+ const errorData = await response.json().catch(() => ({ message: `HTTP error ${response.status}` }));
+ throw new Error(errorData.message || `Error updating warranty: ${response.status}`);
}
- showToast('Warranty updated successfully!', 'success');
+ const result = await response.json();
+ console.log('Received update warranty result:', result);
+
+ // Reload all warranties to get the complete data
+ await loadWarranties();
+
+ // Close modal
closeModals();
- loadWarranties();
+
+ // Show success message
+ showToast('Warranty updated successfully!', 'success');
} catch (error) {
- showToast(error.message, 'error');
console.error('Error updating warranty:', error);
+ showToast(error.message || 'Error updating warranty. Please try again.', 'error');
} finally {
hideLoading();
}
}
async function deleteWarranty() {
- if (!currentWarrantyId) return;
+ // Check if user is authenticated
+ if (window.auth && !window.auth.isAuthenticated()) {
+ showToast('Please login to delete warranties', 'warning');
+ closeModals();
+ setTimeout(() => {
+ window.location.href = 'login.html';
+ }, 1500);
+ return;
+ }
- showLoading();
+ if (!currentWarrantyId) {
+ showToast('No warranty selected for deletion', 'error');
+ return;
+ }
try {
- const response = await fetch(`${API_URL}/${currentWarrantyId}`, {
- method: 'DELETE'
- });
+ showLoading();
+
+ // Get the auth token
+ const token = window.auth.getToken();
+ if (!token) {
+ showToast('Authentication error. Please log in again.', 'error');
+ hideLoading();
+ closeModals();
+ return;
+ }
+
+ // Create request with auth header
+ const options = {
+ method: 'DELETE',
+ headers: {
+ 'Authorization': `Bearer ${token}`,
+ 'Content-Type': 'application/json'
+ }
+ };
+
+ // Use the full URL to avoid path issues
+ const apiUrl = `${window.location.origin}/api/warranties/${currentWarrantyId}`;
+
+ console.log('Deleting warranty with ID:', currentWarrantyId);
+ const response = await fetch(apiUrl, options);
if (!response.ok) {
- const error = await response.json();
- throw new Error(error.error || 'Failed to delete warranty');
+ const errorData = await response.json().catch(() => ({ message: `HTTP error ${response.status}` }));
+ throw new Error(errorData.message || `Error deleting warranty: ${response.status}`);
}
- showToast('Warranty deleted successfully!', 'success');
+ // Reload all warranties to get the updated list
+ await loadWarranties();
+
+ // Close the modal
closeModals();
- loadWarranties();
+
+ // Show success message
+ showToast('Warranty deleted successfully!', 'success');
} catch (error) {
- showToast(error.message, 'error');
console.error('Error deleting warranty:', error);
+ showToast(error.message || 'Error deleting warranty. Please try again.', 'error');
} finally {
hideLoading();
}
@@ -877,42 +1182,130 @@ document.addEventListener('input', (e) => {
}
});
-function applyFilters() {
- let filteredWarranties = [...warranties];
+// Function to reset the form and initialize serial number inputs
+function resetForm() {
+ // Reset the form
+ warrantyForm.reset();
- // Apply search filter
- if (currentFilters.search) {
- filteredWarranties = filteredWarranties.filter(warranty =>
- warranty.product_name.toLowerCase().includes(currentFilters.search)
- );
+ // Reset serial numbers container
+ serialNumbersContainer.innerHTML = '';
+
+ // Add the first serial number input
+ addSerialNumberInput();
+
+ // Reset form tabs
+ currentTabIndex = 0;
+ switchToTab(0);
+
+ // Clear any file input displays
+ fileName.textContent = '';
+ manualFileName.textContent = '';
+}
+
+async function addWarranty(event) {
+ event.preventDefault();
+
+ // Check authentication first
+ if (!window.auth || !window.auth.isAuthenticated()) {
+ showToast('Please log in to add warranties', 'error');
+ return;
}
- // Apply status filter
- if (currentFilters.status !== 'all') {
- filteredWarranties = filteredWarranties.filter(warranty => {
- // We need to calculate the status if it's not already set
- if (!warranty.status) {
- const today = new Date();
- const expirationDate = new Date(warranty.expiration_date);
- const daysRemaining = Math.floor((expirationDate - today) / (1000 * 60 * 60 * 24));
-
- if (daysRemaining < 0) {
- warranty.status = 'expired';
- } else if (daysRemaining < 30) {
- warranty.status = 'expiring';
- } else {
- warranty.status = 'active';
- }
+ // Validate the current tab
+ if (!validateTab(currentTabIndex)) {
+ return;
+ }
+
+ try {
+ showLoading();
+
+ // Create FormData object
+ const formData = new FormData(warrantyForm);
+
+ // Add serial numbers
+ const serialNumberInputs = document.querySelectorAll('input[name="serial_numbers[]"]');
+ formData.delete('serial_numbers[]'); // Remove the default entries
+ serialNumberInputs.forEach(input => {
+ if (input.value.trim()) {
+ formData.append('serial_numbers', input.value.trim());
}
-
- return warranty.status === currentFilters.status;
});
+
+ // Get the auth token
+ const token = window.auth.getToken();
+ if (!token) {
+ showToast('Authentication error. Please log in again.', 'error');
+ hideLoading();
+ return;
+ }
+
+ // Create request with auth header
+ const options = {
+ method: 'POST',
+ body: formData,
+ headers: {
+ 'Authorization': `Bearer ${token}`
+ }
+ };
+
+ // Use the full URL to avoid path issues
+ const apiUrl = window.location.origin + '/api/warranties';
+
+ console.log('Sending warranty data to server...');
+ const response = await fetch(apiUrl, options);
+
+ if (!response.ok) {
+ const errorData = await response.json().catch(() => ({ message: `HTTP error ${response.status}` }));
+ throw new Error(errorData.message || `Error adding warranty: ${response.status}`);
+ }
+
+ const result = await response.json();
+ console.log('Received add warranty result:', result);
+
+ // The server only returns the ID, so we need to fetch the complete warranty data
+ if (result.id) {
+ console.log('Fetching complete warranty data for ID:', result.id);
+
+ // Reload all warranties to get the complete data
+ await loadWarranties();
+
+ // Reset the form and initialize serial number inputs
+ resetForm();
+
+ // Show success message
+ showToast('Warranty added successfully!', 'success');
+ } else {
+ throw new Error('Failed to get warranty ID from server response');
+ }
+ } catch (error) {
+ console.error('Error adding warranty:', error);
+ showToast(error.message || 'Error adding warranty. Please try again.', 'error');
+ } finally {
+ hideLoading();
}
+}
+
+function applyFilters() {
+ console.log('applyFilters called with warranties:', warranties);
+ const filtered = warranties.filter(warranty => {
+ // Status filter
+ if (currentFilters.status !== 'all' && warranty.status !== currentFilters.status) {
+ return false;
+ }
+
+ // Search filter
+ if (currentFilters.search && !warranty.product_name.toLowerCase().includes(currentFilters.search.toLowerCase())) {
+ return false;
+ }
+
+ return true;
+ });
- renderWarranties(filteredWarranties);
+ console.log('Filtered warranties:', filtered);
+ renderWarranties(filtered);
}
-function exportWarranties() {
+async function exportWarranties() {
// Get filtered warranties
let warrantiesToExport = [...warranties];
@@ -984,6 +1377,11 @@ function exportWarranties() {
// Function to switch between views
function switchView(viewType) {
+ console.log('Switching view to:', viewType);
+
+ // Process all warranties to ensure consistency
+ processAllWarranties();
+
// Update current view
currentView = viewType;
@@ -1001,7 +1399,8 @@ function switchView(viewType) {
}
// Re-render warranties with the new view
- renderWarranties();
+ console.log('Applying filters after switching view...');
+ applyFilters();
// Save view preference to localStorage
localStorage.setItem('warrantyView', viewType);
@@ -1009,8 +1408,15 @@ function switchView(viewType) {
// Load saved view preference
function loadViewPreference() {
+ // First check for warrantyView (direct view selection)
const savedView = localStorage.getItem('warrantyView');
- if (savedView) {
- switchView(savedView);
+ // If not found, check for defaultView (from settings)
+ const defaultView = localStorage.getItem('defaultView');
+
+ // Use warrantyView if available, otherwise use defaultView, or fall back to grid
+ const viewToUse = savedView || defaultView || 'grid';
+
+ if (viewToUse) {
+ switchView(viewToUse);
}
}
\ No newline at end of file
diff --git a/frontend/settings-new.html b/frontend/settings-new.html
new file mode 100644
index 0000000..07c3dfd
--- /dev/null
+++ b/frontend/settings-new.html
@@ -0,0 +1,736 @@
+<!DOCTYPE html>
+<html lang="en">
+<head>
+ <!-- Authentication redirect script -->
+ <script src="auth-redirect.js" data-protected="true"></script>
+
+ <!-- Include authentication script first to handle login state immediately -->
+ <script src="include-auth-new.js"></script>
+
+ <meta charset="UTF-8">
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
+ <title>Settings - Warranty Tracker</title>
+ <!-- Load the main site styles first -->
+ <link rel="stylesheet" href="style.css">
+ <!-- Font Awesome for icons -->
+ <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
+ <!-- Then load settings-specific styles -->
+ <link rel="stylesheet" href="settings-styles.css">
+ <!-- Load header fix styles last to override any conflicting styles -->
+ <link rel="stylesheet" href="header-fix.css">
+ <!-- Load fix for auth buttons -->
+ <script src="fix-auth-buttons-loader.js"></script>
+ <style>
+ /* User menu styles - copied from index.html to ensure consistency */
+ .user-menu {
+ position: relative;
+ margin-left: 15px;
+ }
+
+ .user-btn {
+ background: none;
+ border: none;
+ color: var(--text-color);
+ cursor: pointer;
+ display: flex;
+ align-items: center;
+ font-size: 0.9rem;
+ padding: 5px 10px;
+ border-radius: 20px;
+ transition: background-color 0.3s;
+ }
+
+ .user-btn:hover {
+ background-color: rgba(0, 0, 0, 0.05);
+ }
+
+ .dark-mode .user-btn:hover {
+ background-color: rgba(255, 255, 255, 0.1);
+ }
+
+ .user-btn i {
+ margin-right: 5px;
+ }
+
+ .user-menu-dropdown {
+ position: absolute;
+ top: 100%;
+ right: 0;
+ background-color: var(--card-bg);
+ border-radius: 8px;
+ box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
+ width: 200px;
+ z-index: 1000;
+ display: none;
+ padding: 10px 0;
+ margin-top: 5px;
+ }
+
+ .user-menu-dropdown.active {
+ display: block;
+ }
+
+ .user-info {
+ padding: 10px 15px;
+ border-bottom: 1px solid var(--border-color);
+ margin-bottom: 5px;
+ }
+
+ .user-name {
+ font-weight: bold;
+ margin-bottom: 5px;
+ }
+
+ .user-email {
+ font-size: 0.8rem;
+ color: var(--text-muted);
+ word-break: break-all;
+ }
+
+ .user-menu-item {
+ padding: 8px 15px;
+ cursor: pointer;
+ transition: background-color 0.3s;
+ display: flex;
+ align-items: center;
+ }
+
+ .user-menu-item:hover {
+ background-color: var(--hover-bg);
+ }
+
+ .user-menu-item i {
+ margin-right: 10px;
+ width: 16px;
+ text-align: center;
+ }
+
+ .auth-buttons {
+ display: flex;
+ gap: 10px;
+ margin-left: 15px;
+ }
+
+ .auth-btn {
+ padding: 5px 15px;
+ border-radius: 20px;
+ font-size: 0.9rem;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ cursor: pointer;
+ transition: all 0.3s ease;
+ }
+
+ .auth-btn i {
+ margin-right: 5px;
+ }
+
+ .login-btn {
+ background-color: transparent;
+ border: 1px solid var(--primary-color);
+ color: var(--primary-color);
+ }
+
+ .login-btn:hover {
+ background-color: rgba(var(--primary-rgb), 0.1);
+ }
+
+ .register-btn {
+ background-color: var(--primary-color);
+ border: 1px solid var(--primary-color);
+ color: white;
+ }
+
+ .register-btn:hover {
+ background-color: var(--primary-dark);
+ }
+
+ /* Admin section styles */
+ .admin-section {
+ margin-top: 30px;
+ border-top: 1px solid var(--border-color);
+ padding-top: 30px;
+ }
+
+ .admin-section h2 {
+ color: var(--primary-color);
+ margin-bottom: 20px;
+ }
+
+ .admin-controls {
+ margin-bottom: 15px;
+ display: flex;
+ justify-content: flex-end;
+ }
+
+ .table {
+ width: 100%;
+ border-collapse: collapse;
+ margin-bottom: 20px;
+ color: var(--text-color);
+ }
+
+ .table th {
+ background-color: var(--card-header-bg);
+ padding: 10px;
+ text-align: left;
+ font-weight: bold;
+ border-bottom: 2px solid var(--border-color);
+ }
+
+ .table td {
+ padding: 10px;
+ border-bottom: 1px solid var(--border-color);
+ vertical-align: middle;
+ }
+
+ .table tr:hover {
+ background-color: var(--hover-bg);
+ }
+
+ .table-responsive {
+ overflow-x: auto;
+ margin-bottom: 20px;
+ }
+
+ .badge {
+ display: inline-block;
+ padding: 4px 8px;
+ border-radius: 4px;
+ font-size: 0.75rem;
+ font-weight: bold;
+ text-align: center;
+ white-space: nowrap;
+ }
+
+ .badge-success {
+ background-color: #28a745;
+ color: white;
+ }
+
+ .badge-danger {
+ background-color: #dc3545;
+ color: white;
+ }
+
+ .badge-primary {
+ background-color: var(--primary-color);
+ color: white;
+ }
+
+ .badge-secondary {
+ background-color: #6c757d;
+ color: white;
+ }
+
+ .btn-sm {
+ padding: 0.25rem 0.5rem;
+ font-size: 0.875rem;
+ line-height: 1.5;
+ border-radius: 0.2rem;
+ }
+
+ .mr-2 {
+ margin-right: 0.5rem;
+ }
+
+ .font-weight-bold {
+ font-weight: bold;
+ }
+ </style>
+ <!-- Immediate authentication check script -->
+ <script>
+ // Check if user is logged in immediately to hide buttons
+ (function() {
+ if (localStorage.getItem('auth_token')) {
+ // Hide login and register buttons immediately
+ document.addEventListener('DOMContentLoaded', function() {
+ console.log('Inline script: User is logged in, hiding login/register buttons');
+
+ // Hide auth container
+ var authContainer = document.getElementById('authContainer');
+ if (authContainer) {
+ authContainer.style.display = 'none';
+ authContainer.style.visibility = 'hidden';
+ }
+
+ // Show user menu
+ var userMenu = document.getElementById('userMenu');
+ if (userMenu) {
+ userMenu.style.display = 'block';
+ userMenu.style.visibility = 'visible';
+ }
+
+ // Update user info if possible
+ try {
+ var userInfo = JSON.parse(localStorage.getItem('user_info'));
+ if (userInfo) {
+ var displayName = userInfo.first_name || userInfo.username || 'User';
+ var userDisplayName = document.getElementById('userDisplayName');
+ if (userDisplayName) {
+ userDisplayName.textContent = displayName;
+ }
+
+ var userName = document.getElementById('userName');
+ if (userName) {
+ userName.textContent = (userInfo.first_name || '') + ' ' + (userInfo.last_name || '');
+ if (!userName.textContent.trim()) userName.textContent = userInfo.username || 'User';
+ }
+
+ var userEmail = document.getElementById('userEmail');
+ if (userEmail && userInfo.email) {
+ userEmail.textContent = userInfo.email;
+ }
+ }
+ } catch (e) {
+ console.error('Error updating user info:', e);
+ }
+ }, { once: true });
+ }
+ })();
+ </script>
+</head>
+<body>
+ <!-- Header -->
+ <header>
+ <div class="container">
+ <div class="app-title">
+ <i class="fas fa-shield-alt"></i>
+ <h1>Warranty Tracker</h1>
+ </div>
+ <div class="nav-links">
+ <a href="index.html" class="nav-link">
+ <i class="fas fa-home"></i> Home
+ </a>
+ <a href="status.html" class="nav-link">
+ <i class="fas fa-chart-pie"></i> Status
+ </a>
+ </div>
+ <div id="authContainer" class="auth-buttons">
+ <a href="login.html" class="auth-btn login-btn">
+ <i class="fas fa-sign-in-alt"></i> Login
+ </a>
+ <a href="register.html" class="auth-btn register-btn">
+ <i class="fas fa-user-plus"></i> Register
+ </a>
+ </div>
+ <div id="userMenu" class="user-menu" style="display: none;">
+ <button id="userBtn" class="user-btn">
+ <i class="fas fa-user-circle"></i>
+ <span id="userDisplayName">User</span>
+ </button>
+ <div id="userMenuDropdown" class="user-menu-dropdown">
+ <div class="user-info">
+ <div id="userName" class="user-name">User Name</div>
+ <div id="userEmail" class="user-email">[email protected]</div>
+ </div>
+ <div class="user-menu-item">
+ <a href="settings-new.html" style="color: inherit; text-decoration: none; display: flex; align-items: center; width: 100%;">
+ <i class="fas fa-cog"></i> Settings
+ </a>
+ </div>
+ <div class="user-menu-item" id="profileMenuItem">
+ <i class="fas fa-id-card"></i> Profile
+ </div>
+ <div class="user-menu-item" id="logoutMenuItem">
+ <i class="fas fa-sign-out-alt"></i> Logout
+ </div>
+ </div>
+ </div>
+ <div class="settings-container">
+ <button id="settingsBtn" class="settings-btn" aria-label="Settings" type="button">
+ <i class="fas fa-cog"></i>
+ </button>
+ <div id="settingsMenu" class="settings-menu">
+ <div class="settings-item">
+ <span>Dark Mode</span>
+ <label class="toggle-switch" title="Toggle dark mode">
+ <input type="checkbox" id="darkModeToggle">
+ <span class="toggle-slider"></span>
+ </label>
+ </div>
+ <div class="settings-item">
+ <a href="https://github.com/sassanix/Warracker" class="settings-link github-link" target="_blank" rel="noopener noreferrer">
+ <i class="fab fa-github"></i> GitHub
+ </a>
+ </div>
+ <div class="settings-item">
+ <a href="settings.html" class="settings-link">
+ <i class="fas fa-cogs"></i> Old Settings
+ </a>
+ </div>
+ </div>
+ </div>
+ </div>
+ </header>
+
+ <!-- Main Content -->
+ <div class="container">
+ <div class="content-wrapper">
+ <h2>Settings</h2>
+
+ <!-- Account Settings -->
+ <div class="card">
+ <div class="card-header">
+ <h3>Account Settings</h3>
+ </div>
+ <div class="card-body">
+ <form id="profileForm">
+ <div class="form-group">
+ <label for="firstName">First Name</label>
+ <input type="text" id="firstName" name="firstName" class="form-control">
+ </div>
+
+ <div class="form-group">
+ <label for="lastName">Last Name</label>
+ <input type="text" id="lastName" name="lastName" class="form-control">
+ </div>
+
+ <div class="form-group">
+ <label for="email">Email</label>
+ <input type="email" id="email" name="email" class="form-control" disabled>
+ </div>
+
+ <button type="button" id="saveProfileBtn" class="btn btn-primary">Save Changes</button>
+ </form>
+ </div>
+ </div>
+
+ <!-- Preferences -->
+ <div class="card">
+ <div class="card-header">
+ <h3>Preferences</h3>
+ </div>
+ <div class="card-body">
+ <form id="preferencesForm">
+ <div class="form-group">
+ <div class="preference-item">
+ <div>
+ <label>Dark Mode</label>
+ <p class="text-muted">Switch between light and dark theme</p>
+ </div>
+ <label class="toggle-switch">
+ <input type="checkbox" id="darkModeToggleSetting">
+ <span class="toggle-slider"></span>
+ </label>
+ </div>
+ </div>
+
+ <div class="form-group">
+ <div class="preference-item">
+ <div>
+ <label>Default View</label>
+ <p class="text-muted">Choose your preferred view for warranties</p>
+ </div>
+ <select id="defaultView" class="form-control">
+ <option value="grid">Grid View</option>
+ <option value="list">List View</option>
+ <option value="table">Table View</option>
+ </select>
+ </div>
+ </div>
+
+ <div class="form-group">
+ <div class="preference-item">
+ <div>
+ <label>Email Notifications</label>
+ <p class="text-muted">Receive email alerts for warranty expirations</p>
+ </div>
+ <label class="toggle-switch">
+ <input type="checkbox" id="emailNotifications">
+ <span class="toggle-slider"></span>
+ </label>
+ </div>
+ </div>
+
+ <button type="button" id="savePreferencesBtn" class="btn btn-primary">Save Preferences</button>
+ </form>
+ </div>
+ </div>
+
+ <!-- Security -->
+ <div class="card">
+ <div class="card-header">
+ <h3>Security</h3>
+ </div>
+ <div class="card-body">
+ <div class="preference-item">
+ <div>
+ <label>Change Password</label>
+ <p class="text-muted">Update your account password</p>
+ </div>
+ <button id="changePasswordBtn" class="btn btn-outline-primary">Change</button>
+ </div>
+
+ <div id="passwordChangeForm" style="display: none; margin-top: 20px;">
+ <div class="form-group">
+ <label for="currentPassword">Current Password</label>
+ <input type="password" id="currentPassword" name="currentPassword" class="form-control">
+ </div>
+
+ <div class="form-group">
+ <label for="newPassword">New Password</label>
+ <input type="password" id="newPassword" name="newPassword" class="form-control">
+ </div>
+
+ <div class="form-group">
+ <label for="confirmPassword">Confirm New Password</label>
+ <input type="password" id="confirmPassword" name="confirmPassword" class="form-control">
+ </div>
+
+ <div class="button-group">
+ <button type="button" id="savePasswordBtn" class="btn btn-primary">Update Password</button>
+ <button type="button" id="cancelPasswordBtn" class="btn btn-secondary">Cancel</button>
+ </div>
+ </div>
+ </div>
+ </div>
+
+ <!-- Danger Zone -->
+ <div class="card danger-card">
+ <div class="card-header">
+ <h3>Danger Zone</h3>
+ </div>
+ <div class="card-body">
+ <div class="preference-item">
+ <div>
+ <label>Delete Account</label>
+ <p class="text-muted">Permanently delete your account and all data</p>
+ </div>
+ <button id="deleteAccountBtn" class="btn btn-danger">Delete Account</button>
+ </div>
+ </div>
+ </div>
+
+ <!-- Admin Section - Only visible to admins -->
+ <div id="adminSection" class="admin-section" style="display: none;">
+ <h2>Admin Settings</h2>
+
+ <!-- Admin Actions -->
+ <div class="card">
+ <div class="card-header">
+ <h3>Admin Actions</h3>
+ </div>
+ <div class="card-body">
+ <div class="admin-actions-grid">
+ <button id="refreshUsersBtn" class="admin-action-btn">
+ <i class="fas fa-sync-alt"></i>
+ <span>Refresh Data</span>
+ </button>
+ <button id="checkAdminBtn" class="admin-action-btn">
+ <i class="fas fa-user-shield"></i>
+ <span>Check Admin Status</span>
+ </button>
+ <button id="showUsersBtn" class="admin-action-btn">
+ <i class="fas fa-users"></i>
+ <span>Show Users List</span>
+ </button>
+ <button id="testApiBtn" class="admin-action-btn">
+ <i class="fas fa-vial"></i>
+ <span>Test API</span>
+ </button>
+ </div>
+ </div>
+ </div>
+
+ <!-- Site Settings -->
+ <div class="card">
+ <div class="card-header">
+ <h3>Site Settings</h3>
+ </div>
+ <div class="card-body">
+ <form id="siteSettingsForm">
+ <div class="form-group">
+ <div class="preference-item">
+ <div>
+ <label>Registration Enabled</label>
+ <p class="text-muted">Allow new users to register on the site</p>
+ </div>
+ <label class="toggle-switch">
+ <input type="checkbox" id="registrationEnabled">
+ <span class="toggle-slider"></span>
+ </label>
+ </div>
+ </div>
+
+ <button type="button" id="saveSiteSettingsBtn" class="btn btn-primary">Save Site Settings</button>
+ </form>
+ </div>
+ </div>
+ </div>
+ </div>
+ </div>
+
+ <!-- Delete Account Modal -->
+ <div id="deleteAccountModal" class="modal-backdrop">
+ <div class="modal">
+ <div class="modal-header">
+ <h3 class="modal-title">Delete Account</h3>
+ <button class="close-btn" data-dismiss="modal">&times;</button>
+ </div>
+ <div class="modal-body">
+ <p class="text-danger"><strong>Warning: This action cannot be undone.</strong></p>
+ <p>All your data, including warranties, will be permanently deleted.</p>
+ <p>To confirm, please type "DELETE" in the field below:</p>
+ <input type="text" id="deleteConfirmInput" class="form-control" placeholder="Type DELETE to confirm">
+ </div>
+ <div class="modal-footer">
+ <button class="btn btn-secondary" data-dismiss="modal">Cancel</button>
+ <button id="confirmDeleteAccountBtn" class="btn btn-danger" disabled>Delete My Account</button>
+ </div>
+ </div>
+ </div>
+
+ <!-- Change Password Success Modal -->
+ <div id="passwordSuccessModal" class="modal-backdrop">
+ <div class="modal">
+ <div class="modal-header">
+ <h3 class="modal-title">Password Updated</h3>
+ <button class="close-btn" data-dismiss="modal">&times;</button>
+ </div>
+ <div class="modal-body text-center">
+ <i class="fas fa-check-circle success-icon"></i>
+ <p>Your password has been successfully updated.</p>
+ </div>
+ <div class="modal-footer">
+ <button class="btn btn-primary" data-dismiss="modal">OK</button>
+ </div>
+ </div>
+ </div>
+
+ <!-- Edit User Modal (Admin) -->
+ <div id="editUserModal" class="modal-backdrop">
+ <div class="modal">
+ <div class="modal-header">
+ <h3 class="modal-title">Edit User</h3>
+ <button class="close-btn" data-dismiss="modal">&times;</button>
+ </div>
+ <div class="modal-body">
+ <form id="editUserForm">
+ <input type="hidden" id="editUserId">
+
+ <div class="form-group">
+ <label for="editUsername">Username</label>
+ <input type="text" id="editUsername" class="form-control" disabled>
+ </div>
+
+ <div class="form-group">
+ <label for="editEmail">Email</label>
+ <input type="email" id="editEmail" class="form-control" disabled>
+ </div>
+
+ <div class="form-group">
+ <div class="preference-item">
+ <div>
+ <label>Active Status</label>
+ <p class="text-muted">Enable or disable user access</p>
+ </div>
+ <label class="toggle-switch">
+ <input type="checkbox" id="editUserActive">
+ <span class="toggle-slider"></span>
+ </label>
+ </div>
+ </div>
+
+ <div class="form-group">
+ <div class="preference-item">
+ <div>
+ <label>Admin Status</label>
+ <p class="text-muted">Grant or revoke admin privileges</p>
+ </div>
+ <label class="toggle-switch">
+ <input type="checkbox" id="editUserAdmin">
+ <span class="toggle-slider"></span>
+ </label>
+ </div>
+ </div>
+ </form>
+ </div>
+ <div class="modal-footer">
+ <button class="btn btn-secondary" data-dismiss="modal">Cancel</button>
+ <button id="saveUserBtn" class="btn btn-primary">Save Changes</button>
+ </div>
+ </div>
+ </div>
+
+ <!-- Delete User Confirmation Modal (Admin) -->
+ <div id="deleteUserModal" class="modal-backdrop">
+ <div class="modal">
+ <div class="modal-header">
+ <h3>Delete User</h3>
+ <button class="close-modal">&times;</button>
+ </div>
+ <div class="modal-body">
+ <form id="deleteUserForm">
+ <input type="hidden" id="deleteUserId" name="userId">
+ <p>Are you sure you want to delete user <span id="deleteUserName"></span>?</p>
+ <p style="font-size: 0.8em; color: #666;">User ID: <span id="displayUserId"></span></p>
+ <div class="modal-footer">
+ <button type="button" class="btn btn-secondary close-modal">Cancel</button>
+ <button type="button" id="confirmDeleteUserBtn" class="btn btn-danger" onclick="deleteUser()">Delete</button>
+ </div>
+ <div style="margin-top: 20px; border-top: 1px solid #ddd; padding-top: 10px;">
+ <p><small>If the delete button doesn't work, try these alternatives:</small></p>
+ <ul style="font-size: 0.8em;">
+ <li><a href="#" id="directDeleteLink" style="color: #dc3545;" onclick="deleteUser(); return false;">Alternative 1: Direct function call</a></li>
+ <li><a href="#" id="directAPILink" style="color: #dc3545;" onclick="directDeleteUserAPI(document.getElementById('deleteUserId').value); return false;">Alternative 2: Direct API call</a></li>
+ <li><button type="submit" class="btn btn-sm btn-danger">Alternative 3: Form Submit</button></li>
+ </ul>
+ <div style="margin-top: 10px;">
+ <button type="button" id="emergencyDeleteBtn" class="btn btn-sm btn-danger"
+ onclick="(function() {
+ const userId = document.getElementById('deleteUserId').value || document.getElementById('displayUserId').textContent;
+ if (!userId) {
+ alert('Error: User ID is missing');
+ return;
+ }
+ const token = localStorage.getItem('auth_token');
+ if (!token) {
+ alert('Error: Authentication token is missing');
+ return;
+ }
+ alert('Emergency delete for user ID: ' + userId);
+ fetch('/api/admin/users/' + userId, {
+ method: 'DELETE',
+ headers: {
+ 'Authorization': 'Bearer ' + token,
+ 'Content-Type': 'application/json'
+ }
+ })
+ .then(response => {
+ alert('Response status: ' + response.status);
+ if (response.status >= 200 && response.status < 300) {
+ alert('User deleted successfully');
+ document.querySelectorAll('.modal-backdrop').forEach(m => m.style.display = 'none');
+ location.reload();
+ } else {
+ alert('Failed to delete user: ' + response.status);
+ }
+ })
+ .catch(error => {
+ alert('Error: ' + error.message);
+ });
+ })(); return false;">
+ Emergency Delete (Inline JS)
+ </button>
+ </div>
+ </div>
+ </form>
+ </div>
+ </div>
+ </div>
+
+ <!-- Loading Container -->
+ <div id="loadingContainer" class="loading-container">
+ <div class="spinner"></div>
+ </div>
+
+ <!-- Toast Container -->
+ <div id="toastContainer" class="toast-container"></div>
+
+ <!-- Scripts -->
+ <script src="auth.js"></script>
+ <script src="settings-new.js"></script>
+</body>
+</html>
\ No newline at end of file
diff --git a/frontend/settings-new.js b/frontend/settings-new.js
new file mode 100644
index 0000000..36d419a
--- /dev/null
+++ b/frontend/settings-new.js
@@ -0,0 +1,2294 @@
+// DOM Elements
+const darkModeToggle = document.getElementById('darkModeToggle');
+const darkModeToggleSetting = document.getElementById('darkModeToggleSetting');
+const defaultViewSelect = document.getElementById('defaultView');
+const emailNotificationsToggle = document.getElementById('emailNotifications');
+const saveProfileBtn = document.getElementById('saveProfileBtn');
+const savePreferencesBtn = document.getElementById('savePreferencesBtn');
+const changePasswordBtn = document.getElementById('changePasswordBtn');
+const passwordChangeForm = document.getElementById('passwordChangeForm');
+const savePasswordBtn = document.getElementById('savePasswordBtn');
+const cancelPasswordBtn = document.getElementById('cancelPasswordBtn');
+const deleteAccountBtn = document.getElementById('deleteAccountBtn');
+const deleteAccountModal = document.getElementById('deleteAccountModal');
+const deleteConfirmInput = document.getElementById('deleteConfirmInput');
+const confirmDeleteAccountBtn = document.getElementById('confirmDeleteAccountBtn');
+const passwordSuccessModal = document.getElementById('passwordSuccessModal');
+const loadingContainer = document.getElementById('loadingContainer');
+const toastContainer = document.getElementById('toastContainer');
+const settingsBtn = document.getElementById('settingsBtn');
+const settingsMenu = document.getElementById('settingsMenu');
+
+// Form fields
+const firstNameInput = document.getElementById('firstName');
+const lastNameInput = document.getElementById('lastName');
+const emailInput = document.getElementById('email');
+const currentPasswordInput = document.getElementById('currentPassword');
+const newPasswordInput = document.getElementById('newPassword');
+const confirmPasswordInput = document.getElementById('confirmPassword');
+
+// DOM Elements for admin section
+const adminSection = document.getElementById('adminSection');
+const refreshUsersBtn = document.getElementById('refreshUsersBtn');
+const checkAdminBtn = document.getElementById('checkAdminBtn');
+const showUsersBtn = document.getElementById('showUsersBtn');
+const testApiBtn = document.getElementById('testApiBtn');
+const registrationEnabled = document.getElementById('registrationEnabled');
+const saveSiteSettingsBtn = document.getElementById('saveSiteSettingsBtn');
+
+// Initialize settings page
+document.addEventListener('DOMContentLoaded', function() {
+ console.log('DOM fully loaded, initializing settings page');
+
+ // Initialize the page
+ initPage();
+
+ // Set up event listeners
+ setupEventListeners();
+
+ // Initialize modals
+ initModals();
+
+ // Set up direct event listeners for critical elements
+ setupCriticalEventListeners();
+
+ // Make deleteUser function globally accessible
+ window.deleteUser = deleteUser;
+ window.directDeleteUserAPI = directDeleteUserAPI;
+
+ // Add a global click handler for delete buttons
+ document.addEventListener('click', function(event) {
+ // Check if the click was on a delete button or inside the delete modal
+ if (event.target && event.target.id === 'confirmDeleteUserBtn') {
+ console.log('Global click handler caught delete button click');
+ event.preventDefault();
+ event.stopPropagation();
+ deleteUser();
+ return false;
+ }
+
+ // Check for clicks on the direct delete link
+ if (event.target && event.target.id === 'directDeleteLink') {
+ console.log('Global click handler caught direct delete link click');
+ event.preventDefault();
+ event.stopPropagation();
+ deleteUser();
+ return false;
+ }
+
+ // Check for clicks on the direct API link
+ if (event.target && event.target.id === 'directAPILink') {
+ console.log('Global click handler caught direct API link click');
+ event.preventDefault();
+ event.stopPropagation();
+ const userId = window.currentDeleteUserId ||
+ (document.getElementById('deleteUserId') ? document.getElementById('deleteUserId').value : null);
+ directDeleteUserAPI(userId);
+ return false;
+ }
+
+ // Check for clicks on the emergency delete button
+ if (event.target && event.target.id === 'emergencyDeleteBtn') {
+ console.log('Global click handler caught emergency delete button click');
+ // The button has its own inline handler, so we don't need to do anything here
+ }
+
+ // Check for any element with delete-user-btn class or containing "delete" in the id
+ if (event.target &&
+ (event.target.classList.contains('delete-user-btn') ||
+ (event.target.id && event.target.id.toLowerCase().includes('delete')))) {
+ console.log('Global click handler caught click on element with delete in the id:', event.target.id);
+ console.log('Element:', event.target);
+
+ // If this is a button inside the delete modal, try to delete the user
+ if (event.target.closest('#deleteUserModal')) {
+ console.log('Element is inside delete modal, attempting to delete user');
+ event.preventDefault();
+ event.stopPropagation();
+ deleteUser();
+ return false;
+ }
+ }
+ });
+
+ // Add a direct event listener to the confirmDeleteUserBtn
+ const confirmDeleteUserBtn = document.getElementById('confirmDeleteUserBtn');
+ if (confirmDeleteUserBtn) {
+ console.log('Adding direct event listener to confirmDeleteUserBtn on page load');
+ confirmDeleteUserBtn.addEventListener('click', function(e) {
+ console.log('Direct event listener on confirmDeleteUserBtn triggered');
+ e.preventDefault();
+ e.stopPropagation();
+ deleteUser();
+ return false;
+ });
+ }
+});
+
+/**
+ * Initialize the settings page
+ */
+function initPage() {
+ console.log('Initializing settings page');
+
+ // Check authentication
+ if (window.auth) {
+ window.auth.checkAuthState();
+
+ // Redirect to login if not authenticated
+ if (!window.auth.isAuthenticated()) {
+ console.log('User not authenticated, redirecting to login');
+ window.location.href = 'login.html';
+ return;
+ }
+ } else {
+ // Auth module not loaded
+ console.error('Auth module not loaded');
+ window.location.href = 'login.html';
+ return;
+ }
+
+ // Load user data and preferences
+ loadUserData();
+ loadPreferences();
+
+ // Fix for settings button
+ if (settingsBtn) {
+ console.log('Settings button found, adding event listener');
+ settingsBtn.addEventListener('click', function(e) {
+ e.stopPropagation();
+ settingsMenu.classList.toggle('active');
+ console.log('Settings button clicked, menu toggled');
+ });
+
+ // Close settings menu when clicking outside
+ document.addEventListener('click', function(e) {
+ if (settingsMenu.classList.contains('active') &&
+ !settingsMenu.contains(e.target) &&
+ !settingsBtn.contains(e.target)) {
+ settingsMenu.classList.remove('active');
+ }
+ });
+ } else {
+ console.error('Settings button not found');
+ }
+
+ console.log('Settings page initialization complete');
+}
+
+/**
+ * Set up critical event listeners that must work for core functionality
+ */
+function setupCriticalEventListeners() {
+ console.log('Setting up critical event listeners');
+
+ // Set up delete user modal close buttons
+ const closeModalButtons = document.querySelectorAll('.close-modal');
+ closeModalButtons.forEach(button => {
+ button.addEventListener('click', function() {
+ closeAllModals();
+ });
+ });
+
+ // Set up delete user button in the modal
+ const confirmDeleteUserBtn = document.getElementById('confirmDeleteUserBtn');
+ if (confirmDeleteUserBtn) {
+ console.log('Setting up confirmDeleteUserBtn');
+
+ // Add multiple event handlers for redundancy
+ confirmDeleteUserBtn.addEventListener('click', function(e) {
+ e.preventDefault();
+ e.stopPropagation();
+ console.log('Delete button clicked via addEventListener in setupCriticalEventListeners');
+ deleteUser();
+ return false;
+ });
+
+ confirmDeleteUserBtn.onclick = function(e) {
+ e.preventDefault();
+ e.stopPropagation();
+ console.log('Delete button clicked via onclick in setupCriticalEventListeners');
+ deleteUser();
+ return false;
+ };
+ }
+
+ // Set up direct delete link
+ const directDeleteLink = document.getElementById('directDeleteLink');
+ if (directDeleteLink) {
+ directDeleteLink.addEventListener('click', function(e) {
+ e.preventDefault();
+ e.stopPropagation();
+ console.log('Direct delete link clicked in setupCriticalEventListeners');
+ deleteUser();
+ return false;
+ });
+ }
+
+ // Set up direct API link
+ const directAPILink = document.getElementById('directAPILink');
+ if (directAPILink) {
+ directAPILink.addEventListener('click', function(e) {
+ e.preventDefault();
+ e.stopPropagation();
+ console.log('Direct API link clicked in setupCriticalEventListeners');
+ const userId = window.currentDeleteUserId ||
+ (document.getElementById('deleteUserId') ? document.getElementById('deleteUserId').value : null);
+ directDeleteUserAPI(userId);
+ return false;
+ });
+ }
+
+ // Set up delete user form
+ const deleteUserForm = document.getElementById('deleteUserForm');
+ if (deleteUserForm) {
+ deleteUserForm.addEventListener('submit', function(e) {
+ e.preventDefault();
+ e.stopPropagation();
+ console.log('Delete user form submitted in setupCriticalEventListeners');
+ deleteUser();
+ return false;
+ });
+ }
+}
+
+/**
+ * Load user data from localStorage and API
+ */
+async function loadUserData() {
+ showLoading();
+
+ 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 || '';
+
+ // Check if user is admin and show admin section
+ if (currentUser.is_admin) {
+ adminSection.style.display = 'block';
+ loadUsers();
+ loadSiteSettings();
+ }
+ }
+
+ // Fetch fresh user data from API
+ try {
+ const response = await fetch('/api/auth/user', {
+ method: 'GET',
+ headers: {
+ '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 || '';
+
+ // Check if user is admin and show admin section
+ if (userData.is_admin) {
+ adminSection.style.display = 'block';
+ loadUsers();
+ loadSiteSettings();
+ }
+
+ // Update localStorage
+ localStorage.setItem('user_info', JSON.stringify(userData));
+ } else {
+ // Handle error
+ const errorData = await response.json();
+ console.warn('API error:', errorData.message);
+ }
+ } catch (apiError) {
+ console.warn('API error, using localStorage data:', apiError);
+ }
+ } catch (error) {
+ console.error('Error loading user data:', error);
+ showToast('Failed to load user data. Please try again.', 'error');
+ } finally {
+ hideLoading();
+ }
+}
+
+/**
+ * Load user preferences from localStorage
+ */
+function loadPreferences() {
+ // Load dark mode preference
+ const darkMode = localStorage.getItem('darkMode') === 'true';
+ darkModeToggle.checked = darkMode;
+ darkModeToggleSetting.checked = darkMode;
+
+ // Apply the theme immediately
+ setTheme(darkMode);
+
+ // Load default view preference
+ const defaultView = localStorage.getItem('defaultView') || 'grid';
+ defaultViewSelect.value = defaultView;
+
+ // Load email notifications preference (default to true if not set)
+ const emailNotifications = localStorage.getItem('emailNotifications') !== 'false';
+ emailNotificationsToggle.checked = emailNotifications;
+}
+
+/**
+ * Setup event listeners for the settings page
+ */
+function setupEventListeners() {
+ console.log('Setting up event listeners');
+
+ // Dark mode toggle
+ if (darkModeToggle) {
+ darkModeToggle.addEventListener('change', function() {
+ setTheme(this.checked);
+
+ // Also update the settings page toggle
+ if (darkModeToggleSetting) {
+ darkModeToggleSetting.checked = this.checked;
+ }
+ });
+ }
+
+ // Dark mode toggle in settings
+ if (darkModeToggleSetting) {
+ darkModeToggleSetting.addEventListener('change', function() {
+ setTheme(this.checked);
+
+ // Also update the header toggle
+ if (darkModeToggle) {
+ darkModeToggle.checked = this.checked;
+ }
+ });
+ }
+
+ // Save profile button
+ if (saveProfileBtn) {
+ saveProfileBtn.addEventListener('click', saveProfile);
+ }
+
+ // Save preferences button
+ if (savePreferencesBtn) {
+ savePreferencesBtn.addEventListener('click', savePreferences);
+ }
+
+ // Change password button
+ if (changePasswordBtn) {
+ changePasswordBtn.addEventListener('click', function() {
+ passwordChangeForm.style.display = 'block';
+ this.style.display = 'none';
+ });
+ }
+
+ // Save password button
+ if (savePasswordBtn) {
+ savePasswordBtn.addEventListener('click', changePassword);
+ }
+
+ // Cancel password button
+ if (cancelPasswordBtn) {
+ cancelPasswordBtn.addEventListener('click', function() {
+ resetPasswordForm();
+ passwordChangeForm.style.display = 'none';
+ changePasswordBtn.style.display = 'block';
+ });
+ }
+
+ // Delete account button
+ if (deleteAccountBtn) {
+ deleteAccountBtn.addEventListener('click', function() {
+ openModal(deleteAccountModal);
+ });
+ }
+
+ // Delete confirm input
+ if (deleteConfirmInput) {
+ deleteConfirmInput.addEventListener('input', function() {
+ confirmDeleteAccountBtn.disabled = this.value !== 'DELETE';
+ });
+ }
+
+ // Confirm delete account button
+ if (confirmDeleteAccountBtn) {
+ confirmDeleteAccountBtn.addEventListener('click', deleteAccount);
+ }
+
+ // Admin section buttons
+ if (refreshUsersBtn) {
+ refreshUsersBtn.addEventListener('click', loadUsers);
+ }
+
+ if (checkAdminBtn) {
+ checkAdminBtn.addEventListener('click', checkAdminPermissions);
+ }
+
+ if (showUsersBtn) {
+ showUsersBtn.addEventListener('click', showUsersList);
+ }
+
+ if (testApiBtn) {
+ testApiBtn.addEventListener('click', checkApiEndpoint);
+ }
+
+ // Site settings save button
+ if (saveSiteSettingsBtn) {
+ saveSiteSettingsBtn.addEventListener('click', saveSiteSettings);
+ }
+
+ console.log('Event listeners setup complete');
+}
+
+/**
+ * Initialize modals
+ */
+function initModals() {
+ // Close modal when clicking on X or outside
+ document.querySelectorAll('.close-btn, [data-dismiss="modal"]').forEach(closeBtn => {
+ closeBtn.addEventListener('click', () => {
+ document.querySelectorAll('.modal-backdrop').forEach(modal => {
+ modal.style.display = 'none';
+ });
+
+ // Reset delete confirm input
+ if (deleteConfirmInput) {
+ deleteConfirmInput.value = '';
+ confirmDeleteAccountBtn.disabled = true;
+ }
+
+ // Reset password form
+ resetPasswordForm();
+ });
+ });
+
+ // Close modal when clicking outside
+ window.addEventListener('click', (event) => {
+ document.querySelectorAll('.modal-backdrop').forEach(modal => {
+ if (event.target === modal) {
+ modal.style.display = 'none';
+
+ // Reset delete confirm input
+ if (deleteConfirmInput) {
+ deleteConfirmInput.value = '';
+ confirmDeleteAccountBtn.disabled = true;
+ }
+
+ // Reset password form
+ resetPasswordForm();
+ }
+ });
+ });
+
+ // Add direct click handler to delete user modal
+ if (deleteUserModal) {
+ console.log('Adding click handler to deleteUserModal');
+ deleteUserModal.addEventListener('click', function(event) {
+ // Check if the click was on the confirm delete button
+ if (event.target && event.target.id === 'confirmDeleteUserBtn') {
+ event.preventDefault();
+ console.log('Confirm delete button clicked through modal event delegation');
+ deleteUser();
+ }
+ });
+ } else {
+ console.error('deleteUserModal not found in initModals');
+ }
+}
+
+/**
+ * Open a modal
+ * @param {HTMLElement} modal - The modal to open
+ */
+function openModal(modal) {
+ console.log('Opening modal:', modal.id, 'Current display:', modal.style.display);
+
+ // First close all modals
+ closeAllModals();
+
+ // Then open this modal
+ modal.style.display = 'flex';
+ console.log('Modal display after opening:', modal.style.display);
+
+ // If this is the delete user modal, set up the delete button
+ if (modal.id === 'deleteUserModal') {
+ console.log('This is the delete user modal, setting up delete button');
+ // Use setTimeout to ensure the DOM is fully updated
+ setTimeout(() => {
+ setupDeleteButton();
+ }, 100);
+ }
+}
+
+/**
+ * Reset password form
+ */
+function resetPasswordForm() {
+ currentPasswordInput.value = '';
+ newPasswordInput.value = '';
+ confirmPasswordInput.value = '';
+}
+
+/**
+ * Set theme (dark/light)
+ * @param {boolean} isDark - Whether to use dark mode
+ */
+function setTheme(isDark) {
+ document.documentElement.setAttribute('data-theme', isDark ? 'dark' : 'light');
+
+ // Also add/remove the dark-mode class on the body for additional styling
+ if (isDark) {
+ document.body.classList.add('dark-mode');
+ } else {
+ document.body.classList.remove('dark-mode');
+ }
+
+ localStorage.setItem('darkMode', isDark);
+}
+
+/**
+ * Save user profile
+ */
+async function saveProfile() {
+ // Validate form
+ if (!firstNameInput.value.trim() || !lastNameInput.value.trim()) {
+ showToast('Please fill in all required fields', 'error');
+ return;
+ }
+
+ showLoading();
+
+ 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 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');
+ } else {
+ throw new Error('User not found in localStorage');
+ }
+ }
+ } catch (error) {
+ console.error('Error updating profile:', error);
+ showToast('Failed to update profile. Please try again.', 'error');
+ } finally {
+ hideLoading();
+ }
+}
+
+/**
+ * Save user preferences
+ */
+function savePreferences() {
+ // Save dark mode preference
+ const isDark = darkModeToggleSetting.checked;
+ setTheme(isDark);
+ darkModeToggle.checked = isDark;
+
+ // Save default view preference
+ const defaultView = defaultViewSelect.value;
+ localStorage.setItem('defaultView', defaultView);
+ localStorage.setItem('warrantyView', defaultView);
+
+ // Save email notifications preference
+ const emailNotifications = emailNotificationsToggle.checked;
+ localStorage.setItem('emailNotifications', emailNotifications);
+
+ showToast('Preferences saved successfully', 'success');
+}
+
+/**
+ * Change user password
+ */
+async function changePassword() {
+ // Validate form
+ if (!currentPasswordInput.value || !newPasswordInput.value || !confirmPasswordInput.value) {
+ showToast('Please fill in all password fields', 'error');
+ return;
+ }
+
+ if (newPasswordInput.value !== confirmPasswordInput.value) {
+ showToast('New passwords do not match', 'error');
+ return;
+ }
+
+ // Validate password strength
+ if (newPasswordInput.value.length < 8) {
+ showToast('Password must be at least 8 characters long', 'error');
+ return;
+ }
+
+ 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
+ })
+ });
+
+ 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');
+ }
+ } catch (error) {
+ console.error('Error changing password:', error);
+ showToast('Failed to change password. Please try again.', 'error');
+ } finally {
+ hideLoading();
+ }
+}
+
+/**
+ * Delete user account
+ */
+async function deleteAccount() {
+ if (deleteConfirmInput.value !== 'DELETE') {
+ showToast('Please type DELETE to confirm', 'error');
+ return;
+ }
+
+ showLoading();
+
+ try {
+ try {
+ const response = await fetch('/api/auth/account', {
+ method: 'DELETE',
+ headers: {
+ 'Authorization': `Bearer ${window.auth.getToken()}`
+ }
+ });
+
+ if (response.ok) {
+ // Clear auth data
+ if (window.auth.logout) {
+ window.auth.logout();
+ } else {
+ localStorage.removeItem('auth_token');
+ localStorage.removeItem('user_info');
+ }
+
+ // Show success message
+ showToast('Account deleted successfully', 'success');
+
+ // Redirect to home page after a short delay
+ setTimeout(() => {
+ window.location.href = 'index.html';
+ }, 2000);
+ } else {
+ // Handle error
+ const errorData = await response.json();
+ throw new Error(errorData.message || 'Failed to delete account');
+ }
+ } catch (apiError) {
+ console.warn('API error, showing offline message:', apiError);
+ showToast('Account cannot be deleted in offline mode', 'warning');
+ }
+ } catch (error) {
+ console.error('Error deleting account:', error);
+ showToast('Failed to delete account. Please try again.', 'error');
+ } finally {
+ hideLoading();
+
+ // Close modal
+ deleteAccountModal.style.display = 'none';
+
+ // Reset delete confirm input
+ deleteConfirmInput.value = '';
+ confirmDeleteAccountBtn.disabled = true;
+ }
+}
+
+/**
+ * Show loading spinner
+ */
+function showLoading() {
+ loadingContainer.style.display = 'flex';
+}
+
+/**
+ * Hide loading spinner
+ */
+function hideLoading() {
+ loadingContainer.style.display = 'none';
+}
+
+/**
+ * Show a toast notification
+ * @param {string} message - The message to display
+ * @param {string} type - The type of toast (info, success, error, warning)
+ * @param {number} duration - Duration in milliseconds, 0 for no auto-hide
+ * @returns {HTMLElement} - The toast element
+ */
+function showToast(message, type = 'info', duration = 5000) {
+ const toast = document.createElement('div');
+ toast.className = `toast toast-${type}`;
+
+ const icon = document.createElement('i');
+ switch (type) {
+ case 'success':
+ icon.className = 'fas fa-check-circle';
+ break;
+ case 'error':
+ icon.className = 'fas fa-exclamation-circle';
+ break;
+ case 'warning':
+ icon.className = 'fas fa-exclamation-triangle';
+ break;
+ default:
+ icon.className = 'fas fa-info-circle';
+ }
+
+ const messageSpan = document.createElement('span');
+ messageSpan.textContent = message;
+
+ toast.appendChild(icon);
+ toast.appendChild(messageSpan);
+
+ toastContainer.appendChild(toast);
+
+ // Add a method to remove the toast
+ toast.remove = function() {
+ toast.classList.add('toast-fade-out');
+ setTimeout(() => {
+ if (toast.parentNode) {
+ toast.parentNode.removeChild(toast);
+ }
+ }, 300);
+ };
+
+ // Auto-hide toast after specified duration (if not 0)
+ if (duration > 0) {
+ setTimeout(() => {
+ toast.remove();
+ }, duration);
+ }
+
+ return toast;
+}
+
+/**
+ * Load users for admin
+ */
+async function loadUsers() {
+ if (!usersTableBody) return;
+
+ showLoading();
+
+ try {
+ const response = await fetch('/api/admin/users', {
+ method: 'GET',
+ headers: {
+ 'Authorization': `Bearer ${window.auth.getToken()}`
+ }
+ });
+
+ if (response.ok) {
+ const users = await response.json();
+
+ // Clear table
+ usersTableBody.innerHTML = '';
+
+ // Add users to table
+ users.forEach(user => {
+ const row = document.createElement('tr');
+
+ // Username
+ const usernameCell = document.createElement('td');
+ usernameCell.textContent = user.username;
+ row.appendChild(usernameCell);
+
+ // Email
+ const emailCell = document.createElement('td');
+ emailCell.textContent = user.email;
+ row.appendChild(emailCell);
+
+ // Name
+ const nameCell = document.createElement('td');
+ const fullName = `${user.first_name || ''} ${user.last_name || ''}`.trim();
+ nameCell.textContent = fullName || '-';
+ row.appendChild(nameCell);
+
+ // Status
+ const statusCell = document.createElement('td');
+ const statusBadge = document.createElement('span');
+ statusBadge.className = `badge ${user.is_active ? 'badge-success' : 'badge-danger'}`;
+ statusBadge.textContent = user.is_active ? 'Active' : 'Inactive';
+ statusCell.appendChild(statusBadge);
+ row.appendChild(statusCell);
+
+ // Admin
+ const adminCell = document.createElement('td');
+ const adminBadge = document.createElement('span');
+ adminBadge.className = `badge ${user.is_admin ? 'badge-primary' : 'badge-secondary'}`;
+ adminBadge.textContent = user.is_admin ? 'Admin' : 'User';
+ adminCell.appendChild(adminBadge);
+ row.appendChild(adminCell);
+
+ // Actions
+ const actionsCell = document.createElement('td');
+
+ // Edit button
+ const editBtn = document.createElement('button');
+ editBtn.className = 'btn btn-sm btn-outline-primary mr-2';
+ editBtn.innerHTML = '<i class="fas fa-edit"></i>';
+ editBtn.title = 'Edit User';
+ editBtn.addEventListener('click', () => openEditUserModal(user));
+
+ // Delete button
+ const deleteBtn = document.createElement('button');
+ deleteBtn.className = 'btn btn-sm btn-outline-danger';
+ deleteBtn.innerHTML = '<i class="fas fa-trash-alt"></i>';
+ deleteBtn.title = 'Delete User';
+
+ // Add multiple event handlers for redundancy
+ deleteBtn.addEventListener('click', (event) => {
+ event.preventDefault();
+ event.stopPropagation();
+ console.log('Delete button clicked for user:', user);
+ openDeleteUserModal(user);
+ });
+
+ // Also set onclick property
+ deleteBtn.onclick = function(event) {
+ event.preventDefault();
+ event.stopPropagation();
+ console.log('Delete button onclick property triggered for user:', user);
+ openDeleteUserModal(user);
+ return false;
+ };
+
+ // Don't allow editing or deleting self
+ const currentUser = window.auth.getCurrentUser();
+ if (user.id === currentUser.id) {
+ editBtn.disabled = true;
+ deleteBtn.disabled = true;
+ editBtn.title = 'Cannot edit yourself';
+ deleteBtn.title = 'Cannot delete yourself';
+ console.log('Disabled edit/delete for current user:', currentUser.id);
+ }
+
+ actionsCell.appendChild(editBtn);
+ actionsCell.appendChild(deleteBtn);
+ row.appendChild(actionsCell);
+
+ usersTableBody.appendChild(row);
+ });
+
+ console.log('Users loaded successfully:', users.length);
+ } else {
+ console.error('Failed to load users:', response.status);
+ showToast('Failed to load users', 'error');
+ }
+ } catch (error) {
+ console.error('Error loading users:', error);
+ showToast('Error loading users', 'error');
+ } finally {
+ hideLoading();
+ }
+}
+
+/**
+ * Open edit user modal
+ * @param {Object} user - The user to edit
+ */
+function openEditUserModal(user) {
+ editUserId.value = user.id;
+ editUsername.value = user.username;
+ editEmail.value = user.email;
+ editUserActive.checked = user.is_active;
+ editUserAdmin.checked = user.is_admin;
+
+ openModal(editUserModal);
+}
+
+/**
+ * Save user changes
+ */
+async function saveUserChanges() {
+ const userId = editUserId.value;
+
+ if (!userId) {
+ showToast('User ID is missing', 'error');
+ return;
+ }
+
+ showLoading();
+
+ try {
+ const response = await fetch(`/api/admin/users/${userId}`, {
+ method: 'PUT',
+ headers: {
+ 'Authorization': `Bearer ${window.auth.getToken()}`,
+ 'Content-Type': 'application/json'
+ },
+ body: JSON.stringify({
+ is_active: editUserActive.checked,
+ is_admin: editUserAdmin.checked
+ })
+ });
+
+ if (response.ok) {
+ showToast('User updated successfully', 'success');
+ closeAllModals();
+ loadUsers();
+ } else {
+ const errorData = await response.json();
+ showToast(errorData.message || 'Failed to update user', 'error');
+ }
+ } catch (error) {
+ console.error('Error updating user:', error);
+ showToast('Failed to update user. Please try again.', 'error');
+ } finally {
+ hideLoading();
+ }
+}
+
+/**
+ * Open delete user modal
+ * @param {Object} user - User object
+ */
+function openDeleteUserModal(user) {
+ console.log('Opening delete modal for user:', user);
+
+ // Store the user ID in a global variable for easier access
+ window.currentDeleteUserId = user.id;
+ console.log('Set global currentDeleteUserId to:', user.id);
+
+ // Set the user ID in the form
+ const deleteUserIdField = document.getElementById('deleteUserId');
+ if (deleteUserIdField) {
+ deleteUserIdField.value = user.id;
+ console.log('Set deleteUserId field to:', user.id);
+ } else {
+ console.error('deleteUserId field not found in the DOM');
+ }
+
+ // Display user ID for debugging
+ const displayUserIdField = document.getElementById('displayUserId');
+ if (displayUserIdField) {
+ displayUserIdField.textContent = user.id;
+ console.log('Set displayUserId field to:', user.id);
+ }
+
+ // Also set in editUserId for backward compatibility
+ if (editUserId) {
+ editUserId.value = user.id;
+ console.log('Set editUserId.value to:', user.id);
+ }
+
+ // Set the username in the modal
+ const deleteUserNameElement = document.getElementById('deleteUserName');
+ if (deleteUserNameElement) {
+ deleteUserNameElement.textContent = user.username;
+ console.log('Set deleteUserName to:', user.username);
+ } else {
+ console.error('deleteUserName element not found in the DOM');
+ }
+
+ // Make sure the modal is visible
+ const deleteUserModal = document.getElementById('deleteUserModal');
+ if (deleteUserModal) {
+ // First ensure all modals are closed
+ closeAllModals();
+
+ // Then open this modal
+ deleteUserModal.style.display = 'flex';
+ console.log('Delete user modal opened');
+
+ // Ensure the delete button has the correct click handler
+ const confirmDeleteUserBtn = document.getElementById('confirmDeleteUserBtn');
+ if (confirmDeleteUserBtn) {
+ // Remove existing event listeners by cloning
+ const newBtn = confirmDeleteUserBtn.cloneNode(true);
+ confirmDeleteUserBtn.parentNode.replaceChild(newBtn, confirmDeleteUserBtn);
+
+ // Add the click event listener
+ newBtn.addEventListener('click', function(e) {
+ e.preventDefault();
+ e.stopPropagation();
+ console.log('Delete button clicked for user ID:', user.id);
+ deleteUser();
+ return false;
+ });
+
+ // Also set the direct onclick attribute as a simple function call
+ newBtn.setAttribute('onclick', 'console.log("Direct onclick attribute clicked"); deleteUser(); return false;');
+ console.log('Added click event listener to delete button');
+
+ // Add a direct click handler
+ newBtn.onclick = function(e) {
+ e.preventDefault();
+ e.stopPropagation();
+ console.log('Direct onclick property handler clicked for user ID:', user.id);
+ deleteUser();
+ return false;
+ };
+ } else {
+ console.error('confirmDeleteUserBtn not found in the DOM');
+ }
+
+ // Set up the direct delete link
+ const directDeleteLink = document.getElementById('directDeleteLink');
+ if (directDeleteLink) {
+ directDeleteLink.onclick = function(e) {
+ e.preventDefault();
+ e.stopPropagation();
+ console.log('Direct delete link clicked for user ID:', user.id);
+ deleteUser();
+ return false;
+ };
+ console.log('Added onclick handler to direct delete link');
+ }
+
+ // Set up the direct API link
+ const directAPILink = document.getElementById('directAPILink');
+ if (directAPILink) {
+ directAPILink.onclick = function(e) {
+ e.preventDefault();
+ e.stopPropagation();
+ console.log('Direct API link clicked for user ID:', user.id);
+ directDeleteUserAPI(user.id);
+ return false;
+ };
+ console.log('Added onclick handler to direct API link');
+ }
+
+ // Also set up form submit handler
+ const deleteUserForm = document.getElementById('deleteUserForm');
+ if (deleteUserForm) {
+ deleteUserForm.onsubmit = function(e) {
+ e.preventDefault();
+ e.stopPropagation();
+ console.log('Delete user form submitted for user ID:', user.id);
+ deleteUser();
+ return false;
+ };
+ console.log('Added onsubmit handler to delete user form');
+ }
+
+ // Add a direct click handler to the modal for event delegation
+ deleteUserModal.addEventListener('click', function(e) {
+ if (e.target && e.target.id === 'confirmDeleteUserBtn') {
+ e.preventDefault();
+ e.stopPropagation();
+ console.log('Delete button clicked through modal event delegation for user ID:', user.id);
+ deleteUser();
+ return false;
+ }
+ });
+ } else {
+ console.error('deleteUserModal not found in the DOM');
+ }
+}
+
+/**
+ * Delete user
+ */
+function deleteUser() {
+ console.log('=== DELETE USER FUNCTION STARTED ===');
+ console.log('Function caller:', arguments.callee.caller ? arguments.callee.caller.name : 'unknown');
+
+ try {
+ // Get the user ID from various possible sources
+ const userId = window.currentDeleteUserId ||
+ (document.getElementById('deleteUserId') ? document.getElementById('deleteUserId').value : null) ||
+ (document.getElementById('editUserId') ? document.getElementById('editUserId').value : null) ||
+ (document.getElementById('displayUserId') ? document.getElementById('displayUserId').textContent : null);
+
+ console.log('Final User ID to delete:', userId);
+
+ if (!userId) {
+ showToast('User ID is missing', 'error');
+ console.error('Delete user failed: User ID is missing');
+ return;
+ }
+
+ console.log('Starting user deletion process for ID:', userId);
+ showLoading();
+
+ // Use our improved deletion function
+ superEmergencyDelete(userId)
+ .then(success => {
+ if (success) {
+ console.log('User deletion successful');
+ showToast('User deleted successfully', 'success');
+ closeAllModals();
+ loadUsers(); // Refresh the user list
+
+ // Refresh the users list if it's currently displayed
+ const usersModal = document.querySelector('div[style*="z-index: 10000"]');
+ if (usersModal) {
+ document.body.removeChild(usersModal);
+ showUsersList();
+ }
+ } else {
+ console.error('User deletion failed');
+ showToast('Failed to delete user. Check console for details.', 'error');
+ }
+ hideLoading();
+ })
+ .catch(error => {
+ console.error('Error during user deletion:', error);
+ showToast('Error during user deletion: ' + error.message, 'error');
+ hideLoading();
+
+ // Try the direct API call as a fallback
+ if (confirm('Would you like to try a direct API call to delete the user?')) {
+ const directToast = showToast(`Trying direct API call for user ID ${userId}...`, 'info', 0);
+
+ directDeleteUserAPI(userId)
+ .then(directSuccess => {
+ directToast.remove();
+
+ if (directSuccess) {
+ showToast(`User ID ${userId} deleted successfully with direct API call!`, 'success');
+
+ // Refresh the users list if it's currently displayed
+ const usersModal = document.querySelector('div[style*="z-index: 10000"]');
+ if (usersModal) {
+ document.body.removeChild(usersModal);
+ setTimeout(() => {
+ showUsersList();
+ }, 500);
+ }
+ } else {
+ showToast(`Failed to delete user ${user.username} with direct API call.`, 'error');
+ }
+ })
+ .catch(error => {
+ directToast.remove();
+ console.error('Error with direct API call:', error);
+ showToast('Error with direct API call: ' + error.message, 'error');
+ });
+ }
+ })
+ .catch(error => {
+ console.error('Error checking if user exists:', error);
+ showToast('Error checking if user exists: ' + error.message, 'error');
+ });
+ } catch (error) {
+ console.error('Error in deleteUser function:', error);
+ console.error('Error details:', error.message, error.stack);
+ showToast('Failed to delete user. Please try again.', 'error');
+ hideLoading();
+ }
+
+ console.log('=== DELETE USER FUNCTION COMPLETED ===');
+}
+
+/**
+ * Super emergency delete function for user deletion
+ * @param {string|number} userId - The user ID or username to delete
+ * @returns {Promise<boolean>} - Promise that resolves to true if deletion was successful, false otherwise
+ */
+function superEmergencyDelete(userId) {
+ console.log('=== SUPER EMERGENCY DELETE STARTED ===');
+ console.log('User ID or username to delete:', userId);
+
+ return new Promise((resolve, reject) => {
+ if (!userId) {
+ console.error('No user ID provided');
+ reject(new Error('No user ID provided'));
+ return;
+ }
+
+ // Check if the input is a username rather than a numeric ID
+ if (isNaN(userId)) {
+ console.log('Input appears to be a username, not a numeric ID');
+ // Try to find the user ID by username using the Promise-based function
+ findUserIdByUsernameAsync(userId)
+ .then(numericId => {
+ if (numericId) {
+ console.log(`Found numeric ID ${numericId} for username ${userId}`);
+ // Call this function again with the numeric ID
+ return superEmergencyDelete(numericId);
+ } else {
+ throw new Error(`Could not find a user with username "${userId}"`);
+ }
+ })
+ .then(resolve)
+ .catch(reject);
+ return;
+ }
+
+ console.log('Proceeding with numeric user ID:', userId);
+
+ // Get the token
+ const token = localStorage.getItem('auth_token');
+ if (!token) {
+ console.error('Authentication token is missing');
+ reject(new Error('Authentication token is missing'));
+ return;
+ }
+
+ // Create a new XMLHttpRequest
+ const xhr = new XMLHttpRequest();
+ xhr.open('DELETE', `/api/admin/users/${userId}`, true);
+
+ // Set headers
+ xhr.setRequestHeader('Authorization', `Bearer ${token}`);
+ xhr.setRequestHeader('Content-Type', 'application/json');
+ xhr.setRequestHeader('Accept', 'application/json');
+
+ // Set up event handlers
+ xhr.onload = function() {
+ console.log('XHR status:', xhr.status);
+ console.log('XHR response text:', xhr.responseText);
+
+ if (xhr.status >= 200 && xhr.status < 300) {
+ console.log('User deletion successful');
+ resolve(true);
+ } else {
+ console.error('User deletion failed with status:', xhr.status);
+ let errorMessage = 'Unknown error';
+ try {
+ const response = JSON.parse(xhr.responseText);
+ errorMessage = response.message || response.error || 'Unknown error';
+ } catch (e) {
+ errorMessage = xhr.responseText || 'Unknown error';
+ }
+ console.error('Error message:', errorMessage);
+ resolve(false); // Resolve with false instead of rejecting to handle the error in a controlled way
+ }
+ };
+
+ xhr.onerror = function() {
+ console.error('Network error during user deletion');
+ reject(new Error('Network error during user deletion'));
+ };
+
+ xhr.ontimeout = function() {
+ console.error('Request timeout during user deletion');
+ reject(new Error('Request timeout during user deletion'));
+ };
+
+ // Send the request
+ xhr.send();
+ console.log('Delete request sent for user ID:', userId);
+ });
+}
+
+/**
+ * Find a user's numeric ID by their username
+ * @param {string} username - The username to look up
+ * @param {function} callback - Callback function that receives the numeric ID or null if not found
+ */
+function findUserIdByUsername(username, callback) {
+ console.log('=== FIND USER ID BY USERNAME STARTED ===');
+ console.log('Looking up user ID for username:', username);
+
+ // Get the token
+ const token = localStorage.getItem('auth_token');
+ if (!token) {
+ console.error('Authentication token is missing');
+ callback(null);
+ return;
+ }
+
+ // Fetch the list of users
+ fetch('/api/admin/users', {
+ method: 'GET',
+ headers: {
+ 'Authorization': `Bearer ${token}`,
+ 'Content-Type': 'application/json',
+ 'Accept': 'application/json'
+ }
+ })
+ .then(response => {
+ if (!response.ok) {
+ console.error('Failed to fetch users list:', response.status);
+ callback(null);
+ return null;
+ }
+ return response.json();
+ })
+ .then(users => {
+ if (!users) {
+ callback(null);
+ return;
+ }
+
+ console.log('Fetched users list:', users);
+
+ // Find the user with the matching username
+ const user = users.find(u => u.username === username);
+
+ if (user) {
+ console.log('Found user:', user);
+ callback(user.id);
+ } else {
+ console.error('User not found with username:', username);
+ callback(null);
+ }
+ })
+ .catch(error => {
+ console.error('Error fetching users:', error);
+ callback(null);
+ });
+
+ console.log('=== FIND USER ID BY USERNAME COMPLETED ===');
+}
+
+/**
+ * Check admin permissions
+ */
+function checkAdminPermissions() {
+ console.log('=== CHECK ADMIN PERMISSIONS STARTED ===');
+
+ // Get the token
+ const token = localStorage.getItem('auth_token');
+ if (!token) {
+ alert('Error: Authentication token is missing');
+ return;
+ }
+
+ // Get the current user info
+ const userInfo = JSON.parse(localStorage.getItem('user_info') || '{}');
+ console.log('Current user info:', userInfo);
+
+ // Check if the user is an admin
+ if (userInfo.is_admin) {
+ console.log('User is an admin');
+ alert('You are an admin user');
+ } else {
+ console.log('User is not an admin');
+ alert('You are not an admin user');
+ }
+
+ // Make a request to the admin endpoint to verify permissions
+ fetch('/api/admin/users', {
+ method: 'GET',
+ headers: {
+ 'Authorization': `Bearer ${token}`,
+ 'Content-Type': 'application/json'
+ }
+ })
+ .then(response => {
+ console.log('Admin check response status:', response.status);
+
+ if (response.ok) {
+ console.log('Admin endpoint access successful');
+ alert('You have access to the admin endpoint');
+ } else {
+ console.error('Admin endpoint access failed');
+ alert('You do not have access to the admin endpoint');
+ }
+
+ return response.text().catch(() => '');
+ })
+ .then(text => {
+ console.log('Admin check response text:', text);
+ })
+ .catch(error => {
+ console.error('Admin check error:', error);
+ alert('Error checking admin permissions: ' + error.message);
+ });
+
+ console.log('=== CHECK ADMIN PERMISSIONS COMPLETED ===');
+}
+
+/**
+ * Show a list of users in the system
+ */
+function showUsersList() {
+ console.log('=== SHOW USERS LIST STARTED ===');
+
+ // Get the token
+ const token = localStorage.getItem('auth_token');
+ if (!token) {
+ alert('Error: Authentication token is missing');
+ return;
+ }
+
+ // Fetch the list of users
+ fetch('/api/admin/users', {
+ method: 'GET',
+ headers: {
+ 'Authorization': `Bearer ${token}`,
+ 'Content-Type': 'application/json'
+ }
+ })
+ .then(response => {
+ if (!response.ok) {
+ console.error('Failed to fetch users list:', response.status);
+ alert('Failed to fetch users list. Status: ' + response.status);
+ return null;
+ }
+ return response.json();
+ })
+ .then(users => {
+ if (!users) return;
+
+ console.log('Fetched users list:', users);
+
+ // Create a modal to display the users
+ const modal = document.createElement('div');
+ modal.style.position = 'fixed';
+ modal.style.top = '0';
+ modal.style.left = '0';
+ modal.style.width = '100%';
+ modal.style.height = '100%';
+ modal.style.backgroundColor = 'rgba(0, 0, 0, 0.5)';
+ modal.style.display = 'flex';
+ modal.style.justifyContent = 'center';
+ modal.style.alignItems = 'center';
+ modal.style.zIndex = '10000';
+
+ // Create the modal content
+ const modalContent = document.createElement('div');
+ modalContent.style.backgroundColor = 'white';
+ modalContent.style.padding = '20px';
+ modalContent.style.borderRadius = '5px';
+ modalContent.style.maxWidth = '80%';
+ modalContent.style.maxHeight = '80%';
+ modalContent.style.overflow = 'auto';
+
+ // Create the modal header
+ const modalHeader = document.createElement('div');
+ modalHeader.style.display = 'flex';
+ modalHeader.style.justifyContent = 'space-between';
+ modalHeader.style.alignItems = 'center';
+ modalHeader.style.marginBottom = '20px';
+
+ // Create the modal title
+ const modalTitle = document.createElement('h3');
+ modalTitle.textContent = 'Users List';
+
+ // Create the close button
+ const closeButton = document.createElement('button');
+ closeButton.textContent = '×';
+ closeButton.style.backgroundColor = 'transparent';
+ closeButton.style.border = 'none';
+ closeButton.style.fontSize = '24px';
+ closeButton.style.cursor = 'pointer';
+ closeButton.addEventListener('click', function() {
+ document.body.removeChild(modal);
+ });
+
+ // Add the title and close button to the header
+ modalHeader.appendChild(modalTitle);
+ modalHeader.appendChild(closeButton);
+
+ // Create the table
+ const table = document.createElement('table');
+ table.style.width = '100%';
+ table.style.borderCollapse = 'collapse';
+
+ // Create the table header
+ const thead = document.createElement('thead');
+ const headerRow = document.createElement('tr');
+
+ // Create the header cells
+ const headers = ['ID', 'Username', 'Email', 'Name', 'Admin', 'Active', 'Actions'];
+ headers.forEach(headerText => {
+ const th = document.createElement('th');
+ th.textContent = headerText;
+ th.style.padding = '10px';
+ th.style.textAlign = 'left';
+ th.style.borderBottom = '1px solid #ddd';
+ headerRow.appendChild(th);
+ });
+
+ thead.appendChild(headerRow);
+ table.appendChild(thead);
+
+ // Create the table body
+ const tbody = document.createElement('tbody');
+
+ // Add a row for each user
+ users.forEach(user => {
+ const row = document.createElement('tr');
+
+ // Create cells for each property
+ const idCell = document.createElement('td');
+ idCell.textContent = user.id;
+ idCell.style.padding = '10px';
+ idCell.style.borderBottom = '1px solid #ddd';
+
+ const usernameCell = document.createElement('td');
+ usernameCell.textContent = user.username;
+ usernameCell.style.padding = '10px';
+ usernameCell.style.borderBottom = '1px solid #ddd';
+
+ const emailCell = document.createElement('td');
+ emailCell.textContent = user.email;
+ emailCell.style.padding = '10px';
+ emailCell.style.borderBottom = '1px solid #ddd';
+
+ const nameCell = document.createElement('td');
+ nameCell.textContent = `${user.first_name || ''} ${user.last_name || ''}`.trim() || '-';
+ nameCell.style.padding = '10px';
+ nameCell.style.borderBottom = '1px solid #ddd';
+
+ const adminCell = document.createElement('td');
+ adminCell.textContent = user.is_admin ? 'Yes' : 'No';
+ adminCell.style.padding = '10px';
+ adminCell.style.borderBottom = '1px solid #ddd';
+
+ const activeCell = document.createElement('td');
+ activeCell.textContent = user.is_active ? 'Yes' : 'No';
+ activeCell.style.padding = '10px';
+ activeCell.style.borderBottom = '1px solid #ddd';
+
+ const actionsCell = document.createElement('td');
+ actionsCell.style.padding = '10px';
+ actionsCell.style.borderBottom = '1px solid #ddd';
+
+ // Create a delete button
+ const deleteButton = document.createElement('button');
+ deleteButton.textContent = 'Delete';
+ deleteButton.style.backgroundColor = '#dc3545';
+ deleteButton.style.color = 'white';
+ deleteButton.style.border = 'none';
+ deleteButton.style.padding = '5px 10px';
+ deleteButton.style.borderRadius = '3px';
+ deleteButton.style.cursor = 'pointer';
+
+ // Don't allow deleting the current user
+ const currentUser = JSON.parse(localStorage.getItem('user_info') || '{}');
+ if (user.id === currentUser.id) {
+ deleteButton.disabled = true;
+ deleteButton.style.opacity = '0.5';
+ deleteButton.style.cursor = 'not-allowed';
+ deleteButton.title = 'Cannot delete yourself';
+ } else {
+ deleteButton.addEventListener('click', function() {
+ if (confirm(`Are you sure you want to delete user ${user.username} (ID: ${user.id})?`)) {
+ document.body.removeChild(modal);
+
+ // First check if the user still exists
+ const checkingToast = showToast(`Checking if user ${user.username} still exists...`, 'info', 0);
+
+ checkUserExists(user.id)
+ .then(existingUser => {
+ checkingToast.remove();
+
+ if (!existingUser) {
+ showToast(`User ${user.username} no longer exists`, 'warning');
+ showUsersList(); // Refresh the list
+ return;
+ }
+
+ // User exists, proceed with deletion
+ testUserDeletion(user.id);
+ })
+ .catch(error => {
+ checkingToast.remove();
+ console.error('Error checking if user exists:', error);
+ showToast('Error checking if user exists: ' + error.message, 'error');
+
+ // Ask if they want to try deletion anyway
+ if (confirm(`Error checking if user ${user.username} exists. Try deletion anyway?`)) {
+ testUserDeletion(user.id);
+ } else {
+ showUsersList(); // Refresh the list
+ }
+ });
+ }
+ });
+ }
+
+ actionsCell.appendChild(deleteButton);
+
+ // Add all cells to the row
+ row.appendChild(idCell);
+ row.appendChild(usernameCell);
+ row.appendChild(emailCell);
+ row.appendChild(nameCell);
+ row.appendChild(adminCell);
+ row.appendChild(activeCell);
+ row.appendChild(actionsCell);
+
+ // Add the row to the table body
+ tbody.appendChild(row);
+ });
+
+ table.appendChild(tbody);
+
+ // Add the header and table to the modal content
+ modalContent.appendChild(modalHeader);
+ modalContent.appendChild(table);
+
+ // Add the modal content to the modal
+ modal.appendChild(modalContent);
+
+ // Add the modal to the page
+ document.body.appendChild(modal);
+
+ console.log('Users list displayed');
+ })
+ .catch(error => {
+ console.error('Error fetching users:', error);
+ alert('Error fetching users: ' + error.message);
+ });
+
+ console.log('=== SHOW USERS LIST COMPLETED ===');
+}
+
+// Add the test API buttons when the page loads
+document.addEventListener('DOMContentLoaded', function() {
+ // Add the test API buttons after a short delay to ensure the page is fully loaded
+ setTimeout(addTestApiButtons, 1000);
+});
+
+/**
+ * Promise-based version of findUserIdByUsername
+ * @param {string} username - The username to look up
+ * @returns {Promise<number|null>} - Promise that resolves to the user ID or null if not found
+ */
+function findUserIdByUsernameAsync(username) {
+ return new Promise((resolve) => {
+ findUserIdByUsername(username, resolve);
+ });
+}
+
+/**
+ * Check if a user exists by ID or username
+ * @param {string|number} userIdOrUsername - The user ID or username to check
+ * @returns {Promise<Object|null>} - Promise that resolves to the user object if found, null otherwise
+ */
+function checkUserExists(userIdOrUsername) {
+ console.log('=== CHECK USER EXISTS STARTED ===');
+ console.log('Checking if user exists:', userIdOrUsername);
+
+ return new Promise((resolve, reject) => {
+ // Get the token
+ const token = localStorage.getItem('auth_token');
+ if (!token) {
+ console.error('Authentication token is missing');
+ reject(new Error('Authentication token is missing'));
+ return;
+ }
+
+ // Fetch the list of users
+ fetch('/api/admin/users', {
+ method: 'GET',
+ headers: {
+ 'Authorization': `Bearer ${token}`,
+ 'Content-Type': 'application/json',
+ 'Accept': 'application/json'
+ }
+ })
+ .then(response => {
+ if (!response.ok) {
+ console.error('Failed to fetch users list:', response.status);
+ reject(new Error(`Failed to fetch users list: ${response.status}`));
+ return null;
+ }
+ return response.json();
+ })
+ .then(users => {
+ if (!users) {
+ resolve(null);
+ return;
+ }
+
+ console.log('Fetched users list for checking existence');
+
+ // Check if the input is a numeric ID
+ if (!isNaN(userIdOrUsername)) {
+ // Convert to number for comparison
+ const userId = Number(userIdOrUsername);
+ const user = users.find(u => u.id === userId);
+
+ if (user) {
+ console.log('Found user by ID:', user);
+ resolve(user);
+ } else {
+ console.log('User not found with ID:', userId);
+ resolve(null);
+ }
+ } else {
+ // Assume it's a username
+ const user = users.find(u => u.username === userIdOrUsername);
+
+ if (user) {
+ console.log('Found user by username:', user);
+ resolve(user);
+ } else {
+ console.log('User not found with username:', userIdOrUsername);
+ resolve(null);
+ }
+ }
+ })
+ .catch(error => {
+ console.error('Error checking if user exists:', error);
+ reject(error);
+ });
+ });
+}
+
+/**
+ * Test user deletion functionality
+ * @param {string|number} userId - The user ID or username to delete
+ */
+function testUserDeletion(userId) {
+ console.log('=== TEST USER DELETION STARTED ===');
+ console.log('Attempting to delete user:', userId);
+
+ // Check if we have a valid user ID
+ if (!userId) {
+ console.error('No user ID provided');
+ alert('Error: No user ID provided');
+ return;
+ }
+
+ // Show a loading indicator
+ const loadingToast = showToast('Checking user...', 'info', 0); // 0 means no auto-hide
+
+ // First check if the user exists
+ checkUserExists(userId)
+ .then(user => {
+ if (!user) {
+ loadingToast.remove();
+ showToast(`User with ID/username "${userId}" not found`, 'error');
+ return;
+ }
+
+ // Update the loading toast
+ loadingToast.remove();
+ const deletingToast = showToast(`Deleting user ${user.username} (ID: ${user.id})...`, 'info', 0);
+
+ // Use our improved deletion function with the numeric ID
+ return superEmergencyDelete(user.id)
+ .then(success => {
+ // Hide the loading toast
+ if (deletingToast) {
+ deletingToast.remove();
+ }
+
+ if (success) {
+ console.log('User deletion successful');
+ showToast(`User ${user.username} deleted successfully!`, 'success');
+
+ // Refresh the users list if it's currently displayed
+ const usersModal = document.querySelector('div[style*="z-index: 10000"]');
+ if (usersModal) {
+ document.body.removeChild(usersModal);
+ setTimeout(() => {
+ showUsersList();
+ }, 500);
+ }
+ } else {
+ console.error('User deletion failed');
+ showToast(`Failed to delete user ${user.username}. Check console for details.`, 'error');
+
+ // Offer to try direct API call
+ if (confirm(`Would you like to try a direct API call to delete user ${user.username}?`)) {
+ const directToast = showToast(`Trying direct API call for user ${user.username}...`, 'info', 0);
+
+ directDeleteUserAPI(user.id)
+ .then(directSuccess => {
+ directToast.remove();
+
+ if (directSuccess) {
+ showToast(`User ${user.username} deleted successfully with direct API call!`, 'success');
+
+ // Refresh the users list if it's currently displayed
+ const usersModal = document.querySelector('div[style*="z-index: 10000"]');
+ if (usersModal) {
+ document.body.removeChild(usersModal);
+ setTimeout(() => {
+ showUsersList();
+ }, 500);
+ }
+ } else {
+ showToast(`Failed to delete user ${user.username} with direct API call.`, 'error');
+ }
+ })
+ .catch(error => {
+ directToast.remove();
+ console.error('Error with direct API call:', error);
+ showToast('Error with direct API call: ' + error.message, 'error');
+ });
+ }
+ }
+ })
+ .catch(error => {
+ // Hide the loading toast
+ if (deletingToast) {
+ deletingToast.remove();
+ }
+
+ console.error('Error during user deletion:', error);
+ showToast('Error during user deletion: ' + error.message, 'error');
+ });
+ })
+ .catch(error => {
+ loadingToast.remove();
+ console.error('Error checking if user exists:', error);
+ showToast('Error checking if user exists: ' + error.message, 'error');
+ });
+
+ console.log('=== TEST USER DELETION COMPLETED ===');
+}
+
+/**
+ * Close all modals
+ */
+function closeAllModals() {
+ console.log('Closing all modals');
+
+ // Get all modals
+ const modals = document.querySelectorAll('.modal-backdrop');
+
+ // Close each modal
+ modals.forEach(modal => {
+ console.log('Closing modal:', modal.id);
+ modal.style.display = 'none';
+ });
+
+ // Also reset any form fields
+ if (deleteConfirmInput) {
+ deleteConfirmInput.value = '';
+ if (confirmDeleteAccountBtn) {
+ confirmDeleteAccountBtn.disabled = true;
+ }
+ }
+
+ // Reset password form
+ resetPasswordForm();
+
+ console.log('All modals closed');
+}
+
+/**
+ * Load site settings
+ */
+async function loadSiteSettings() {
+ showLoading();
+
+ try {
+ const response = await fetch('/api/admin/settings', {
+ method: 'GET',
+ headers: {
+ 'Authorization': `Bearer ${window.auth.getToken()}`
+ }
+ });
+
+ if (response.ok) {
+ const settings = await response.json();
+
+ // Update form fields
+ if (registrationEnabled) {
+ registrationEnabled.checked = settings.registration_enabled === 'true';
+ }
+ } else {
+ const errorData = await response.json();
+ console.warn('API error:', errorData.message);
+ }
+ } catch (error) {
+ console.error('Error loading site settings:', error);
+ showToast('Failed to load site settings. Please try again.', 'error');
+ } finally {
+ hideLoading();
+ }
+}
+
+/**
+ * Save site settings
+ */
+async function saveSiteSettings() {
+ showLoading();
+
+ try {
+ const response = await fetch('/api/admin/settings', {
+ method: 'PUT',
+ headers: {
+ 'Authorization': `Bearer ${window.auth.getToken()}`,
+ 'Content-Type': 'application/json'
+ },
+ body: JSON.stringify({
+ registration_enabled: registrationEnabled ? registrationEnabled.checked : false
+ })
+ });
+
+ if (response.ok) {
+ showToast('Site settings saved successfully', 'success');
+ } else {
+ const errorData = await response.json();
+ showToast(errorData.message || 'Failed to save site settings', 'error');
+ }
+ } catch (error) {
+ console.error('Error saving site settings:', error);
+ showToast('Failed to save site settings. Please try again.', 'error');
+ } finally {
+ hideLoading();
+ }
+}
+
+/**
+ * Add test API buttons to the page
+ */
+function addTestApiButtons() {
+ console.log('Test API buttons function called but disabled');
+ // Function disabled to prevent floating buttons from appearing
+ // The functionality is now available through the admin action buttons in the Admin Settings section
+ return;
+
+ // Original code below is kept for reference but will not execute due to the return above
+ console.log('Adding test API buttons to the page');
+
+ // Create a container for the buttons
+ const buttonContainer = document.createElement('div');
+ buttonContainer.style.position = 'fixed';
+ buttonContainer.style.bottom = '20px';
+ buttonContainer.style.right = '20px';
+ buttonContainer.style.zIndex = '9999';
+ buttonContainer.style.display = 'flex';
+ buttonContainer.style.flexDirection = 'column';
+ buttonContainer.style.gap = '10px';
+
+ // Create a button to check API endpoint
+ const apiCheckBtn = document.createElement('button');
+ apiCheckBtn.className = 'btn btn-info';
+ apiCheckBtn.textContent = 'Check API Endpoint';
+ apiCheckBtn.addEventListener('click', checkApiEndpoint);
+
+ // Create a button to test user deletion
+ const testDeleteBtn = document.createElement('button');
+ testDeleteBtn.className = 'btn btn-danger';
+ testDeleteBtn.textContent = 'Test User Deletion';
+ testDeleteBtn.addEventListener('click', function() {
+ const userId = prompt('Enter user ID to delete:');
+ if (userId) {
+ if (confirm(`Are you sure you want to delete user ID ${userId}?`)) {
+ testUserDeletion(userId);
+ }
+ }
+ });
+
+ // Create a button to check permissions
+ const checkPermissionsBtn = document.createElement('button');
+ checkPermissionsBtn.className = 'btn btn-warning';
+ checkPermissionsBtn.textContent = 'Check Admin Permissions';
+ checkPermissionsBtn.addEventListener('click', checkAdminPermissions);
+
+ // Create a button to show users
+ const showUsersBtn = document.createElement('button');
+ showUsersBtn.className = 'btn btn-primary';
+ showUsersBtn.textContent = 'Show Users';
+ showUsersBtn.addEventListener('click', showUsersList);
+
+ // Add buttons to the container
+ buttonContainer.appendChild(apiCheckBtn);
+ buttonContainer.appendChild(testDeleteBtn);
+ buttonContainer.appendChild(checkPermissionsBtn);
+ buttonContainer.appendChild(showUsersBtn);
+
+ // Add the container to the body
+ document.body.appendChild(buttonContainer);
+
+ console.log('Test API buttons added to the page');
+}
+
+/**
+ * Check if the API endpoint is accessible
+ */
+function checkApiEndpoint() {
+ console.log('Checking API endpoint accessibility...');
+
+ // Try to access a simple API endpoint
+ fetch('/api/auth/validate-token', {
+ method: 'GET',
+ headers: {
+ 'Authorization': `Bearer ${window.auth.getToken()}`
+ }
+ })
+ .then(response => {
+ console.log('API endpoint check response status:', response.status);
+ if (response.ok) {
+ console.log('API endpoint is accessible');
+ showToast('API endpoint is accessible', 'success');
+ } else {
+ console.error('API endpoint is not accessible');
+ showToast('API endpoint is not accessible. Status: ' + response.status, 'error');
+ }
+ return response.json().catch(() => ({}));
+ })
+ .then(data => {
+ console.log('API endpoint check response data:', data);
+ })
+ .catch(error => {
+ console.error('Error checking API endpoint:', error);
+ showToast('Error checking API endpoint: ' + error.message, 'error');
+ });
+}
+
+/**
+ * Set up the delete button for user deletion
+ */
+function setupDeleteButton() {
+ console.log('=== SETUP DELETE BUTTON STARTED ===');
+
+ // Get the confirm delete button
+ const confirmDeleteUserBtn = document.getElementById('confirmDeleteUserBtn');
+ if (!confirmDeleteUserBtn) {
+ console.error('confirmDeleteUserBtn not found in setupDeleteButton');
+ return;
+ }
+
+ try {
+ // Get the user ID from various possible sources
+ let userId = window.currentDeleteUserId || null;
+
+ if (!userId && document.getElementById('deleteUserId')) {
+ userId = document.getElementById('deleteUserId').value;
+ }
+
+ if (!userId && document.getElementById('editUserId')) {
+ userId = document.getElementById('editUserId').value;
+ }
+
+ if (!userId && document.getElementById('displayUserId')) {
+ userId = document.getElementById('displayUserId').textContent;
+ }
+
+ console.log('Setting up delete button for user ID:', userId);
+
+ // Remove existing event listeners by cloning
+ const newBtn = confirmDeleteUserBtn.cloneNode(true);
+ confirmDeleteUserBtn.parentNode.replaceChild(newBtn, confirmDeleteUserBtn);
+
+ // Add new event listener
+ newBtn.addEventListener('click', function(e) {
+ e.preventDefault();
+ e.stopPropagation();
+ console.log('Delete button clicked in setupDeleteButton');
+ deleteUser();
+ return false;
+ });
+
+ // Also set onclick for redundancy
+ newBtn.onclick = function(e) {
+ e.preventDefault();
+ e.stopPropagation();
+ console.log('Delete button clicked via onclick in setupDeleteButton');
+ deleteUser();
+ return false;
+ };
+
+ console.log('Delete button set up successfully');
+ } catch (error) {
+ console.error('Error setting up delete button:', error);
+ }
+
+ console.log('=== SETUP DELETE BUTTON COMPLETED ===');
+}
+
+/**
+ * Direct API call for user deletion
+ * @param {string|number} userId - The user ID or username to delete
+ * @returns {Promise<boolean>} - Promise that resolves to true if deletion was successful, false otherwise
+ */
+function directDeleteUserAPI(userId) {
+ console.log('=== DIRECT DELETE API CALL STARTED ===');
+ console.log('Function caller:', arguments.callee.caller ? arguments.callee.caller.name : 'unknown');
+
+ return new Promise((resolve, reject) => {
+ // Try to get the user ID from multiple sources if not provided
+ if (!userId) {
+ const deleteUserIdField = document.getElementById('deleteUserId');
+ const editUserIdField = document.getElementById('editUserId');
+ const displayUserIdField = document.getElementById('displayUserId');
+
+ userId = window.currentDeleteUserId;
+
+ if (!userId && deleteUserIdField && deleteUserIdField.value) {
+ userId = deleteUserIdField.value;
+ } else if (!userId && editUserIdField && editUserIdField.value) {
+ userId = editUserIdField.value;
+ } else if (!userId && displayUserIdField && displayUserIdField.textContent) {
+ userId = displayUserIdField.textContent;
+ }
+ }
+
+ console.log('User ID to delete:', userId);
+
+ if (!userId) {
+ console.error('Direct delete API call failed: User ID is missing');
+ reject(new Error('User ID is missing'));
+ return;
+ }
+
+ // Check if the input is a username rather than a numeric ID
+ if (isNaN(userId)) {
+ console.log('Input appears to be a username, not a numeric ID');
+ // Try to find the user ID by username
+ findUserIdByUsernameAsync(userId)
+ .then(numericId => {
+ if (numericId) {
+ console.log(`Found numeric ID ${numericId} for username ${userId}`);
+ // Call this function again with the numeric ID
+ return directDeleteUserAPI(numericId);
+ } else {
+ throw new Error(`Could not find a user with username "${userId}"`);
+ }
+ })
+ .then(resolve)
+ .catch(reject);
+ return;
+ }
+
+ console.log('Proceeding with numeric user ID:', userId);
+
+ // Get the token with detailed logging
+ const token = localStorage.getItem('auth_token');
+ console.log('Token exists:', !!token);
+ console.log('Token length:', token ? token.length : 0);
+
+ if (!token) {
+ console.error('Authentication token is missing');
+ reject(new Error('Authentication token is missing'));
+ return;
+ }
+
+ // Log the API endpoint
+ const apiEndpoint = `/api/admin/users/${userId}`;
+ console.log('Direct API endpoint:', apiEndpoint);
+
+ // Create headers with detailed logging
+ const headers = {
+ 'Authorization': `Bearer ${token}`,
+ 'Content-Type': 'application/json',
+ 'Accept': 'application/json'
+ };
+ console.log('Direct API request headers:', Object.keys(headers));
+
+ // Make the fetch request with detailed logging
+ console.log('Direct API fetch request configuration:', {
+ method: 'DELETE',
+ headers: Object.keys(headers),
+ credentials: 'same-origin'
+ });
+
+ // Make a fetch API call
+ fetch(apiEndpoint, {
+ method: 'DELETE',
+ headers: headers,
+ credentials: 'same-origin' // Include cookies
+ })
+ .then(response => {
+ console.log('Direct API response received');
+ console.log('Direct API response status:', response.status);
+ console.log('Direct API response status text:', response.statusText);
+ console.log('Direct API response headers:', [...response.headers.entries()]);
+ console.log('Direct API response type:', response.type);
+ console.log('Direct API response URL:', response.url);
+
+ // Get the raw text first
+ return response.text().then(text => {
+ console.log('Direct API raw response text:', text);
+ try {
+ const data = text ? JSON.parse(text) : {};
+ return {
+ status: response.status,
+ data: data
+ };
+ } catch (err) {
+ console.log('Error parsing Direct API JSON response:', err);
+ return {
+ status: response.status,
+ data: { message: text || 'No response data or invalid JSON' }
+ };
+ }
+ });
+ })
+ .then(result => {
+ console.log('Direct API response data:', result);
+
+ if (result.status >= 200 && result.status < 300) {
+ console.log('Direct API call successful');
+ resolve(true);
+ } else {
+ const errorMessage = result.data && result.data.message ? result.data.message : 'Failed to delete user';
+ console.error('Direct API call failed:', errorMessage);
+ resolve(false); // Resolve with false instead of rejecting
+ }
+ })
+ .catch(error => {
+ console.error('Direct API call error:', error);
+ console.error('Direct API call error details:', error.message, error.stack);
+ reject(error);
+ });
+ });
+}
\ No newline at end of file
diff --git a/frontend/settings-redirect.html b/frontend/settings-redirect.html
new file mode 100644
index 0000000..aa8bdf1
--- /dev/null
+++ b/frontend/settings-redirect.html
@@ -0,0 +1,50 @@
+<!DOCTYPE html>
+<html lang="en">
+<head>
+ <meta charset="UTF-8">
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
+ <meta http-equiv="refresh" content="0;url=settings-new.html">
+ <title>Redirecting to Settings</title>
+ <style>
+ body {
+ font-family: Arial, sans-serif;
+ text-align: center;
+ padding: 50px;
+ background-color: #f5f5f5;
+ }
+ .container {
+ max-width: 600px;
+ margin: 0 auto;
+ background-color: white;
+ padding: 30px;
+ border-radius: 8px;
+ box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
+ }
+ h1 {
+ color: #333;
+ }
+ p {
+ color: #666;
+ margin-bottom: 20px;
+ }
+ a {
+ color: #007bff;
+ text-decoration: none;
+ }
+ a:hover {
+ text-decoration: underline;
+ }
+ </style>
+</head>
+<body>
+ <div class="container">
+ <h1>Redirecting to Settings</h1>
+ <p>You are being redirected to the new settings page.</p>
+ <p>If you are not redirected automatically, <a href="settings-new.html">click here</a>.</p>
+ </div>
+ <script>
+ // JavaScript redirect as a fallback
+ window.location.href = "settings-new.html";
+ </script>
+</body>
+</html>
\ No newline at end of file
diff --git a/frontend/settings-styles.css b/frontend/settings-styles.css
new file mode 100644
index 0000000..e05326e
--- /dev/null
+++ b/frontend/settings-styles.css
@@ -0,0 +1,933 @@
+/* Settings Page Styles */
+:root {
+ --text-secondary: var(--dark-gray);
+ --input-bg: var(--card-bg);
+ --text-muted: #6c757d;
+ --hover-bg: rgba(0, 0, 0, 0.05);
+}
+
+body {
+ background-color: var(--bg-color);
+ color: var(--text-color);
+ font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
+ line-height: 1.6;
+ transition: background-color 0.3s ease, color 0.3s ease;
+}
+
+/* Header Styles */
+header {
+ background-color: var(--card-bg);
+ box-shadow: var(--shadow);
+ padding: 20px 0;
+ margin-bottom: 30px;
+}
+
+header .container {
+ display: flex;
+ justify-content: space-between;
+ align-items: center;
+}
+
+.app-title {
+ display: flex;
+ align-items: center;
+}
+
+.app-title h1 {
+ color: var(--primary-color);
+ font-size: 2.2rem;
+ margin: 0;
+}
+
+.app-title i {
+ font-size: 2rem;
+ margin-right: 15px;
+ color: var(--primary-color);
+}
+
+/* Navigation Links */
+.nav-links {
+ display: flex;
+ gap: 20px;
+ margin: 0 20px;
+}
+
+.nav-link {
+ text-decoration: none;
+ color: var(--text-color);
+ padding: 8px 12px;
+ border-radius: 4px;
+ transition: background-color 0.3s;
+ display: flex;
+ align-items: center;
+ gap: 8px;
+}
+
+.nav-link:hover {
+ background-color: rgba(0, 0, 0, 0.05);
+}
+
+.nav-link.active {
+ background-color: rgba(0, 0, 0, 0.05);
+ font-weight: 600;
+}
+
+.nav-link i {
+ font-size: 1rem;
+}
+
+/* Settings Button */
+.settings-container {
+ position: relative;
+ margin-left: 10px;
+}
+
+.settings-btn {
+ background: none;
+ border: none;
+ color: var(--text-color);
+ font-size: 1.2rem;
+ cursor: pointer;
+ width: 40px;
+ height: 40px;
+ border-radius: 50%;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ transition: background-color 0.3s;
+}
+
+.settings-btn:hover {
+ background-color: rgba(0, 0, 0, 0.05);
+}
+
+.dark-mode .settings-btn:hover {
+ background-color: rgba(255, 255, 255, 0.1);
+}
+
+.settings-menu {
+ position: absolute;
+ top: 100%;
+ right: 0;
+ background-color: var(--card-bg);
+ border-radius: 8px;
+ box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
+ width: 200px;
+ z-index: 1000;
+ display: none;
+ padding: 10px 0;
+ margin-top: 5px;
+}
+
+.settings-menu.active {
+ display: block;
+}
+
+.settings-item {
+ padding: 10px 15px;
+ display: flex;
+ justify-content: space-between;
+ align-items: center;
+ border-bottom: 1px solid var(--border-color);
+}
+
+.settings-item:last-child {
+ border-bottom: none;
+}
+
+.settings-link {
+ color: var(--text-color);
+ text-decoration: none;
+ display: flex;
+ align-items: center;
+ width: 100%;
+ transition: color 0.3s;
+}
+
+.settings-link:hover {
+ color: var(--primary-color);
+}
+
+.settings-link i {
+ margin-right: 10px;
+ width: 16px;
+ text-align: center;
+}
+
+.github-link {
+ color: var(--text-color);
+}
+
+.github-link:hover {
+ color: #6e5494;
+}
+
+/* Content Styles */
+.content-wrapper {
+ max-width: 800px;
+ margin: 0 auto;
+ padding: 20px 0;
+}
+
+.content-wrapper h2 {
+ margin-bottom: 20px;
+ color: var(--primary-color);
+ font-weight: 600;
+}
+
+.settings-container {
+ max-width: 800px;
+ margin: 0 auto;
+ padding: 20px;
+}
+
+.settings-section {
+ background-color: var(--card-bg);
+ border-radius: 10px;
+ padding: 20px;
+ margin-bottom: 20px;
+ box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
+}
+
+.settings-section h3 {
+ margin-top: 0;
+ padding-bottom: 10px;
+ border-bottom: 1px solid var(--border-color);
+ color: var(--primary-color);
+}
+
+.settings-option {
+ display: flex;
+ justify-content: space-between;
+ align-items: center;
+ padding: 15px 0;
+ border-bottom: 1px solid var(--border-color);
+}
+
+.settings-option:last-child {
+ border-bottom: none;
+}
+
+.option-label {
+ display: flex;
+ flex-direction: column;
+}
+
+.option-title {
+ font-weight: 600;
+ margin-bottom: 5px;
+}
+
+.option-description {
+ font-size: 0.9rem;
+ color: var(--text-secondary);
+}
+
+.settings-form {
+ margin-top: 15px;
+}
+
+.form-row {
+ margin-bottom: 15px;
+}
+
+.form-row label {
+ display: block;
+ margin-bottom: 5px;
+ font-weight: 500;
+}
+
+.form-row input {
+ width: 100%;
+ padding: 10px;
+ border: 1px solid var(--border-color);
+ border-radius: 5px;
+ background-color: var(--input-bg);
+ color: var(--text-color);
+}
+
+/* Toggle switch */
+.switch {
+ position: relative;
+ display: inline-block;
+ width: 50px;
+ height: 24px;
+}
+
+.switch input {
+ opacity: 0;
+ width: 0;
+ height: 0;
+}
+
+.slider {
+ position: absolute;
+ cursor: pointer;
+ top: 0;
+ left: 0;
+ right: 0;
+ bottom: 0;
+ background-color: #ccc;
+ transition: .4s;
+ border-radius: 24px;
+}
+
+.slider:before {
+ position: absolute;
+ content: "";
+ height: 16px;
+ width: 16px;
+ left: 4px;
+ bottom: 4px;
+ background-color: white;
+ transition: .4s;
+ border-radius: 50%;
+}
+
+input:checked + .slider {
+ background-color: var(--primary-color);
+}
+
+input:checked + .slider:before {
+ transform: translateX(26px);
+}
+
+/* Responsive */
+@media (max-width: 768px) {
+ .settings-option {
+ flex-direction: column;
+ align-items: flex-start;
+ }
+
+ .option-label {
+ margin-bottom: 10px;
+ }
+}
+
+/* Delete account modal */
+.delete-account-warning {
+ color: #dc3545;
+ font-weight: 600;
+ margin-bottom: 15px;
+}
+
+.delete-confirm-input {
+ margin: 15px 0;
+ width: 100%;
+ padding: 10px;
+ border: 1px solid var(--border-color);
+ border-radius: 5px;
+ background-color: var(--input-bg);
+ color: var(--text-color);
+}
+
+/* Form select styling */
+.form-select {
+ width: 100%;
+ padding: 10px;
+ border: 1px solid var(--border-color);
+ border-radius: 5px;
+ background-color: var(--input-bg);
+ color: var(--text-color);
+ appearance: none;
+ -webkit-appearance: none;
+ -moz-appearance: none;
+ background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='12' height='12' fill='%23333' viewBox='0 0 16 16'%3E%3Cpath d='M7.247 11.14 2.451 5.658C1.885 5.013 2.345 4 3.204 4h9.592a1 1 0 0 1 .753 1.659l-4.796 5.48a1 1 0 0 1-1.506 0z'/%3E%3C/svg%3E");
+ background-repeat: no-repeat;
+ background-position: right 10px center;
+ padding-right: 30px;
+}
+
+.form-select:focus {
+ outline: none;
+ border-color: var(--primary-color);
+}
+
+/* Text center utility */
+.text-center {
+ text-align: center;
+}
+
+/* Danger zone */
+.danger-zone {
+ background-color: rgba(255, 0, 0, 0.05);
+}
+
+.dark-mode .danger-zone {
+ background-color: rgba(255, 0, 0, 0.1);
+}
+
+/* Button styles */
+.btn {
+ display: inline-block;
+ font-weight: 500;
+ text-align: center;
+ white-space: nowrap;
+ vertical-align: middle;
+ user-select: none;
+ border: 1px solid transparent;
+ padding: 0.375rem 0.75rem;
+ font-size: 1rem;
+ line-height: 1.5;
+ border-radius: 0.25rem;
+ transition: color 0.15s ease-in-out, background-color 0.15s ease-in-out, border-color 0.15s ease-in-out, box-shadow 0.15s ease-in-out;
+ cursor: pointer;
+}
+
+.btn-primary {
+ color: #fff;
+ background-color: var(--primary-color);
+ border-color: var(--primary-color);
+}
+
+.btn-primary:hover {
+ background-color: var(--primary-dark);
+ border-color: var(--primary-dark);
+}
+
+.btn-secondary {
+ color: #fff;
+ background-color: var(--dark-gray);
+ border-color: var(--dark-gray);
+}
+
+.btn-secondary:hover {
+ background-color: #5a6268;
+ border-color: #545b62;
+}
+
+.btn-danger {
+ color: #fff;
+ background-color: var(--danger-color);
+ border-color: var(--danger-color);
+}
+
+.btn-danger:hover {
+ background-color: #c82333;
+ border-color: #bd2130;
+}
+
+.btn-outline {
+ color: var(--primary-color);
+ background-color: transparent;
+ border-color: var(--primary-color);
+}
+
+.btn-outline:hover {
+ color: #fff;
+ background-color: var(--primary-color);
+ border-color: var(--primary-color);
+}
+
+/* Form control */
+.form-control {
+ display: block;
+ width: 100%;
+ padding: 0.375rem 0.75rem;
+ font-size: 1rem;
+ line-height: 1.5;
+ color: var(--text-color);
+ background-color: var(--input-bg);
+ background-clip: padding-box;
+ border: 1px solid var(--border-color);
+ border-radius: 0.25rem;
+ transition: border-color 0.15s ease-in-out, box-shadow 0.15s ease-in-out;
+}
+
+.form-control:focus {
+ color: var(--text-color);
+ background-color: var(--input-bg);
+ border-color: var(--primary-color);
+ outline: 0;
+ box-shadow: 0 0 0 0.2rem rgba(0, 123, 255, 0.25);
+}
+
+.form-control:disabled {
+ background-color: var(--light-gray);
+ opacity: 0.7;
+}
+
+/* Modal styles */
+.modal-backdrop {
+ position: fixed;
+ top: 0;
+ left: 0;
+ width: 100%;
+ height: 100%;
+ background-color: var(--modal-backdrop);
+ display: none;
+ justify-content: center;
+ align-items: center;
+ z-index: 1000;
+}
+
+.modal {
+ background-color: var(--card-bg);
+ border-radius: 8px;
+ box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
+ width: 90%;
+ max-width: 500px;
+ max-height: 90vh;
+ overflow-y: auto;
+ position: relative;
+}
+
+.modal-header {
+ padding: 15px 20px;
+ border-bottom: 1px solid var(--border-color);
+ display: flex;
+ justify-content: space-between;
+ align-items: center;
+}
+
+.modal-title {
+ margin: 0;
+ font-size: 1.25rem;
+ color: var(--primary-color);
+}
+
+.close-btn {
+ background: none;
+ border: none;
+ font-size: 1.5rem;
+ line-height: 1;
+ color: var(--text-color);
+ cursor: pointer;
+ opacity: 0.7;
+ transition: opacity 0.3s;
+}
+
+.close-btn:hover {
+ opacity: 1;
+}
+
+.modal-body {
+ padding: 20px;
+}
+
+.modal-footer {
+ padding: 15px 20px;
+ border-top: 1px solid var(--border-color);
+ display: flex;
+ justify-content: flex-end;
+ gap: 10px;
+}
+
+/* Card styles */
+.card {
+ background-color: var(--card-bg);
+ border-radius: 10px;
+ box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
+ margin-bottom: 20px;
+ overflow: hidden;
+}
+
+.card-header {
+ padding: 15px 20px;
+ border-bottom: 1px solid var(--border-color);
+}
+
+.card-header h3 {
+ margin: 0;
+ color: var(--primary-color);
+ font-size: 1.25rem;
+}
+
+.card-body {
+ padding: 20px;
+}
+
+.danger-card {
+ border: 1px solid rgba(220, 53, 69, 0.2);
+}
+
+.danger-card .card-header {
+ background-color: rgba(220, 53, 69, 0.05);
+}
+
+/* Form styles */
+.form-group {
+ margin-bottom: 20px;
+}
+
+.form-group label {
+ display: block;
+ margin-bottom: 5px;
+ font-weight: 500;
+}
+
+.form-control {
+ display: block;
+ width: 100%;
+ padding: 10px;
+ font-size: 1rem;
+ line-height: 1.5;
+ color: var(--text-color);
+ background-color: var(--input-bg);
+ border: 1px solid var(--border-color);
+ border-radius: 5px;
+ transition: border-color 0.15s ease-in-out, box-shadow 0.15s ease-in-out;
+}
+
+.form-control:focus {
+ border-color: var(--primary-color);
+ outline: 0;
+ box-shadow: 0 0 0 0.2rem rgba(0, 123, 255, 0.25);
+}
+
+.form-control:disabled {
+ background-color: var(--light-gray);
+ opacity: 0.7;
+}
+
+/* Preference item */
+.preference-item {
+ display: flex;
+ justify-content: space-between;
+ align-items: center;
+ padding: 15px 0;
+ border-bottom: 1px solid var(--border-color);
+}
+
+.preference-item:last-child {
+ border-bottom: none;
+}
+
+.preference-item label {
+ font-weight: 500;
+ margin-bottom: 5px;
+}
+
+.preference-item p {
+ margin: 0;
+}
+
+.text-muted {
+ color: var(--text-muted);
+ font-size: 0.9rem;
+}
+
+.text-danger {
+ color: var(--danger-color);
+}
+
+/* Toggle switch */
+.toggle-switch {
+ position: relative;
+ display: inline-block;
+ width: 50px;
+ height: 24px;
+}
+
+.toggle-switch input {
+ opacity: 0;
+ width: 0;
+ height: 0;
+}
+
+.toggle-slider {
+ position: absolute;
+ cursor: pointer;
+ top: 0;
+ left: 0;
+ right: 0;
+ bottom: 0;
+ background-color: #ccc;
+ transition: .4s;
+ border-radius: 24px;
+}
+
+.toggle-slider:before {
+ position: absolute;
+ content: "";
+ height: 16px;
+ width: 16px;
+ left: 4px;
+ bottom: 4px;
+ background-color: white;
+ transition: .4s;
+ border-radius: 50%;
+}
+
+input:checked + .toggle-slider {
+ background-color: var(--primary-color);
+}
+
+input:checked + .toggle-slider:before {
+ transform: translateX(26px);
+}
+
+/* Button styles */
+.btn {
+ display: inline-block;
+ font-weight: 500;
+ text-align: center;
+ white-space: nowrap;
+ vertical-align: middle;
+ user-select: none;
+ border: 1px solid transparent;
+ padding: 0.375rem 0.75rem;
+ font-size: 1rem;
+ line-height: 1.5;
+ border-radius: 0.25rem;
+ transition: color 0.15s ease-in-out, background-color 0.15s ease-in-out, border-color 0.15s ease-in-out, box-shadow 0.15s ease-in-out;
+ cursor: pointer;
+}
+
+.btn-primary {
+ color: #fff;
+ background-color: var(--primary-color);
+ border-color: var(--primary-color);
+}
+
+.btn-primary:hover {
+ background-color: var(--primary-dark);
+ border-color: var(--primary-dark);
+}
+
+.btn-secondary {
+ color: #fff;
+ background-color: var(--dark-gray);
+ border-color: var(--dark-gray);
+}
+
+.btn-secondary:hover {
+ background-color: #5a6268;
+ border-color: #545b62;
+}
+
+.btn-danger {
+ color: #fff;
+ background-color: var(--danger-color);
+ border-color: var(--danger-color);
+}
+
+.btn-danger:hover {
+ background-color: #c82333;
+ border-color: #bd2130;
+}
+
+.btn-outline-primary {
+ color: var(--primary-color);
+ background-color: transparent;
+ border-color: var(--primary-color);
+}
+
+.btn-outline-primary:hover {
+ color: #fff;
+ background-color: var(--primary-color);
+ border-color: var(--primary-color);
+}
+
+.button-group {
+ display: flex;
+ gap: 10px;
+ margin-top: 15px;
+}
+
+/* Success icon */
+.success-icon {
+ font-size: 3rem;
+ color: var(--secondary-color);
+ margin-bottom: 15px;
+ display: block;
+}
+
+/* Loading Container */
+.loading-container {
+ position: fixed;
+ top: 0;
+ left: 0;
+ width: 100%;
+ height: 100%;
+ background-color: var(--loading-backdrop);
+ display: none;
+ justify-content: center;
+ align-items: center;
+ z-index: 9999;
+}
+
+.spinner {
+ width: 50px;
+ height: 50px;
+ border: 5px solid rgba(255, 255, 255, 0.3);
+ border-radius: 50%;
+ border-top-color: var(--primary-color);
+ animation: spin 1s ease-in-out infinite;
+}
+
+@keyframes spin {
+ to {
+ transform: rotate(360deg);
+ }
+}
+
+/* Toast Container */
+.toast-container {
+ position: fixed;
+ bottom: 20px;
+ right: 20px;
+ z-index: 9999;
+ display: flex;
+ flex-direction: column;
+ gap: 10px;
+}
+
+.toast {
+ display: flex;
+ align-items: center;
+ gap: 10px;
+ padding: 12px 16px;
+ border-radius: 4px;
+ box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
+ animation: toast-in 0.3s ease-out;
+ max-width: 350px;
+}
+
+.toast i {
+ font-size: 18px;
+}
+
+.toast-success {
+ background-color: #d4edda;
+ color: #155724;
+ border-left: 4px solid var(--secondary-color);
+}
+
+.toast-error {
+ background-color: #f8d7da;
+ color: #721c24;
+ border-left: 4px solid var(--danger-color);
+}
+
+.toast-warning {
+ background-color: #fff3cd;
+ color: #856404;
+ border-left: 4px solid var(--warning-color);
+}
+
+.toast-info {
+ background-color: #d1ecf1;
+ color: #0c5460;
+ border-left: 4px solid var(--primary-color);
+}
+
+.toast-fade-out {
+ animation: toast-out 0.3s ease-in forwards;
+}
+
+@keyframes toast-in {
+ from {
+ transform: translateX(100%);
+ opacity: 0;
+ }
+ to {
+ transform: translateX(0);
+ opacity: 1;
+ }
+}
+
+@keyframes toast-out {
+ from {
+ transform: translateX(0);
+ opacity: 1;
+ }
+ to {
+ transform: translateX(100%);
+ opacity: 0;
+ }
+}
+
+/* Dark mode adjustments */
+.dark-mode .form-control {
+ background-color: var(--card-bg);
+ color: var(--text-color);
+ border-color: var(--border-color);
+}
+
+.dark-mode .toast-success {
+ background-color: rgba(46, 204, 113, 0.2);
+ color: #d4edda;
+}
+
+.dark-mode .toast-error {
+ background-color: rgba(231, 76, 60, 0.2);
+ color: #f8d7da;
+}
+
+.dark-mode .toast-warning {
+ background-color: rgba(243, 156, 18, 0.2);
+ color: #fff3cd;
+}
+
+.dark-mode .toast-info {
+ background-color: rgba(52, 152, 219, 0.2);
+ color: #d1ecf1;
+}
+
+.dark-mode .spinner {
+ border-color: rgba(255, 255, 255, 0.2);
+ border-top-color: var(--primary-color);
+}
+
+/* Admin Actions Grid */
+.admin-actions-grid {
+ display: grid;
+ grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
+ gap: 20px;
+ margin-bottom: 20px;
+}
+
+.admin-action-btn {
+ display: flex;
+ flex-direction: column;
+ align-items: center;
+ justify-content: center;
+ background-color: var(--card-bg);
+ border: 1px solid var(--border-color);
+ border-radius: 8px;
+ padding: 20px;
+ transition: all 0.3s ease;
+ cursor: pointer;
+ color: var(--text-color);
+}
+
+.admin-action-btn:hover {
+ transform: translateY(-3px);
+ box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
+ border-color: var(--primary-color);
+}
+
+.admin-action-btn i {
+ font-size: 2rem;
+ margin-bottom: 10px;
+ color: var(--primary-color);
+}
+
+.admin-action-btn span {
+ font-weight: 500;
+ text-align: center;
+}
+
+/* Specific button colors */
+#refreshUsersBtn i {
+ color: #4299e1; /* Blue */
+}
+
+#checkAdminBtn i {
+ color: #4a5568; /* Gray */
+}
+
+#showUsersBtn i {
+ color: #48bb78; /* Green */
+}
+
+#testApiBtn i {
+ color: #ed8936; /* Orange */
+}
+
+@media (max-width: 576px) {
+ .admin-actions-grid {
+ grid-template-columns: 1fr;
+ }
+}
\ No newline at end of file
diff --git a/frontend/settings.js b/frontend/settings.js
new file mode 100644
index 0000000..57e7451
--- /dev/null
+++ b/frontend/settings.js
@@ -0,0 +1,522 @@
+// DOM Elements
+const darkModeToggle = document.getElementById('darkModeToggle');
+const darkModeToggleSetting = document.getElementById('darkModeToggleSetting');
+const defaultViewSelect = document.getElementById('defaultView');
+const emailNotificationsToggle = document.getElementById('emailNotifications');
+const saveProfileBtn = document.getElementById('saveProfileBtn');
+const savePreferencesBtn = document.getElementById('savePreferencesBtn');
+const changePasswordBtn = document.getElementById('changePasswordBtn');
+const passwordChangeForm = document.getElementById('passwordChangeForm');
+const savePasswordBtn = document.getElementById('savePasswordBtn');
+const cancelPasswordBtn = document.getElementById('cancelPasswordBtn');
+const deleteAccountBtn = document.getElementById('deleteAccountBtn');
+const deleteAccountModal = document.getElementById('deleteAccountModal');
+const deleteConfirmInput = document.getElementById('deleteConfirmInput');
+const confirmDeleteAccountBtn = document.getElementById('confirmDeleteAccountBtn');
+const passwordSuccessModal = document.getElementById('passwordSuccessModal');
+const loadingContainer = document.getElementById('loadingContainer');
+const toastContainer = document.getElementById('toastContainer');
+
+// Form fields
+const firstNameInput = document.getElementById('firstName');
+const lastNameInput = document.getElementById('lastName');
+const emailInput = document.getElementById('email');
+const currentPasswordInput = document.getElementById('currentPassword');
+const newPasswordInput = document.getElementById('newPassword');
+const confirmPasswordInput = document.getElementById('confirmPassword');
+
+// Initialize settings page
+document.addEventListener('DOMContentLoaded', () => {
+ // Check authentication
+ if (window.auth) {
+ window.auth.checkAuthState();
+
+ // Redirect to login if not authenticated
+ if (!window.auth.isAuthenticated()) {
+ window.location.href = 'login.html';
+ return;
+ }
+ } else {
+ // Auth module not loaded
+ console.error('Auth module not loaded');
+ window.location.href = 'login.html';
+ return;
+ }
+
+ // Load user data and preferences
+ loadUserData();
+ loadPreferences();
+
+ // Setup event listeners
+ setupEventListeners();
+
+ // Initialize modals
+ initModals();
+});
+
+/**
+ * Load user data from localStorage and API
+ */
+async function loadUserData() {
+ showLoading();
+
+ 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 || '';
+ }
+
+ // Fetch fresh user data from API
+ const response = await fetch('/api/auth/user', {
+ method: 'GET',
+ headers: {
+ '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 || '';
+
+ // Update localStorage
+ localStorage.setItem('user_info', JSON.stringify(userData));
+ } else {
+ // Handle error
+ const errorData = await response.json();
+ showToast(errorData.message || 'Failed to load user data', 'error');
+ }
+ } catch (error) {
+ console.error('Error loading user data:', error);
+ showToast('Failed to load user data. Please try again.', 'error');
+ } finally {
+ hideLoading();
+ }
+}
+
+/**
+ * Load user preferences from localStorage
+ */
+function loadPreferences() {
+ // Load dark mode preference
+ const darkMode = localStorage.getItem('darkMode') === 'true';
+ darkModeToggle.checked = darkMode;
+ darkModeToggleSetting.checked = darkMode;
+
+ // Load default view preference
+ const defaultView = localStorage.getItem('defaultView') || 'grid';
+ defaultViewSelect.value = defaultView;
+
+ // Load email notifications preference (default to true if not set)
+ const emailNotifications = localStorage.getItem('emailNotifications') !== 'false';
+ emailNotificationsToggle.checked = emailNotifications;
+}
+
+/**
+ * Setup event listeners for the settings page
+ */
+function setupEventListeners() {
+ // Dark mode toggle
+ darkModeToggle.addEventListener('change', () => {
+ const isDark = darkModeToggle.checked;
+ setTheme(isDark);
+ darkModeToggleSetting.checked = isDark;
+ });
+
+ darkModeToggleSetting.addEventListener('change', () => {
+ const isDark = darkModeToggleSetting.checked;
+ setTheme(isDark);
+ darkModeToggle.checked = isDark;
+ });
+
+ // Save profile button
+ saveProfileBtn.addEventListener('click', saveProfile);
+
+ // Save preferences button
+ savePreferencesBtn.addEventListener('click', savePreferences);
+
+ // Change password button
+ changePasswordBtn.addEventListener('click', () => {
+ passwordChangeForm.style.display = 'block';
+ changePasswordBtn.style.display = 'none';
+ });
+
+ // Cancel password change
+ cancelPasswordBtn.addEventListener('click', () => {
+ passwordChangeForm.style.display = 'none';
+ changePasswordBtn.style.display = 'block';
+ resetPasswordForm();
+ });
+
+ // Save password button
+ savePasswordBtn.addEventListener('click', changePassword);
+
+ // Delete account button
+ deleteAccountBtn.addEventListener('click', () => {
+ openModal(deleteAccountModal);
+ });
+
+ // Delete confirm input
+ deleteConfirmInput.addEventListener('input', () => {
+ confirmDeleteAccountBtn.disabled = deleteConfirmInput.value !== 'DELETE';
+ });
+
+ // Confirm delete account button
+ confirmDeleteAccountBtn.addEventListener('click', deleteAccount);
+}
+
+/**
+ * Initialize modals
+ */
+function initModals() {
+ // Close modal when clicking on X or outside
+ document.querySelectorAll('.close-btn, [data-dismiss="modal"]').forEach(closeBtn => {
+ closeBtn.addEventListener('click', () => {
+ document.querySelectorAll('.modal-backdrop').forEach(modal => {
+ modal.style.display = 'none';
+ });
+
+ // Reset delete confirm input
+ if (deleteConfirmInput) {
+ deleteConfirmInput.value = '';
+ confirmDeleteAccountBtn.disabled = true;
+ }
+
+ // Reset password form
+ resetPasswordForm();
+ });
+ });
+
+ // Close modal when clicking outside
+ window.addEventListener('click', (event) => {
+ document.querySelectorAll('.modal-backdrop').forEach(modal => {
+ if (event.target === modal) {
+ modal.style.display = 'none';
+
+ // Reset delete confirm input
+ if (deleteConfirmInput) {
+ deleteConfirmInput.value = '';
+ confirmDeleteAccountBtn.disabled = true;
+ }
+
+ // Reset password form
+ resetPasswordForm();
+ }
+ });
+ });
+}
+
+/**
+ * Open a modal
+ * @param {HTMLElement} modal - The modal to open
+ */
+function openModal(modal) {
+ modal.style.display = 'flex';
+}
+
+/**
+ * Reset password form
+ */
+function resetPasswordForm() {
+ currentPasswordInput.value = '';
+ newPasswordInput.value = '';
+ confirmPasswordInput.value = '';
+}
+
+/**
+ * Set theme (dark/light)
+ * @param {boolean} isDark - Whether to use dark mode
+ */
+function setTheme(isDark) {
+ document.documentElement.setAttribute('data-theme', isDark ? 'dark' : 'light');
+ localStorage.setItem('darkMode', isDark);
+}
+
+/**
+ * Save user profile
+ */
+async function saveProfile() {
+ // Validate form
+ if (!firstNameInput.value.trim() || !lastNameInput.value.trim()) {
+ showToast('Please fill in all required fields', 'error');
+ return;
+ }
+
+ showLoading();
+
+ 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 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');
+ } else {
+ throw new Error('User not found in localStorage');
+ }
+ }
+ } catch (error) {
+ console.error('Error updating profile:', error);
+ showToast('Failed to update profile. Please try again.', 'error');
+ } finally {
+ hideLoading();
+ }
+}
+
+/**
+ * Save user preferences
+ */
+function savePreferences() {
+ // Save dark mode preference
+ const isDark = darkModeToggleSetting.checked;
+ setTheme(isDark);
+ darkModeToggle.checked = isDark;
+
+ // Save default view preference
+ const defaultView = defaultViewSelect.value;
+ localStorage.setItem('defaultView', defaultView);
+ localStorage.setItem('warrantyView', defaultView);
+
+ // Save email notifications preference
+ const emailNotifications = emailNotificationsToggle.checked;
+ localStorage.setItem('emailNotifications', emailNotifications);
+
+ showToast('Preferences saved successfully', 'success');
+}
+
+/**
+ * Change user password
+ */
+async function changePassword() {
+ // Validate form
+ if (!currentPasswordInput.value || !newPasswordInput.value || !confirmPasswordInput.value) {
+ showToast('Please fill in all password fields', 'error');
+ return;
+ }
+
+ if (newPasswordInput.value !== confirmPasswordInput.value) {
+ showToast('New passwords do not match', 'error');
+ return;
+ }
+
+ // Validate password strength
+ if (newPasswordInput.value.length < 8) {
+ showToast('Password must be at least 8 characters long', 'error');
+ return;
+ }
+
+ 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
+ })
+ });
+
+ 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');
+ }
+ } catch (error) {
+ console.error('Error changing password:', error);
+ showToast('Failed to change password. Please try again.', 'error');
+ } finally {
+ hideLoading();
+ }
+}
+
+/**
+ * Delete user account
+ */
+async function deleteAccount() {
+ if (deleteConfirmInput.value !== 'DELETE') {
+ showToast('Please type DELETE to confirm', 'error');
+ return;
+ }
+
+ showLoading();
+
+ try {
+ try {
+ const response = await fetch('/api/auth/account', {
+ method: 'DELETE',
+ headers: {
+ 'Authorization': `Bearer ${window.auth.getToken()}`
+ }
+ });
+
+ if (response.ok) {
+ // Clear auth data
+ if (window.auth.logout) {
+ window.auth.logout();
+ } else {
+ localStorage.removeItem('auth_token');
+ localStorage.removeItem('user_info');
+ }
+
+ // Show success message
+ showToast('Account deleted successfully', 'success');
+
+ // Redirect to home page after a short delay
+ setTimeout(() => {
+ window.location.href = 'index.html';
+ }, 2000);
+ } else {
+ // Handle error
+ const errorData = await response.json();
+ throw new Error(errorData.message || 'Failed to delete account');
+ }
+ } catch (apiError) {
+ console.warn('API error, showing offline message:', apiError);
+ showToast('Account cannot be deleted in offline mode', 'warning');
+ }
+ } catch (error) {
+ console.error('Error deleting account:', error);
+ showToast('Failed to delete account. Please try again.', 'error');
+ } finally {
+ hideLoading();
+
+ // Close modal
+ deleteAccountModal.style.display = 'none';
+
+ // Reset delete confirm input
+ deleteConfirmInput.value = '';
+ confirmDeleteAccountBtn.disabled = true;
+ }
+}
+
+/**
+ * Show loading spinner
+ */
+function showLoading() {
+ loadingContainer.style.display = 'flex';
+}
+
+/**
+ * Hide loading spinner
+ */
+function hideLoading() {
+ loadingContainer.style.display = 'none';
+}
+
+/**
+ * Show toast message
+ * @param {string} message - Message to display
+ * @param {string} type - Toast type (success, error, info, warning)
+ */
+function showToast(message, type = 'info') {
+ const toast = document.createElement('div');
+ toast.className = `toast toast-${type}`;
+
+ const icon = document.createElement('i');
+ switch (type) {
+ case 'success':
+ icon.className = 'fas fa-check-circle';
+ break;
+ case 'error':
+ icon.className = 'fas fa-exclamation-circle';
+ break;
+ case 'warning':
+ icon.className = 'fas fa-exclamation-triangle';
+ break;
+ default:
+ icon.className = 'fas fa-info-circle';
+ }
+
+ const messageSpan = document.createElement('span');
+ messageSpan.textContent = message;
+
+ toast.appendChild(icon);
+ toast.appendChild(messageSpan);
+
+ toastContainer.appendChild(toast);
+
+ // Remove toast after 5 seconds
+ setTimeout(() => {
+ toast.classList.add('toast-fade-out');
+ setTimeout(() => {
+ toastContainer.removeChild(toast);
+ }, 300);
+ }, 5000);
+}
\ No newline at end of file
diff --git a/frontend/status.html b/frontend/status.html
index 4010b79..ba29bb7 100644
--- a/frontend/status.html
+++ b/frontend/status.html
@@ -1,14 +1,201 @@
<!DOCTYPE html>
<html lang="en">
<head>
+ <!-- Authentication redirect script -->
+ <script src="auth-redirect.js" data-protected="true"></script>
+
+ <!-- Include authentication script first to handle login state immediately -->
+ <script src="include-auth-new.js"></script>
+
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
- <title>Warranty Status Dashboard</title>
+ <title>Status - Warranty Tracker</title>
<link rel="stylesheet" href="style.css">
<!-- 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">
<!-- Chart.js for visualizations -->
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
+ <!-- Load fix for auth buttons -->
+ <script src="fix-auth-buttons-loader.js"></script>
+ <style>
+ .user-menu {
+ position: relative;
+ margin-left: 15px;
+ }
+
+ .user-btn {
+ background: none;
+ border: none;
+ color: var(--text-color);
+ cursor: pointer;
+ display: flex;
+ align-items: center;
+ font-size: 0.9rem;
+ padding: 5px 10px;
+ border-radius: 20px;
+ transition: background-color 0.3s;
+ }
+
+ .user-btn:hover {
+ background-color: rgba(0, 0, 0, 0.05);
+ }
+
+ .dark-mode .user-btn:hover {
+ background-color: rgba(255, 255, 255, 0.1);
+ }
+
+ .user-btn i {
+ margin-right: 5px;
+ }
+
+ .user-menu-dropdown {
+ position: absolute;
+ top: 100%;
+ right: 0;
+ background-color: var(--card-bg);
+ border-radius: 8px;
+ box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
+ width: 200px;
+ z-index: 1000;
+ display: none;
+ padding: 10px 0;
+ margin-top: 5px;
+ }
+
+ .user-menu-dropdown.active {
+ display: block;
+ }
+
+ .user-info {
+ padding: 10px 15px;
+ border-bottom: 1px solid var(--border-color);
+ margin-bottom: 5px;
+ }
+
+ .user-name {
+ font-weight: bold;
+ margin-bottom: 5px;
+ }
+
+ .user-email {
+ font-size: 0.8rem;
+ color: var(--text-muted);
+ word-break: break-all;
+ }
+
+ .user-menu-item {
+ padding: 8px 15px;
+ cursor: pointer;
+ transition: background-color 0.3s;
+ display: flex;
+ align-items: center;
+ }
+
+ .user-menu-item:hover {
+ background-color: var(--hover-bg);
+ }
+
+ .user-menu-item i {
+ margin-right: 10px;
+ width: 16px;
+ text-align: center;
+ }
+
+ .auth-buttons {
+ display: flex;
+ gap: 10px;
+ margin-left: 15px;
+ }
+
+ .auth-btn {
+ padding: 5px 15px;
+ border-radius: 20px;
+ font-size: 0.9rem;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ cursor: pointer;
+ transition: all 0.3s ease;
+ }
+
+ .auth-btn i {
+ margin-right: 5px;
+ }
+
+ .login-btn {
+ background-color: transparent;
+ border: 1px solid var(--primary-color);
+ color: var(--primary-color);
+ }
+
+ .login-btn:hover {
+ background-color: rgba(var(--primary-rgb), 0.1);
+ }
+
+ .register-btn {
+ background-color: var(--primary-color);
+ border: 1px solid var(--primary-color);
+ color: white;
+ }
+
+ .register-btn:hover {
+ background-color: var(--primary-dark);
+ }
+ </style>
+
+ <!-- Immediate authentication check script -->
+ <script>
+ // Check if user is logged in immediately to hide buttons
+ (function() {
+ if (localStorage.getItem('auth_token')) {
+ // Hide login and register buttons immediately
+ document.addEventListener('DOMContentLoaded', function() {
+ console.log('Inline script: User is logged in, hiding login/register buttons');
+
+ // Hide auth container
+ var authContainer = document.getElementById('authContainer');
+ if (authContainer) {
+ authContainer.style.display = 'none';
+ authContainer.style.visibility = 'hidden';
+ }
+
+ // Show user menu
+ var userMenu = document.getElementById('userMenu');
+ if (userMenu) {
+ userMenu.style.display = 'block';
+ userMenu.style.visibility = 'visible';
+ }
+
+ // Update user info if possible
+ try {
+ var userInfo = JSON.parse(localStorage.getItem('user_info'));
+ if (userInfo) {
+ var displayName = userInfo.first_name || userInfo.username || 'User';
+ var userDisplayName = document.getElementById('userDisplayName');
+ if (userDisplayName) {
+ userDisplayName.textContent = displayName;
+ }
+
+ var userName = document.getElementById('userName');
+ if (userName) {
+ userName.textContent = (userInfo.first_name || '') + ' ' + (userInfo.last_name || '');
+ if (!userName.textContent.trim()) userName.textContent = userInfo.username || 'User';
+ }
+
+ var userEmail = document.getElementById('userEmail');
+ if (userEmail && userInfo.email) {
+ userEmail.textContent = userInfo.email;
+ }
+ }
+ } catch (e) {
+ console.error('Error updating user info:', e);
+ }
+ }, { once: true });
+ }
+ })();
+ </script>
</head>
<body>
<!-- Header -->
@@ -26,8 +213,39 @@
<i class="fas fa-chart-pie"></i> Status
</a>
</div>
+ <div id="authContainer" class="auth-buttons">
+ <a href="login.html" class="auth-btn login-btn">
+ <i class="fas fa-sign-in-alt"></i> Login
+ </a>
+ <a href="register.html" class="auth-btn register-btn">
+ <i class="fas fa-user-plus"></i> Register
+ </a>
+ </div>
+ <div id="userMenu" class="user-menu" style="display: none;">
+ <button id="userBtn" class="user-btn">
+ <i class="fas fa-user-circle"></i>
+ <span id="userDisplayName">User</span>
+ </button>
+ <div id="userMenuDropdown" class="user-menu-dropdown">
+ <div class="user-info">
+ <div id="userName" class="user-name">User Name</div>
+ <div id="userEmail" class="user-email">[email protected]</div>
+ </div>
+ <div class="user-menu-item" id="profileMenuItem">
+ <i class="fas fa-id-card"></i> Profile
+ </div>
+ <div class="user-menu-item">
+ <a href="settings-new.html" style="color: inherit; text-decoration: none; display: block;">
+ <i class="fas fa-cog"></i> Settings
+ </a>
+ </div>
+ <div class="user-menu-item" id="logoutMenuItem">
+ <i class="fas fa-sign-out-alt"></i> Logout
+ </div>
+ </div>
+ </div>
<div class="settings-container">
- <button id="settingsBtn" class="settings-btn" aria-label="Settings">
+ <button id="settingsBtn" class="settings-btn" aria-label="Settings" type="button">
<i class="fas fa-cog"></i>
</button>
<div id="settingsMenu" class="settings-menu">
@@ -193,8 +411,13 @@
<!-- Toast Notifications -->
<div class="toast-container" id="toastContainer"></div>
-
- <!-- Load status.js script after page is processed -->
+
+ <!-- Loading Spinner -->
+ <div class="loading-container" id="loadingContainer">
+ <div class="loading-spinner"></div>
+ </div>
+
+ <script src="auth.js"></script>
<script src="status.js"></script>
</body>
-</html>
\ No newline at end of file
+</html>
\ No newline at end of file
diff --git a/frontend/status.js b/frontend/status.js
index 10674af..d45fd20 100644
--- a/frontend/status.js
+++ b/frontend/status.js
@@ -14,7 +14,8 @@ const sortableHeaders = document.querySelectorAll('.sortable');
const exportBtn = document.getElementById('exportBtn');
// Configuration
-const API_URL = '/api/statistics'; // Full URL for statistics endpoint
+const API_BASE_URL = '/api/statistics'; // Base URL for statistics endpoint
+const API_URL = window.location.origin + API_BASE_URL; // Full URL for statistics endpoint
const EXPIRING_SOON_DAYS = 30; // Number of days to consider "expiring soon"
// Global variables for sorting and filtering
@@ -49,17 +50,35 @@ function initializeTheme() {
// Initialize theme when page loads
initializeTheme();
-// Settings menu toggle
-settingsBtn.addEventListener('click', (e) => {
- e.stopPropagation();
- settingsMenu.classList.toggle('active');
-});
-
-// Close settings menu when clicking outside
-document.addEventListener('click', (e) => {
- if (!settingsMenu.contains(e.target) && !settingsBtn.contains(e.target)) {
- settingsMenu.classList.remove('active');
+// Initialize settings button
+document.addEventListener('DOMContentLoaded', () => {
+ // Ensure auth state is checked
+ if (window.auth && window.auth.checkAuthState) {
+ window.auth.checkAuthState();
+ }
+
+ // Ensure settings button works
+ if (settingsBtn && settingsMenu) {
+ console.log('Status page: Settings button found, adding event listener');
+ settingsBtn.addEventListener('click', function(e) {
+ e.stopPropagation();
+ settingsMenu.classList.toggle('active');
+ console.log('Status page: Settings button clicked, menu toggled');
+ });
+
+ // Close settings menu when clicking outside
+ document.addEventListener('click', function(e) {
+ if (settingsMenu.classList.contains('active') &&
+ !settingsMenu.contains(e.target) &&
+ !settingsBtn.contains(e.target)) {
+ settingsMenu.classList.remove('active');
+ }
+ });
+ } else {
+ console.error('Status page: Settings button or menu not found');
}
+
+ // ... existing code ...
});
// Dark mode toggle
@@ -144,7 +163,38 @@ function hideError() {
// Fetch statistics from API
async function fetchStatistics() {
try {
- const response = await fetch(API_URL);
+ console.log('Checking authentication status...');
+ console.log('window.auth exists:', !!window.auth);
+
+ // Check if auth is available and user is authenticated
+ if (!window.auth) {
+ console.error('Auth object not available. Make sure auth.js is loaded before status.js');
+ throw new Error('Authentication system not available. Please refresh the page.');
+ }
+
+ console.log('User is authenticated:', window.auth.isAuthenticated());
+ if (!window.auth.isAuthenticated()) {
+ throw new Error('Authentication required. Please log in to view statistics.');
+ }
+
+ // Get the auth token
+ const token = window.auth.getToken();
+ console.log('Auth token available:', !!token);
+ if (!token) {
+ throw new Error('Authentication token not available. Please log in again.');
+ }
+
+ // Create request with auth header
+ const options = {
+ method: 'GET',
+ headers: {
+ 'Authorization': `Bearer ${token}`,
+ 'Content-Type': 'application/json'
+ }
+ };
+
+ console.log('Fetching statistics from:', API_URL);
+ const response = await fetch(API_URL, options);
if (!response.ok) {
const errorText = await response.text();
@@ -647,126 +697,32 @@ async function initDashboard() {
// Create charts
createStatusChart(summary);
-
- // Handle timeline data
- if (Array.isArray(timeline) && timeline.length > 0) {
- createTimelineChart(timeline);
- } else {
- // Create default timeline if none provided
- createTimelineChart([
- { month: 1, year: new Date().getFullYear(), count: 0 },
- { month: 2, year: new Date().getFullYear(), count: 0 },
- { month: 3, year: new Date().getFullYear(), count: 0 }
- ]);
- }
+ createTimelineChart(timeline);
// Update recent expirations table
- if (Array.isArray(recentWarranties)) {
- updateRecentExpirations(recentWarranties);
- } else {
- updateRecentExpirations([]);
- }
+ updateRecentExpirations(recentWarranties);
+
+ // Store all warranties for filtering
+ allWarranties = recentWarranties;
+
+ // Set up event listeners for filtering and sorting
+ setupEventListeners();
- showToast('Dashboard updated successfully', 'success');
+ hideLoading();
} catch (error) {
console.error('Error initializing dashboard:', error);
- showError(
- 'There was a problem loading the warranty statistics. Please try refreshing the page.',
- error.message
- );
-
- // Fallback to static data for demonstration if API fails
- document.getElementById('activeCount').textContent = '10';
- document.getElementById('expiringCount').textContent = '5';
- document.getElementById('expiredCount').textContent = '3';
- document.getElementById('totalCount').textContent = '18';
-
- // Create a simple chart with static data
- try {
- const ctx = document.getElementById('statusChart').getContext('2d');
- if (window.statusChart) window.statusChart.destroy();
-
- window.statusChart = new Chart(ctx, {
- type: 'doughnut',
- data: {
- labels: ['Active', 'Expiring Soon', 'Expired'],
- datasets: [{
- data: [10, 5, 3],
- backgroundColor: [
- '#4CAF50',
- '#FF9800',
- '#F44336'
- ],
- borderWidth: 1
- }]
- },
- options: {
- responsive: true,
- maintainAspectRatio: false,
- plugins: {
- legend: {
- position: 'bottom'
- }
- }
- }
- });
-
- // Create a simple timeline chart
- const timelineCtx = document.getElementById('timelineChart').getContext('2d');
- if (window.timelineChart) window.timelineChart.destroy();
-
- window.timelineChart = new Chart(timelineCtx, {
- type: 'bar',
- data: {
- labels: ['Jan 2023', 'Feb 2023', 'Mar 2023'],
- datasets: [{
- label: 'Warranties Expiring',
- data: [2, 3, 4],
- backgroundColor: '#3498db',
- borderColor: '#2980b9',
- borderWidth: 1
- }]
- },
- options: {
- responsive: true,
- maintainAspectRatio: false,
- scales: {
- y: {
- beginAtZero: true,
- ticks: {
- precision: 0
- }
- }
- }
- }
- });
-
- // Add some sample data to the table
- const sampleWarranties = [
- {
- id: 1,
- product_name: 'Sample Product 1',
- purchase_date: '2022-01-01',
- expiration_date: '2023-01-01',
- invoice_path: null
- },
- {
- id: 2,
- product_name: 'Sample Product 2',
- purchase_date: '2022-01-01',
- expiration_date: '2023-06-15',
- invoice_path: null
- }
- ];
-
- // Update the table with sample data
- updateRecentExpirations(sampleWarranties);
+
+ // Check if it's an authentication error
+ if (error.message.includes('Authentication required') ||
+ error.message.includes('Authentication token') ||
+ error.message.includes('401')) {
- } catch (chartError) {
- console.error('Error creating fallback charts:', chartError);
+ showError('Authentication Required',
+ 'Please <a href="login.html">log in</a> to view your warranty statistics.');
+ } else {
+ showError('Error Loading Dashboard',
+ 'There was a problem loading the warranty statistics. Please try refreshing the page.');
}
-
- showToast('Using demo data - API connection failed', 'warning');
} finally {
hideLoading();
}
@@ -905,4 +861,112 @@ function exportWarrantyData() {
document.body.removeChild(link);
showToast('Data exported successfully', 'success');
+}
+
+// Set up event listeners for filtering and sorting
+function setupEventListeners() {
+ // Refresh button
+ if (refreshDashboardBtn) {
+ refreshDashboardBtn.addEventListener('click', refreshDashboard);
+ }
+
+ // Search input
+ if (searchWarranties) {
+ searchWarranties.addEventListener('input', filterAndSortWarranties);
+ }
+
+ // Status filter
+ if (statusFilter) {
+ statusFilter.addEventListener('change', filterAndSortWarranties);
+ }
+
+ // Sortable headers
+ if (sortableHeaders) {
+ sortableHeaders.forEach(header => {
+ header.addEventListener('click', () => {
+ const column = header.getAttribute('data-column');
+
+ // Toggle direction if same column, otherwise default to ascending
+ if (currentSort.column === column) {
+ currentSort.direction = currentSort.direction === 'asc' ? 'desc' : 'asc';
+ } else {
+ currentSort.column = column;
+ currentSort.direction = 'asc';
+ }
+
+ // Update header classes to show sort direction
+ updateSortHeaderClasses();
+
+ // Apply the new sort
+ filterAndSortWarranties();
+ });
+ });
+ }
+
+ // Export button
+ if (exportBtn) {
+ exportBtn.addEventListener('click', exportWarrantyData);
+ }
+
+ // Dark mode toggle
+ if (darkModeToggle) {
+ darkModeToggle.addEventListener('change', (e) => {
+ setTheme(e.target.checked);
+
+ // Redraw charts with new theme colors if they exist
+ if (window.statusChart) {
+ createStatusChart({
+ active: parseInt(document.getElementById('activeCount').textContent) || 0,
+ expiring_soon: parseInt(document.getElementById('expiringCount').textContent) || 0,
+ expired: parseInt(document.getElementById('expiredCount').textContent) || 0
+ });
+ }
+
+ if (window.timelineChart && allWarranties.length > 0) {
+ createTimelineChart(extractTimelineData(allWarranties));
+ }
+ });
+ }
+}
+
+// Helper function to extract timeline data from warranties
+function extractTimelineData(warranties) {
+ // Create a map to store counts by month and year
+ const timelineMap = new Map();
+
+ // Get current date for reference
+ const today = new Date();
+
+ // Process each warranty
+ warranties.forEach(warranty => {
+ if (warranty.expiration_date) {
+ const expDate = new Date(warranty.expiration_date);
+ const month = expDate.getMonth() + 1; // 1-12
+ const year = expDate.getFullYear();
+
+ // Create a key for this month/year
+ const key = `${year}-${month}`;
+
+ // Increment the count for this month/year
+ if (timelineMap.has(key)) {
+ timelineMap.set(key, timelineMap.get(key) + 1);
+ } else {
+ timelineMap.set(key, 1);
+ }
+ }
+ });
+
+ // Convert the map to an array of objects
+ const timeline = Array.from(timelineMap.entries()).map(([key, count]) => {
+ const [year, month] = key.split('-').map(Number);
+ return { year, month, count };
+ });
+
+ // Sort by date
+ timeline.sort((a, b) => {
+ if (a.year !== b.year) return a.year - b.year;
+ return a.month - b.month;
+ });
+
+ return timeline;
}
\ No newline at end of file
diff --git a/frontend/style.css b/frontend/style.css
index 2feab0a..2ae9710 100644
--- a/frontend/style.css
+++ b/frontend/style.css
@@ -973,23 +973,6 @@ input:checked + .toggle-slider:before {
transform: translateX(26px);
}
-.toggle-slider:after {
- content: '☀️';
- position: absolute;
- top: 3px;
- left: 6px;
- font-size: 12px;
- color: var(--white);
- opacity: 0.7;
- transition: var(--transition);
-}
-
-input:checked + .toggle-slider:after {
- content: '🌙';
- left: auto;
- right: 6px;
-}
-
/* ===== UTILITIES ===== */
.text-danger {
color: var(--danger-color);
diff --git a/frontend/test-auth-buttons.js b/frontend/test-auth-buttons.js
new file mode 100644
index 0000000..68d5455
--- /dev/null
+++ b/frontend/test-auth-buttons.js
@@ -0,0 +1 @@
+console.log('Testing authentication status:', localStorage.getItem('auth_token'));
diff --git a/nginx.conf b/nginx.conf
index 6bd1b37..dcd2340 100644
--- a/nginx.conf
+++ b/nginx.conf
@@ -15,7 +15,7 @@ server {
# Add CORS headers globally
add_header 'Access-Control-Allow-Origin' '*';
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS, PUT, DELETE';
- add_header 'Access-Control-Allow-Headers' 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range';
+ add_header 'Access-Control-Allow-Headers' 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range,Authorization';
# MIME types - fixed duplicate js entry
types {
@@ -37,19 +37,22 @@ server {
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
+ # Pass Authorization header to backend
+ proxy_set_header Authorization $http_authorization;
+
# Add debug headers to see what's happening
add_header X-Debug-Message "API request proxied to backend" always;
# CORS for API
add_header 'Access-Control-Allow-Origin' '*' always;
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS, PUT, DELETE' always;
- add_header 'Access-Control-Allow-Headers' 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range' always;
+ add_header 'Access-Control-Allow-Headers' 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range,Authorization' always;
# CORS preflight
if ($request_method = 'OPTIONS') {
add_header 'Access-Control-Allow-Origin' '*' always;
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS, PUT, DELETE' always;
- add_header 'Access-Control-Allow-Headers' 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range' always;
+ add_header 'Access-Control-Allow-Headers' 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range,Authorization' always;
add_header 'Access-Control-Max-Age' 1728000 always;
add_header 'Content-Type' 'text/plain charset=UTF-8' always;
add_header 'Content-Length' 0 always;