This commit is contained in:
Jason
2026-04-11 00:04:09 -05:00
commit 7a2fffd62e
110 changed files with 51809 additions and 0 deletions
+147
View File
@@ -0,0 +1,147 @@
# Product App - Modular Flask Application
## 🏗️ Structure
```
product_app/
├── app.py # Main application file
├── passenger_wsgi.py # Passenger WSGI entry point for production
├── requirements.txt # Python dependencies
├── blueprints/ # Modular routes organized by feature
│ ├── __init__.py
│ ├── auth.py # Login/logout/session management
│ └── users.py # User CRUD operations
├── templates/ # HTML templates
│ ├── login.html
│ └── user_manager.html
└── data/ # Data storage
└── users.json # User accounts with hashed passwords
```
## 🎯 Features Implemented
### ✅ Authentication System (blueprints/auth.py)
- Login with username/password
- Session management
- Password hashing (PBKDF2-SHA256, 1M iterations)
- Login required decorator
- Permission checking: `can_user('manage_users')`
- User status checking (active/inactive)
### ✅ User Management (blueprints/users.py)
- View all users
- Add new users
- Delete users
- Toggle active/inactive status
- Change passwords (requires admin verification)
- Location-based access control
- Permission system (manage_users, create_quotes, etc.)
- Download users as JSON
## 🔐 Default Login
- **Username:** `Master`
- **Password:** `Master`
- **Permissions:** Full access (manage_users)
## 🚀 Local Testing
```bash
cd product_app
python app.py
```
Visit: http://localhost:8080/
## Routes
### Main Routes
- `/` - Home (redirects to login if not authenticated)
- `/test` - Test page to verify app is running
### Authentication Routes (auth_bp)
- `/login` - Login page
- `/logout` - Logout
- `/api/login` - POST: Login API
- `/api/session` - GET: Current session info
### User Management Routes (users_bp)
- `/users/` - User management page
- `/users/api` - GET: List all users, POST: Add user
- `/users/api/<index>` - DELETE: Delete user
- `/users/api/<index>/active` - PATCH: Toggle active status
- `/users/api/<index>/change-password` - POST: Change password
- `/users/api/download` - GET: Download users.json
## 📦 Production Deployment
### Upload to Server: `/home/bmdwtjuw/product-finder/`
Files to upload:
- `app.py`
- `passenger_wsgi.py` (or just use existing)
- `blueprints/` (entire folder)
- `__init__.py`
- `auth.py`
- `users.py`
- `templates/` (entire folder)
- `login.html`
- `user_manager.html`
- `data/users.json`
### Control Panel Settings
- **Application startup file:** `passenger_wsgi.py` (or `app.py`)
- **Application Entry point:** `application`
- **Python version:** 3.13.11
### Test After Deployment:
1. https://columbiawindows.com/product-finder/test
2. https://columbiawindows.com/product-finder/login
3. Login with Master/Master
4. Test user management
## 🔧 Adding New Features
### Create a New Blueprint
1. Create `blueprints/your_feature.py`:
```python
from flask import Blueprint, render_template
from blueprints.auth import login_required, can_user
your_feature_bp = Blueprint('your_feature', __name__, url_prefix='/your-feature')
@your_feature_bp.route('/')
@login_required
def index():
return render_template('your_feature.html')
```
2. Register in `app.py`:
```python
from blueprints.your_feature import your_feature_bp
app.register_blueprint(your_feature_bp)
```
3. Create `templates/your_feature.html`
4. Test locally, then upload to server
## 📝 Benefits of Blueprint Structure
**Separation of Concerns:** Each feature in its own file
**Easy to Maintain:** Find and edit specific features quickly
**Scalable:** Add new features without touching existing code
**Testable:** Each blueprint can be tested independently
**Reusable:** Share decorators (login_required, permission_required) across blueprints
## 🛠️ Next Steps
- Add more blueprints for other features (quotes, products, etc.)
- Add more templates as needed
- Extend permission system
- Add location selection page
- Add the main product finder quiz
+87
View File
@@ -0,0 +1,87 @@
from flask import Flask, session, redirect, url_for
import secrets
import os
# Get the directory where this script is located
basedir = os.path.abspath(os.path.dirname(__file__))
# Initialize Flask with explicit paths
app = Flask(__name__,
template_folder=os.path.join(basedir, 'templates'),
static_folder=os.path.join(basedir, 'static'))
# Configure session - generate a random secret key
app.secret_key = secrets.token_hex(32)
app.config['SESSION_COOKIE_HTTPONLY'] = True
app.config['SESSION_COOKIE_SAMESITE'] = 'Lax'
# Import and register blueprints
from blueprints.auth import auth_bp
from blueprints.users import users_bp
app.register_blueprint(auth_bp)
app.register_blueprint(users_bp)
# Home route
@app.route('/')
def home():
"""Redirect to login if not authenticated, otherwise show home"""
if 'user_id' not in session:
return redirect(url_for('auth.login_page'))
# If user hasn't selected a location yet, redirect to selection
if not session.get('currentLocation') and len(session.get('accessibleLocations', [])) > 1:
return redirect(url_for('auth.select_location_page'))
return f"""
<html>
<head><title>Home</title></head>
<body style="font-family: Arial; padding: 20px;">
<h1>Welcome, {session.get('username', 'User')}!</h1>
<p>Current Location: {session.get('currentLocation', 'Not selected')}</p>
<ul>
<li><a href="{url_for('users.user_manager')}">Manage Users</a></li>
<li><a href="{url_for('auth.select_location_page')}">Change Location</a></li>
<li><a href="{url_for('auth.logout')}">Logout</a></li>
</ul>
</body>
</html>
"""
@app.route('/test')
def test():
"""Test route to verify app is running"""
import sys
return f"""
<html>
<head><title>Test Page</title></head>
<body style="font-family: Arial; padding: 20px;">
<h1>Flask App is Running!</h1>
<ul>
<li><strong>Python:</strong> {sys.version}</li>
<li><strong>Routes:</strong> {len(list(app.url_map.iter_rules()))}</li>
</ul>
<p><a href="{url_for('auth.login_page')}">Login</a></p>
</body>
</html>
"""
# Error handlers
@app.errorhandler(404)
def page_not_found(e):
return "<h1>404 - Page Not Found</h1>", 404
@app.errorhandler(500)
def internal_error(e):
return "<h1>500 - Internal Server Error</h1>", 500
# This is the critical line for Passenger
application = app
if __name__ == '__main__':
# Create necessary directories
os.makedirs(os.path.join(basedir, 'templates'), exist_ok=True)
os.makedirs(os.path.join(basedir, 'data'), exist_ok=True)
# Run the application
app.run(debug=True, host='0.0.0.0', port=8080)
+1
View File
@@ -0,0 +1 @@
# Blueprint package
+253
View File
@@ -0,0 +1,253 @@
"""
Authentication Blueprint
Handles login, logout, and session management
"""
from flask import Blueprint, render_template, request, jsonify, session, redirect, url_for
from werkzeug.security import check_password_hash
from functools import wraps
import json
import os
auth_bp = Blueprint('auth', __name__)
# Path to users file
USERS_FILE = os.path.join(os.path.dirname(os.path.dirname(__file__)), 'data', 'users.json')
def load_users():
"""Load users from JSON file"""
if os.path.exists(USERS_FILE):
try:
with open(USERS_FILE, 'r') as f:
return json.load(f)
except:
return []
return []
def login_required(f):
"""Decorator to require login for routes"""
@wraps(f)
def decorated_function(*args, **kwargs):
if 'user_id' not in session:
return redirect(url_for('auth.login_page'))
# Check if user is active
users = load_users()
if session['user_id'] >= len(users):
session.clear()
return redirect(url_for('auth.login_page', message='User not found'))
user = users[session['user_id']]
if not user.get('active', True):
session.clear()
return redirect(url_for('auth.login_page', message='Account is inactive'))
return f(*args, **kwargs)
return decorated_function
def get_current_user():
"""Get the currently logged in user"""
if 'user_id' not in session:
return None
users = load_users()
if session['user_id'] >= len(users):
return None
return users[session['user_id']]
def can_user(permission, location=None):
"""
Check if current user has a specific permission.
Args:
permission (str): Permission name (e.g., 'manage_users')
location (str, optional): Check permission for specific location
Returns:
bool: True if user has permission
"""
user = get_current_user()
if not user:
return False
if not user.get('active', True):
return False
# Check global permissions
global_permissions = user.get('permissions', {})
if permission in global_permissions:
return global_permissions[permission] is True
if location == 'global':
return False
# Check location-specific permissions
check_location = location if location else session.get('currentLocation')
if not check_location:
return False
location_settings = user.get('locationSettings', {})
if check_location in location_settings:
loc_permissions = location_settings[check_location].get('permissions', {})
if permission in loc_permissions:
return loc_permissions[permission] is True
return False
# Routes
@auth_bp.route('/login')
def login_page():
"""Serve the login page"""
if 'user_id' in session:
return redirect(url_for('home'))
return render_template('login.html')
@auth_bp.route('/select-location')
def select_location_page():
"""Serve the location selection page"""
if 'user_id' not in session:
return redirect(url_for('auth.login_page'))
return render_template('select_location.html')
@auth_bp.route('/api/login', methods=['POST'])
def login():
"""Authenticate user and create session"""
try:
data = request.json
username = data.get('username')
password = data.get('password')
if not username or not password:
return jsonify({
'status': 'error',
'message': 'Username and password are required'
}), 400
users = load_users()
# Find user by username
user_index = None
user = None
for i, u in enumerate(users):
if u['username'] == username:
user_index = i
user = u
break
if not user:
return jsonify({
'status': 'error',
'message': 'Invalid username or password'
}), 401
# Check if user is active
if not user.get('active', True):
return jsonify({
'status': 'error',
'message': 'Account is inactive. Please contact an administrator.'
}), 403
# Verify password
if not check_password_hash(user['password'], password):
return jsonify({
'status': 'error',
'message': 'Invalid username or password'
}), 401
# Create session
session['user_id'] = user_index
session['username'] = user['username']
session['defaultLocation'] = user.get('defaultLocation')
# Get accessible locations
accessible_locations = []
if 'locationSettings' in user:
for loc_code, settings in user['locationSettings'].items():
if settings.get('accessible', False):
accessible_locations.append(loc_code)
session['accessibleLocations'] = accessible_locations
# Check if user needs to select a location
requiresLocationSelection = len(accessible_locations) > 1
# If only one location or no accessible locations, auto-select default
if not requiresLocationSelection:
session['currentLocation'] = user.get('defaultLocation')
return jsonify({
'status': 'success',
'message': 'Login successful',
'requiresLocationSelection': requiresLocationSelection
})
except Exception as e:
return jsonify({
'status': 'error',
'message': str(e)
}), 500
@auth_bp.route('/api/select-location', methods=['POST'])
def select_location():
"""Select a location for the current session"""
if 'user_id' not in session:
return jsonify({
'status': 'error',
'message': 'Not logged in'
}), 401
try:
data = request.json
location = data.get('location')
# Verify user has access to this location
accessible = session.get('accessibleLocations', [])
if location not in accessible:
return jsonify({
'status': 'error',
'message': 'You do not have access to this location'
}), 403
session['currentLocation'] = location
return jsonify({
'status': 'success',
'message': 'Location selected',
'currentLocation': location
})
except Exception as e:
return jsonify({
'status': 'error',
'message': str(e)
}), 500
@auth_bp.route('/logout')
def logout():
"""Log out user and clear session"""
session.clear()
return redirect(url_for('auth.login_page'))
@auth_bp.route('/api/session', methods=['GET'])
def get_session():
"""Get current session information"""
if 'user_id' not in session:
return jsonify({
'status': 'error',
'message': 'Not logged in'
}), 401
# Get user permissions
user = get_current_user()
permissions = {}
if user:
permissions = user.get('permissions', {})
return jsonify({
'status': 'success',
'username': session.get('username'),
'defaultLocation': session.get('defaultLocation'),
'currentLocation': session.get('currentLocation'),
'accessibleLocations': session.get('accessibleLocations', []),
'permissions': permissions
})
+276
View File
@@ -0,0 +1,276 @@
"""
User Management Blueprint
Handles user CRUD operations
"""
from flask import Blueprint, render_template, request, jsonify, send_file
from werkzeug.security import generate_password_hash, check_password_hash
from blueprints.auth import login_required, can_user, get_current_user
from io import BytesIO
import json
import os
users_bp = Blueprint('users', __name__, url_prefix='/users')
# Path to users file
USERS_FILE = os.path.join(os.path.dirname(os.path.dirname(__file__)), 'data', 'users.json')
def load_users():
"""Load users from JSON file"""
if os.path.exists(USERS_FILE):
try:
with open(USERS_FILE, 'r') as f:
return json.load(f)
except:
return []
return []
def save_users(users):
"""Save users to JSON file"""
os.makedirs(os.path.dirname(USERS_FILE), exist_ok=True)
with open(USERS_FILE, 'w') as f:
json.dump(users, f, indent=2)
def permission_required(permission):
"""Decorator to require specific permission"""
from functools import wraps
def decorator(f):
@wraps(f)
def decorated_function(*args, **kwargs):
if not can_user(permission):
return jsonify({
'status': 'error',
'message': 'Permission denied'
}), 403
return f(*args, **kwargs)
return decorated_function
return decorator
# Routes
@users_bp.route('/')
@login_required
def user_manager():
"""Serve the user management page"""
if not can_user('manage_users'):
return "<h1>403 - Permission Denied</h1><p>You don't have permission to manage users.</p>", 403
return render_template('user_manager.html')
@users_bp.route('/api', methods=['GET'])
@login_required
@permission_required('manage_users')
def get_users():
"""Get all users"""
users = load_users()
return jsonify({
'status': 'success',
'users': users
})
@users_bp.route('/api', methods=['POST'])
@login_required
@permission_required('manage_users')
def add_user():
"""Add a new user with hashed password"""
try:
data = request.json
# Validate required fields
if not data.get('username') or not data.get('password') or not data.get('defaultLocation'):
return jsonify({
'status': 'error',
'message': 'Username, password, and default location are required'
}), 400
users = load_users()
# Check if username already exists
if any(user['username'] == data['username'] for user in users):
return jsonify({
'status': 'error',
'message': 'Username already exists'
}), 400
# Hash the password
hashed_password = generate_password_hash(data['password'], method='pbkdf2:sha256')
# Get location settings
location_settings = data.get('locationSettings', {})
default_location = data['defaultLocation']
# Ensure default location is accessible
if default_location not in location_settings:
location_settings[default_location] = {}
location_settings[default_location]['accessible'] = True
# Create new user
new_user = {
'username': data['username'],
'password': hashed_password,
'defaultLocation': default_location,
'locationSettings': location_settings,
'permissions': data.get('permissions', {}),
'active': data.get('active', True)
}
users.append(new_user)
save_users(users)
return jsonify({
'status': 'success',
'message': 'User added successfully',
'users': users
})
except Exception as e:
return jsonify({
'status': 'error',
'message': str(e)
}), 500
@users_bp.route('/api/<int:user_index>', methods=['DELETE'])
@login_required
@permission_required('manage_users')
def delete_user(user_index):
"""Delete a specific user by index"""
try:
users = load_users()
if user_index < 0 or user_index >= len(users):
return jsonify({
'status': 'error',
'message': 'Invalid user index'
}), 400
users.pop(user_index)
save_users(users)
return jsonify({
'status': 'success',
'message': 'User deleted successfully',
'users': users
})
except Exception as e:
return jsonify({
'status': 'error',
'message': str(e)
}), 500
@users_bp.route('/api/<int:user_index>/active', methods=['PATCH'])
@login_required
@permission_required('manage_users')
def toggle_user_active(user_index):
"""Toggle user active status"""
try:
data = request.json
users = load_users()
if user_index < 0 or user_index >= len(users):
return jsonify({
'status': 'error',
'message': 'Invalid user index'
}), 400
users[user_index]['active'] = data.get('active', True)
save_users(users)
return jsonify({
'status': 'success',
'message': 'User status updated',
'users': users
})
except Exception as e:
return jsonify({
'status': 'error',
'message': str(e)
}), 500
@users_bp.route('/api/<int:user_index>/change-password', methods=['POST'])
@login_required
@permission_required('manage_users')
def change_user_password(user_index):
"""Change a user's password with current user verification"""
try:
data = request.json
new_password = data.get('newPassword')
current_user_password = data.get('currentUserPassword')
if not new_password or not current_user_password:
return jsonify({
'status': 'error',
'message': 'New password and current user password are required'
}), 400
if len(new_password) < 6:
return jsonify({
'status': 'error',
'message': 'Password must be at least 6 characters long'
}), 400
# Verify current user's password
current_user = get_current_user()
if not current_user:
return jsonify({
'status': 'error',
'message': 'Not authenticated'
}), 401
if not check_password_hash(current_user['password'], current_user_password):
return jsonify({
'status': 'error',
'message': 'Your password is incorrect. Password change denied for security reasons.'
}), 403
# Load users and validate index
users = load_users()
if user_index < 0 or user_index >= len(users):
return jsonify({
'status': 'error',
'message': 'Invalid user index'
}), 400
# Update password
hashed_password = generate_password_hash(new_password, method='pbkdf2:sha256')
target_username = users[user_index]['username']
users[user_index]['password'] = hashed_password
save_users(users)
return jsonify({
'status': 'success',
'message': f'Password changed successfully for user "{target_username}"'
})
except Exception as e:
return jsonify({
'status': 'error',
'message': str(e)
}), 500
@users_bp.route('/api/download')
@login_required
@permission_required('manage_users')
def download_users():
"""Download users as JSON file"""
try:
users = load_users()
if not users:
return jsonify({
'status': 'error',
'message': 'No users to download'
}), 400
json_data = json.dumps(users, indent=2)
return send_file(
BytesIO(json_data.encode()),
mimetype='application/json',
as_attachment=True,
download_name='users.json'
)
except Exception as e:
return jsonify({
'status': 'error',
'message': str(e)
}), 500
+25
View File
@@ -0,0 +1,25 @@
[
{
"username": "Master",
"password": "pbkdf2:sha256:1000000$tPRmseRGKLveXTxS$87eda9a20db29d12838fcb607f1f3536141f743ec9879702dc2a0dd893b4078d",
"defaultLocation": "KC",
"permissions": {
"manage_users": true
},
"locationSettings": {
"LINDS": {
"accessible": true
},
"IOLA": {
"accessible": true
},
"KC": {
"accessible": true
},
"BMD": {
"accessible": true
}
},
"active": true
}
]
+17
View File
@@ -0,0 +1,17 @@
import importlib.machinery
import importlib.util
import os
import sys
sys.path.insert(0, os.path.dirname(__file__))
def load_source(modname, filename):
loader = importlib.machinery.SourceFileLoader(modname, filename)
spec = importlib.util.spec_from_file_location(modname, filename, loader=loader)
module = importlib.util.module_from_spec(spec)
loader.exec_module(module)
return module
wsgi = load_source('wsgi', 'app.py')
application = wsgi.application
+1
View File
@@ -0,0 +1 @@
Flask==3.1.3
+213
View File
@@ -0,0 +1,213 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Login</title>
<style>
* { margin: 0; padding: 0; box-sizing: border-box; }
body {
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
min-height: 100vh;
display: flex;
align-items: center;
justify-content: center;
padding: 20px;
}
.login-container {
background: white;
padding: 40px;
border-radius: 10px;
box-shadow: 0 10px 30px rgba(0, 0, 0, 0.3);
width: 100%;
max-width: 400px;
}
.login-header {
text-align: center;
margin-bottom: 30px;
}
.login-header h1 {
color: #333;
margin-bottom: 10px;
font-size: 28px;
}
.login-header p {
color: #666;
font-size: 14px;
}
.form-group {
margin-bottom: 20px;
}
.form-group label {
display: block;
margin-bottom: 8px;
color: #333;
font-weight: 600;
}
.form-group input {
width: 100%;
padding: 12px;
border: 2px solid #e0e0e0;
border-radius: 5px;
font-size: 16px;
transition: border-color 0.3s;
}
.form-group input:focus {
outline: none;
border-color: #667eea;
}
.btn {
width: 100%;
padding: 14px;
border: none;
border-radius: 5px;
font-size: 16px;
font-weight: 600;
cursor: pointer;
transition: all 0.3s;
background: #667eea;
color: white;
}
.btn:hover {
background: #5568d3;
transform: translateY(-2px);
box-shadow: 0 5px 15px rgba(102, 126, 234, 0.4);
}
.btn:disabled {
background: #cbd5e0;
cursor: not-allowed;
transform: none;
}
.alert {
padding: 12px;
border-radius: 5px;
margin-bottom: 20px;
display: none;
}
.alert.show {
display: block;
}
.alert-error {
background: #fed7d7;
color: #742a2a;
border-left: 4px solid #f56565;
}
.loading-spinner {
border: 3px solid #f3f3f3;
border-top: 3px solid #667eea;
border-radius: 50%;
width: 20px;
height: 20px;
animation: spin 1s linear infinite;
display: inline-block;
margin-left: 10px;
vertical-align: middle;
display: none;
}
@keyframes spin {
0% { transform: rotate(0deg); }
100% { transform: rotate(360deg); }
}
</style>
</head>
<body>
<div class="login-container">
<div class="login-header">
<h1>🔐 Login</h1>
<p>Please sign in to continue</p>
</div>
<div class="alert alert-error" id="errorAlert"></div>
<form id="loginForm">
<div class="form-group">
<label for="username">Username</label>
<input type="text" id="username" name="username" required autofocus
placeholder="Enter your username">
</div>
<div class="form-group">
<label for="password">Password</label>
<input type="password" id="password" name="password" required
placeholder="Enter your password">
</div>
<button type="submit" class="btn" id="loginBtn">
Sign In
<span class="loading-spinner" id="loadingSpinner"></span>
</button>
</form>
</div>
<script>
document.getElementById('loginForm').addEventListener('submit', async (e) => {
e.preventDefault();
const username = document.getElementById('username').value;
const password = document.getElementById('password').value;
const loginBtn = document.getElementById('loginBtn');
const spinner = document.getElementById('loadingSpinner');
loginBtn.disabled = true;
spinner.style.display = 'inline-block';
try {
const response = await fetch('/api/login', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ username, password })
});
const data = await response.json();
if (data.status === 'success') {
// Check if user needs to select a location
if (data.requiresLocationSelection) {
window.location.href = '/select-location';
} else {
window.location.href = '/';
}
} else {
showAlert(data.message || 'Invalid username or password');
loginBtn.disabled = false;
spinner.style.display = 'none';
}
} catch (error) {
showAlert('Error connecting to server. Please try again.');
loginBtn.disabled = false;
spinner.style.display = 'none';
}
});
function showAlert(message) {
const alert = document.getElementById('errorAlert');
alert.textContent = message;
alert.classList.add('show');
setTimeout(() => {
alert.classList.remove('show');
}, 5000);
}
</script>
</body>
</html>
+375
View File
@@ -0,0 +1,375 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Select Location</title>
<style>
* { margin: 0; padding: 0; box-sizing: border-box; }
body {
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
min-height: 100vh;
display: flex;
align-items: center;
justify-content: center;
padding: 20px;
}
.location-container {
background: white;
padding: 40px;
border-radius: 10px;
box-shadow: 0 10px 30px rgba(0, 0, 0, 0.3);
width: 100%;
max-width: 500px;
}
.location-header {
text-align: center;
margin-bottom: 30px;
}
.location-header h1 {
color: #333;
margin-bottom: 10px;
font-size: 28px;
}
.location-header p {
color: #666;
font-size: 15px;
}
.user-info {
background: #f7fafc;
padding: 15px;
border-radius: 5px;
margin-bottom: 30px;
border-left: 4px solid #667eea;
}
.user-info strong {
color: #333;
display: block;
margin-bottom: 5px;
}
.user-info span {
color: #666;
font-size: 14px;
}
.location-grid {
display: grid;
grid-template-columns: repeat(2, 1fr);
gap: 15px;
margin-bottom: 20px;
}
.location-card {
background: #f7fafc;
border: 3px solid #e0e0e0;
border-radius: 8px;
padding: 30px 20px;
text-align: center;
cursor: pointer;
transition: all 0.3s;
position: relative;
}
.location-card:hover {
border-color: #667eea;
background: #edf2f7;
transform: translateY(-3px);
box-shadow: 0 5px 15px rgba(102, 126, 234, 0.3);
}
.location-card.selected {
border-color: #667eea;
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
color: white;
}
.location-card .icon {
font-size: 40px;
margin-bottom: 10px;
}
.location-card .name {
font-size: 18px;
font-weight: 600;
}
.location-card .description {
font-size: 13px;
margin-top: 5px;
opacity: 0.8;
}
.btn {
width: 100%;
padding: 14px;
border: none;
border-radius: 5px;
font-size: 16px;
font-weight: 600;
cursor: pointer;
transition: all 0.3s;
background: #667eea;
color: white;
}
.btn:hover {
background: #5568d3;
transform: translateY(-2px);
box-shadow: 0 5px 15px rgba(102, 126, 234, 0.4);
}
.btn:disabled {
background: #cbd5e0;
cursor: not-allowed;
transform: none;
}
.alert {
padding: 12px;
border-radius: 5px;
margin-bottom: 20px;
display: none;
}
.alert.show {
display: block;
}
.alert-error {
background: #fed7d7;
color: #742a2a;
border-left: 4px solid #f56565;
}
.footer {
text-align: center;
margin-top: 20px;
}
.footer a {
color: #667eea;
text-decoration: none;
font-size: 14px;
}
.footer a:hover {
text-decoration: underline;
}
.loading-spinner {
border: 3px solid #f3f3f3;
border-top: 3px solid #667eea;
border-radius: 50%;
width: 20px;
height: 20px;
animation: spin 1s linear infinite;
display: inline-block;
margin-left: 10px;
vertical-align: middle;
display: none;
}
@keyframes spin {
0% { transform: rotate(0deg); }
100% { transform: rotate(360deg); }
}
@media (max-width: 600px) {
.location-grid {
grid-template-columns: 1fr;
}
}
</style>
</head>
<body>
<div class="location-container">
<div class="location-header">
<h1>📍 Select Your Location</h1>
<p>Choose which location you'll be working from today</p>
</div>
<div class="user-info">
<strong>Welcome, <span id="username">User</span>!</strong>
<span>Default Location: <span id="defaultLocation">-</span></span>
</div>
<div class="alert alert-error" id="errorAlert"></div>
<div class="location-grid" id="locationGrid">
<!-- Locations will be populated here -->
</div>
<button class="btn" id="confirmBtn" disabled>
Confirm Location
<span class="loading-spinner" id="loadingSpinner"></span>
</button>
<div class="footer">
<a href="/users" id="manageUsersLink" style="display: none; margin-right: 15px;">Manage Users</a>
<a href="/logout">Logout</a>
</div>
</div>
<script>
let selectedLocation = null;
let sessionData = null;
// Location details
const locationDetails = {
'LINDS': {
icon: '🏭',
name: 'LINDS',
description: 'Lindsborg Location'
},
'IOLA': {
icon: '🏢',
name: 'IOLA',
description: 'Iola Location'
},
'KC': {
icon: '🌆',
name: 'KC',
description: 'Kansas City Location'
},
'BMD': {
icon: '🏛️',
name: 'BMD',
description: 'BMD Location'
}
};
// Load session data on page load
loadSessionData();
async function loadSessionData() {
try {
const response = await fetch('/api/session');
const data = await response.json();
if (data.status === 'success') {
sessionData = data;
document.getElementById('username').textContent = data.username;
document.getElementById('defaultLocation').textContent = data.defaultLocation || 'Not set';
// Show manage users link if user has permission
if (data.permissions && data.permissions.manage_users === true) {
document.getElementById('manageUsersLink').style.display = 'inline';
}
// Render accessible locations
renderLocations(data.accessibleLocations || []);
// Auto-select default location if available
if (data.defaultLocation && data.accessibleLocations.includes(data.defaultLocation)) {
selectLocation(data.defaultLocation);
}
} else {
showError('Error loading session. Please login again.');
setTimeout(() => {
window.location.href = '/login';
}, 2000);
}
} catch (error) {
showError('Error connecting to server.');
}
}
function renderLocations(accessibleLocations) {
const grid = document.getElementById('locationGrid');
if (accessibleLocations.length === 0) {
grid.innerHTML = '<p style="color: #666; text-align: center; grid-column: 1 / -1;">No accessible locations found.</p>';
return;
}
grid.innerHTML = accessibleLocations.map(locCode => {
const loc = locationDetails[locCode] || {
icon: '📍',
name: locCode,
description: locCode
};
return `
<div class="location-card" onclick="selectLocation('${locCode}')" data-location="${locCode}">
<div class="icon">${loc.icon}</div>
<div class="name">${loc.name}</div>
<div class="description">${loc.description}</div>
</div>
`;
}).join('');
}
function selectLocation(locCode) {
selectedLocation = locCode;
// Remove selected class from all cards
document.querySelectorAll('.location-card').forEach(card => {
card.classList.remove('selected');
});
// Add selected class to clicked card
const card = document.querySelector(`[data-location="${locCode}"]`);
if (card) {
card.classList.add('selected');
}
// Enable confirm button
document.getElementById('confirmBtn').disabled = false;
}
document.getElementById('confirmBtn').addEventListener('click', async () => {
if (!selectedLocation) return;
const confirmBtn = document.getElementById('confirmBtn');
const spinner = document.getElementById('loadingSpinner');
confirmBtn.disabled = true;
spinner.style.display = 'inline-block';
try {
const response = await fetch('/api/select-location', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ location: selectedLocation })
});
const data = await response.json();
if (data.status === 'success') {
// Redirect to main app
window.location.href = '/';
} else {
showError(data.message || 'Error selecting location');
confirmBtn.disabled = false;
spinner.style.display = 'none';
}
} catch (error) {
showError('Error connecting to server');
confirmBtn.disabled = false;
spinner.style.display = 'none';
}
});
function showError(message) {
const alert = document.getElementById('errorAlert');
alert.textContent = message;
alert.classList.add('show');
setTimeout(() => {
alert.classList.remove('show');
}, 5000);
}
</script>
</body>
</html>
+498
View File
@@ -0,0 +1,498 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>User Manager</title>
<style>
* { margin: 0; padding: 0; box-sizing: border-box; }
body {
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
min-height: 100vh;
padding: 20px;
}
.container {
max-width: 900px;
margin: 0 auto;
}
.header {
background: white;
padding: 30px;
border-radius: 10px;
box-shadow: 0 10px 30px rgba(0, 0, 0, 0.2);
margin-bottom: 30px;
display: flex;
justify-content: space-between;
align-items: center;
}
.header h1 {
color: #333;
}
.card {
background: white;
padding: 30px;
border-radius: 10px;
box-shadow: 0 10px 30px rgba(0, 0, 0, 0.2);
margin-bottom: 20px;
}
.card h2 {
color: #333;
margin-bottom: 20px;
border-bottom: 2px solid #667eea;
padding-bottom: 10px;
}
.form-group {
margin-bottom: 20px;
}
.form-group label {
display: block;
margin-bottom: 8px;
color: #333;
font-weight: 600;
}
.form-group input, .form-group select {
width: 100%;
padding: 12px;
border: 2px solid #e0e0e0;
border-radius: 5px;
font-size: 16px;
}
.form-group input:focus, .form-group select:focus {
outline: none;
border-color: #667eea;
}
.btn {
padding: 12px 30px;
border: none;
border-radius: 5px;
font-size: 16px;
font-weight: 600;
cursor: pointer;
transition: all 0.3s;
}
.btn-primary {
background: #667eea;
color: white;
}
.btn-primary:hover {
background: #5568d3;
}
.btn-danger {
background: #f56565;
color: white;
}
.btn-danger:hover {
background: #e53e3e;
}
.btn-secondary {
background: #cbd5e0;
color: #333;
}
.btn-secondary:hover {
background: #a0aec0;
}
.user-item {
background: #f7fafc;
padding: 15px;
border-radius: 5px;
margin-bottom: 10px;
display: flex;
justify-content: space-between;
align-items: center;
border-left: 4px solid #667eea;
}
.user-item.inactive {
opacity: 0.6;
border-left-color: #cbd5e0;
}
.user-info {
flex: 1;
}
.user-info strong {
color: #333;
display: block;
margin-bottom: 5px;
}
.user-info span {
color: #666;
font-size: 14px;
}
.user-actions {
display: flex;
gap: 10px;
}
.user-actions button {
padding: 8px 16px;
font-size: 14px;
}
.alert {
padding: 15px;
border-radius: 5px;
margin-bottom: 20px;
display: none;
}
.alert.show {
display: block;
}
.alert-success {
background: #c6f6d5;
color: #22543d;
border-left: 4px solid #48bb78;
}
.alert-error {
background: #fed7d7;
color: #742a2a;
border-left: 4px solid #f56565;
}
.active-toggle {
display: flex;
align-items: center;
gap: 8px;
}
.active-toggle input {
width: 20px;
height: 20px;
cursor: pointer;
}
.location-checkboxes {
display: grid;
grid-template-columns: repeat(2, 1fr);
gap: 10px;
margin-top: 10px;
}
.location-item {
display: flex;
align-items: center;
gap: 10px;
}
.location-item input {
width: 20px;
height: 20px;
}
</style>
</head>
<body>
<div class="container">
<div class="header">
<h1>👥 User Manager</h1>
<a href="/" style="color: #333; text-decoration: none;">← Back to Home</a>
</div>
<div class="alert alert-success" id="successAlert"></div>
<div class="alert alert-error" id="errorAlert"></div>
<!-- Add User Form -->
<div class="card">
<h2>Add New User</h2>
<form id="addUserForm">
<div class="form-group">
<label for="newUsername">Username</label>
<input type="text" id="newUsername" required>
</div>
<div class="form-group">
<label for="newPassword">Password</label>
<input type="password" id="newPassword" required minlength="6">
</div>
<div class="form-group">
<label for="defaultLocation">Default Location</label>
<select id="defaultLocation" required>
<option value="">Select Location</option>
<option value="LINDS">LINDS</option>
<option value="IOLA">IOLA</option>
<option value="KC">KC</option>
<option value="BMD">BMD</option>
</select>
</div>
<div class="form-group">
<label>Accessible Locations</label>
<div class="location-checkboxes" id="accessibleLocations">
<div class="location-item">
<input type="checkbox" id="loc_LINDS" value="LINDS">
<label for="loc_LINDS">LINDS</label>
</div>
<div class="location-item">
<input type="checkbox" id="loc_IOLA" value="IOLA">
<label for="loc_IOLA">IOLA</label>
</div>
<div class="location-item">
<input type="checkbox" id="loc_KC" value="KC">
<label for="loc_KC">KC</label>
</div>
<div class="location-item">
<input type="checkbox" id="loc_BMD" value="BMD">
<label for="loc_BMD">BMD</label>
</div>
</div>
</div>
<div class="form-group">
<label>Permissions</label>
<div class="location-checkboxes">
<div class="location-item">
<input type="checkbox" id="perm_manage_users" value="manage_users">
<label for="perm_manage_users">Manage Users</label>
</div>
<div class="location-item">
<input type="checkbox" id="perm_create_quotes" value="create_quotes">
<label for="perm_create_quotes">Create Quotes</label>
</div>
</div>
</div>
<button type="submit" class="btn btn-primary">Add User</button>
</form>
</div>
<!-- User List -->
<div class="card">
<h2>Existing Users</h2>
<div id="userList"></div>
</div>
</div>
<script>
let users = [];
// Load users on page load
loadUsers();
async function loadUsers() {
try {
const response = await fetch('/users/api');
const data = await response.json();
if (data.status === 'success') {
users = data.users;
renderUsers();
} else {
showError(data.message);
}
} catch (error) {
showError('Error loading users: ' + error.message);
}
}
function renderUsers() {
const userList = document.getElementById('userList');
if (users.length === 0) {
userList.innerHTML = '<p style="color: #666;">No users found. Add a user above.</p>';
return;
}
userList.innerHTML = users.map((user, index) => `
<div class="user-item ${user.active ? '' : 'inactive'}">
<div class="user-info">
<strong>${user.username}</strong>
<span>Location: ${user.defaultLocation || 'Not set'} |
Status: ${user.active ? '<span style="color: #48bb78;">Active</span>' : '<span style="color: #f56565;">Inactive</span>'}</span>
</div>
<div class="user-actions">
<div class="active-toggle">
<input type="checkbox" ${user.active ? 'checked' : ''}
onchange="toggleActive(${index}, this.checked)">
<span>Active</span>
</div>
<button class="btn btn-secondary" onclick="changePassword(${index})">Change Password</button>
<button class="btn btn-danger" onclick="deleteUser(${index})">Delete</button>
</div>
</div>
`).join('');
}
// Add user form submission
document.getElementById('addUserForm').addEventListener('submit', async (e) => {
e.preventDefault();
const username = document.getElementById('newUsername').value;
const password = document.getElementById('newPassword').value;
const defaultLocation = document.getElementById('defaultLocation').value;
// Get accessible locations
const locationSettings = {};
['LINDS', 'IOLA', 'KC', 'BMD'].forEach(loc => {
const checkbox = document.getElementById(`loc_${loc}`);
if (checkbox.checked) {
locationSettings[loc] = { accessible: true, permissions: {} };
}
});
// Get permissions
const permissions = {};
if (document.getElementById('perm_manage_users').checked) {
permissions.manage_users = true;
}
if (document.getElementById('perm_create_quotes').checked) {
permissions.create_quotes = true;
}
try {
const response = await fetch('/users/api', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
username,
password,
defaultLocation,
locationSettings,
permissions,
active: true
})
});
const data = await response.json();
if (data.status === 'success') {
showSuccess('User added successfully!');
users = data.users;
renderUsers();
e.target.reset();
} else {
showError(data.message);
}
} catch (error) {
showError('Error adding user: ' + error.message);
}
});
async function toggleActive(index, active) {
try {
const response = await fetch(`/users/api/${index}/active`, {
method: 'PATCH',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ active })
});
const data = await response.json();
if (data.status === 'success') {
showSuccess('User status updated!');
users = data.users;
renderUsers();
} else {
showError(data.message);
renderUsers(); // Revert checkbox
}
} catch (error) {
showError('Error updating user: ' + error.message);
renderUsers(); // Revert checkbox
}
}
async function changePassword(index) {
const newPassword = prompt('Enter new password (min 6 characters):');
if (!newPassword || newPassword.length < 6) {
alert('Password must be at least 6 characters long');
return;
}
const currentPassword = prompt('Enter YOUR password to confirm this change:');
if (!currentPassword) return;
try {
const response = await fetch(`/users/api/${index}/change-password`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
newPassword: newPassword,
currentUserPassword: currentPassword
})
});
const data = await response.json();
if (data.status === 'success') {
showSuccess(data.message);
} else {
showError(data.message);
}
} catch (error) {
showError('Error changing password: ' + error.message);
}
}
async function deleteUser(index) {
if (!confirm(`Are you sure you want to delete ${users[index].username}?`)) {
return;
}
try {
const response = await fetch(`/users/api/${index}`, {
method: 'DELETE'
});
const data = await response.json();
if (data.status === 'success') {
showSuccess('User deleted successfully!');
users = data.users;
renderUsers();
} else {
showError(data.message);
}
} catch (error) {
showError('Error deleting user: ' + error.message);
}
}
function showSuccess(message) {
const alert = document.getElementById('successAlert');
alert.textContent = message;
alert.classList.add('show');
setTimeout(() => alert.classList.remove('show'), 5000);
}
function showError(message) {
const alert = document.getElementById('errorAlert');
alert.textContent = message;
alert.classList.add('show');
setTimeout(() => alert.classList.remove('show'), 5000);
}
// Auto-check location when selected as default
document.getElementById('defaultLocation').addEventListener('change', (e) => {
const loc = e.target.value;
if (loc) {
document.getElementById(`loc_${loc}`).checked = true;
}
});
</script>
</body>
</html>