docs: Add comprehensive settings page analysis and improvements

- Add detailed settings page analysis report (settings.md)
- Document identified security vulnerabilities and code quality issues
- Provide prioritized improvement recommendations
- Document permission and access control issues
- Add testing checklist for validation
- Track modifications to settings.py, routes.py, and settings.html templates
This commit is contained in:
Quality App System
2026-01-23 22:54:11 +02:00
parent 64b67b2979
commit d45dc1dab1
8 changed files with 1969 additions and 600 deletions

View File

@@ -0,0 +1,301 @@
# DASHBOARD PAGE - COMPREHENSIVE ANALYSIS REPORT
## 1. PAGE OVERVIEW
**Location:** `/dashboard` route
**Route Handler:** `routes.py` (lines 303-317)
**Template:** `templates/dashboard.html`
**Purpose:** Main navigation hub for authenticated users - displays module access cards based on user role and assigned modules
---
## 2. FUNCTIONALITY ANALYSIS
### Backend Logic (`routes.py` lines 303-317):
```
Function: dashboard()
- Checks if user is in session (if not, redirects to login)
- Retrieves user_role and user_modules from session
- Applies module override for superadmin/admin roles
- Passes user_modules and user_role to template
```
### What It Does:
1. **Session Validation**: Ensures only logged-in users can access dashboard
2. **Role-Based Access**:
- Superadmin/Admin users → see all 4 modules
- Other users → see only their assigned modules
3. **Module Display**: Conditionally renders cards for:
- Quality Module (scan & reports)
- Warehouse Module
- Labels Module
- Daily Mirror (BI/Reports)
- Settings (admin only)
---
## 3. FRONTEND STRUCTURE
### Template Layout (`dashboard.html`):
- **Floating Help Button**: Icon (📖) linking to help docs
- **Dashboard Container**: Uses flexbox layout with 3 columns on desktop
- **Module Cards**: Each card has:
- Title (h3)
- Description paragraph
- Action button(s) linking to module entry points
### CSS Styling (`style.css` lines 562-635 & `css/dashboard.css`):
- **Desktop**: 3-column flex layout (33.33% each)
- **Mobile**: Single column responsive (100%)
- **Cards**: Box shadow, rounded corners, hover effects
- **Dark Mode Support**: Color inversion for dark theme
### Button Links:
| Module | Primary Link | Secondary Link |
|--------|-------------|-----------------|
| Quality | `/main_scan` | `/reports` |
| Warehouse | `/warehouse` | None |
| Labels | `/etichete` | None |
| Daily Mirror | Daily Mirror Hub | None |
| Settings | `/settings` | None |
---
## 4. ISSUES & BUGS FOUND
### 🔴 CRITICAL ISSUES:
1. **Missing Module Initialization Check**
- **Problem**: Session modules might be None or missing if user was created before modules column was added
- **Line**: 309 `user_modules = session.get('modules', [])`
- **Impact**: Users might see no modules even if they should have access
- **Severity**: HIGH
2. **No Permission Validation for Routes**
- **Problem**: Routes like `/main_scan`, `/reports`, `/warehouse` are accessed directly without checking if user has permission
- **Impact**: Users could potentially bypass dashboard and access modules directly via URL
- **Severity**: MEDIUM
### 🟡 MODERATE ISSUES:
3. **Missing Error Handling**
- **Problem**: No try-catch for session access or template rendering
- **Line**: 303-317
- **Impact**: Unexpected errors will crash the page
- **Severity**: MEDIUM
4. **Inconsistent Module Names**
- **Problem**: Module names in Python ('quality', 'warehouse', 'labels', 'daily_mirror') vs route names might not match
- **Impact**: Conditional checks might fail if naming is inconsistent elsewhere
- **Severity**: MEDIUM
5. **No Logout on Invalid Session**
- **Problem**: If session exists but role/modules are missing, user isn't logged out, just redirected
- **Severity**: LOW
### 🟢 MINOR ISSUES:
6. **Debug Print Statement**
- **Line**: 304 `print("Session user:", session.get('user'), session.get('role'))`
- **Issue**: Left in production code (should use logging instead)
- **Severity**: LOW
7. **Hard-coded Module List for Superadmin**
- **Problem**: Superadmin sees ALL modules regardless of actual permissions
- **Impact**: Could mask permission issues
- **Severity**: LOW
---
## 5. CODE QUALITY ASSESSMENT
### Strengths:
✅ Clean, readable Python code
✅ Good separation of concerns (route, template, CSS)
✅ Responsive design with mobile support
✅ Dark mode support
✅ Accessible help button on every page
✅ Role-based conditional rendering (Jinja2)
### Weaknesses:
❌ No input validation
❌ No error handling
❌ Debug logging in production
❌ Hardcoded role list
❌ No permission auditing
❌ Missing module validation
---
## 6. SUGGESTIONS FOR IMPROVEMENT
### Priority 1 (Critical):
1. **Add Module Validation** - Check if user's assigned modules are valid
```python
VALID_MODULES = ['quality', 'warehouse', 'labels', 'daily_mirror']
if user_modules:
user_modules = [m for m in user_modules if m in VALID_MODULES]
```
2. **Add @login_required Decorator** - Use Flask-Login instead of manual session check
```python
@bp.route('/dashboard')
@login_required
def dashboard():
```
3. **Validate Session Data** - Check that critical session fields exist
```python
try:
user_role = session.get('role')
if not user_role:
flash('Invalid session data', 'danger')
return redirect(url_for('main.login'))
```
### Priority 2 (High):
4. **Replace Debug Print** - Use proper logging
```python
from app.logging_config import get_logger
logger = get_logger('dashboard')
logger.debug(f"User {session.get('user')} accessed dashboard")
```
5. **Add Permission Checks to Module Routes** - Add decorators to protect actual module entry points
```python
@bp.route('/main_scan')
@requires_quality_module # This should be enforced
def main_scan():
```
6. **Dynamic Module List** - Build module list from database instead of hardcoding
```python
AVAILABLE_MODULES = {
'quality': {'name': 'Quality Module', 'icon': '📋'},
'warehouse': {'name': 'Warehouse Module', 'icon': '📦'},
# ...
}
```
### Priority 3 (Medium):
7. **Add Error Handler** - Catch exceptions gracefully
```python
try:
# existing code
except Exception as e:
logger.error(f"Dashboard error: {e}")
flash('Error loading dashboard', 'danger')
return redirect(url_for('main.login'))
```
8. **Show User Info Card** - Add a card showing current user info, role, and assigned modules
- Helps users understand what they have access to
- Good for support/debugging
9. **Add Module Status Indicators** - Show if modules are available/unavailable
- Green checkmark for enabled modules
- Gray for disabled modules (with reason)
10. **Activity Log Card** - Show recent activity (last logins, module access)
- Improves security awareness
- Helps track usage
---
## 7. DATABASE CONNECTIVITY CHECK
### Current Implementation:
- Dashboard itself does NOT connect to database
- Relies entirely on session data set during login
- Session data is passed from `users` table during login
### Potential Issue:
- If user's modules are updated in database, changes won't reflect until next login
- No "refresh" mechanism
### Recommendation:
- Consider lazy-loading modules from database on dashboard load
- OR implement session refresh mechanism
---
## 8. NAVIGATION VERIFICATION
### All Links Work To:
✅ `/main_scan` - Quality Module entry
✅ `/reports` - Reports/Quality Reports
✅ `/warehouse` - Warehouse Module
✅ `/etichete` - Labels Module
✅ `/daily_mirror/*` - Daily Mirror Hub
✅ `/settings` - Admin Settings
✅ Header: Go to Dashboard, Logout links
✅ Floating Help button to documentation
---
## 9. RESPONSIVE DESIGN VERIFICATION
✅ Desktop (1200px+): 3-column layout
✅ Tablet (768px-1199px): Likely 2 columns (verify CSS breakpoints)
✅ Mobile (<768px): Single column
✅ Dark mode toggle functional
✅ Help button accessible on all sizes
---
## 10. SECURITY ASSESSMENT
### Current Security:
- Session-based authentication
- No CSRF token visible (verify in base.html form handling)
- Role-based access control
### Concerns:
⚠️ Direct URL access might bypass dashboard (no decorator on module routes)
⚠️ No session timeout visible
⚠️ No IP/device validation
⚠️ Hard-coded module list for superadmin
---
## SUMMARY TABLE
| Aspect | Status | Risk Level |
|--------|--------|------------|
| Authentication | ✅ Working | Low |
| Authorization | ⚠️ Partial | Medium |
| Error Handling | ❌ Missing | Medium |
| Code Quality | ✅ Good | Low |
| Performance | ✅ Good | Low |
| Responsive Design | ✅ Good | Low |
| Database Sync | ⚠️ Async | Medium |
| Documentation | ✅ Present | Low |
---
## NEXT STEPS FOR USER REVIEW
1. **Test all module links** - Click each card's button and verify:
- Module page loads
- User has correct permissions
- No 404 or permission errors
2. **Test with different user roles**:
- Superadmin (should see all modules)
- Admin (should see all modules)
- Manager (should see assigned modules only)
- Worker (should see limited modules)
3. **Test responsive design**:
- Resize browser to mobile size
- Check card layout
- Verify buttons still work
4. **Test dark mode**:
- Click theme toggle
- Verify colors are readable
- Check card contrast
5. **Check session persistence**:
- Login, navigate away, come back
- Verify dashboard still loads without re-login

View File

@@ -0,0 +1,437 @@
# SETTINGS PAGE - COMPREHENSIVE ANALYSIS REPORT
## 1. PAGE OVERVIEW
**Location:** `/settings` route
**Route Handler:** `routes.py` (line 319) → `settings.py` (line 199 `settings_handler()`)
**Template:** `templates/settings.html` (2852 lines)
**Purpose:** Admin/Superadmin configuration hub for user management, database settings, backups, and system maintenance
---
## 2. FUNCTIONALITY ANALYSIS
### Backend Logic (`settings.py` lines 199-250):
```
Function: settings_handler()
- Checks if user is superadmin (only superadmin allowed)
- Fetches all users from external MariaDB database
- Loads external database configuration from external_server.conf
- Converts user data to dictionaries for template rendering
```
### What It Does:
The settings page provides 6 major functional areas:
1. **User Management (Legacy)**
- Lists all users from database
- Edit/Delete users
- Create new users
- Shows username, role, email
2. **Simplified User Management**
- Modern 4-tier system (Superadmin → Admin → Manager → Worker)
- Module-based permissions (Quality, Warehouse, Labels)
- Links to `/user_management_simple` route
3. **External Server Settings**
- Configure database connection details
- Server domain/IP, port, database name, username, password
- Saves to `external_server.conf`
4. **Print Extension Management** (Superadmin only)
- Manage QZ Tray printer pairing keys
- Control direct printing functionality
5. **Maintenance & Cleanup** (Admin+ only)
- **Log File Management**: Auto-delete old log files (7-365 days configurable)
- **System Storage Info**: Shows usage for logs, database, backups
- **Database Table Management**: Clear/truncate individual tables with caution warnings
6. **Database Backup Management** (Admin+ only)
- **Quick Actions**: Full backup, Data-only backup, Refresh
- **Backup Schedules**: Create automated backup schedules (daily/weekly/monthly)
- **Per-Table Backup/Restore**: Backup and restore individual tables
- **Full Database Restore**: Restore entire database from backup (Superadmin only)
---
## 3. FRONTEND STRUCTURE
### Template Layout (`settings.html`):
- **Card-based layout** with multiple collapsible sections
- **6 main cards**: User Management, External Server, User & Permissions, Print Extension, Maintenance & Cleanup, Database Backups
- **Responsive grid layout** for backup management sections
- **Status indicators** showing active/inactive features
### CSS Styling:
- Uses inline CSS styles (heavy reliance on style attributes)
- **Color coding**: Green (#4caf50) for safe actions, Orange (#ff9800) for caution, Red (#ff5722) for dangerous operations
- **Dark mode support** with CSS variables
- **Responsive grid** for desktop and mobile
- **Storage stat cards** with gradient backgrounds
### Features:
✅ Toggle-able sections (collapsible backup management)
✅ Live storage information display
✅ Status messages with color-coded backgrounds
✅ Confirmation dialogs for dangerous operations
✅ Progress indicators for long-running tasks
✅ Caution warnings for data-destructive operations
---
## 4. ISSUES & BUGS FOUND
### 🔴 CRITICAL ISSUES:
1. **Weak Authorization Check**
- **Problem**: `settings_handler()` checks only if `session['role'] == 'superadmin'`
- **Line**: `settings.py:200`
- **Impact**: Admin users cannot access settings even though some features should be admin-accessible
- **Severity**: CRITICAL
2. **Password Visible in Template**
- **Problem**: Password field in External Server Settings is plain text
- **Line**: `settings.html:35 <input type="password">`
- **Impact**: Password is visible in browser history, cached, logged
- **Severity**: HIGH (Security Issue)
3. **Missing SQL Injection Protection**
- **Problem**: Database table names in truncate/backup operations might not be validated
- **Impact**: Potential SQL injection if table names come from user input
- **Severity**: HIGH
4. **No CSRF Token Visible**
- **Problem**: Form submissions don't show CSRF token verification
- **Line**: `settings.html:22 <form method="POST"...>`
- **Impact**: Forms vulnerable to CSRF attacks
- **Severity**: HIGH
### 🟡 MODERATE ISSUES:
5. **Hardcoded Role Check in Template**
- **Problem**: Template checks `session.role == 'superadmin'` directly instead of using decorator
- **Line**: `settings.html:82, 191, etc.`
- **Impact**: Permission logic scattered in template instead of centralized in backend
- **Severity**: MEDIUM
6. **Missing Error Handling in settings_handler()**
- **Problem**: No try-catch around entire function, only for database operations
- **Impact**: Template errors will crash the page
- **Severity**: MEDIUM
7. **Connection Not Properly Closed**
- **Problem**: `conn.close()` called after cursor operations but exceptions might leak connections
- **Line**: `settings.py:243`
- **Impact**: Database connection pool exhaustion over time
- **Severity**: MEDIUM
8. **Inline CSS Over-usage**
- **Problem**: 2852 line template with 90% inline styles
- **Impact**: Hard to maintain, slow to load, inconsistent styling, large file size
- **Severity**: MEDIUM
9. **No Input Validation in Form**
- **Problem**: External server settings form doesn't validate port number format or server connectivity before saving
- **Impact**: Bad configuration saved, app breaks on next restart
- **Severity**: MEDIUM
### 🟢 MINOR ISSUES:
10. **Inconsistent Column Names**
- **Problem**: Some user queries select 'modules' column but it might not exist on all user rows
- **Line**: `settings.py:224`
- **Impact**: None if column exists, but code assumes it does
- **Severity**: LOW
11. **Magic Strings**
- **Problem**: Database table names, role names, module names hardcoded throughout
- **Impact**: Hard to refactor, duplicate code
- **Severity**: LOW
12. **Dead Code in Deprecated Function**
- **Problem**: `get_external_db_connection()` marked deprecated but still used
- **Line**: `settings.py:254`
- **Impact**: Confusing for maintainers
- **Severity**: LOW
13. **Print Statement Logging**
- **Problem**: Uses `print()` instead of proper logger
- **Impact**: Not captured in logging system
- **Severity**: LOW
14. **No Loading States**
- **Problem**: Long operations (backups, restores) might appear frozen
- **Impact**: Users might click buttons multiple times
- **Severity**: LOW
---
## 5. CODE QUALITY ASSESSMENT
### Strengths:
✅ Comprehensive feature set
✅ Good UI/UX with status indicators
✅ Caution warnings for dangerous operations
✅ Separate "Legacy" vs "Simplified" user management
✅ Supports dark mode
✅ Responsive design
✅ Detailed backup management capabilities
### Weaknesses:
❌ Critical authorization issues
❌ Security vulnerabilities (CSRF, SQL injection risks)
❌ Massive template file with inline styles
❌ Weak error handling
❌ Mixed permissions logic (template + backend)
❌ Poor code organization
❌ Connection pool management issues
❌ No input validation
---
## 6. PERMISSIONS & ACCESS CONTROL
### Current Implementation:
```
settings_handler() → superadmin only → shows ALL features
template → checks session['role'] == 'superadmin' for some sections
```
### Issues:
- **Admin users cannot access** even though some features are admin-appropriate
- **Backup management** should be available to admins
- **Log cleanup** should be available to admins
- **User management** should be restricted to admin+ (currently superadmin only)
### Recommended Roles:
- **Superadmin**: Full access (everything)
- **Admin**: User management, settings updates, backups, cleanup (everything except pairing keys)
- **Manager/Worker**: No access
---
## 7. DATABASE OPERATIONS ANALYSIS
### Tables Accessed:
1. `users` - Read/write (fetch all users, create, edit, delete)
2. `roles` - Possibly read (in user management)
3. Application tables (in truncate operations) - Write (truncate/clear)
4. Any table in database (backup/restore) - Read/Write
### Potential Risks:
⚠️ Truncating tables without proper backup check
⚠️ Restoring database without current backup
⚠️ No transaction handling for backup/restore operations
⚠️ No verification of backup integrity before restore
---
## 8. SECURITY ASSESSMENT
### VULNERABILITIES FOUND:
**Critical (Fix Immediately):**
1. CSRF Token missing on forms
2. Password field plain text in form (visible in browser)
3. Authorization only checks superadmin, not generic admin
**High (Fix Soon):**
1. SQL injection risk on table operations
2. No input validation on external server settings
3. Weak connection handling
**Medium (Fix Later):**
1. Permissions scattered in template
2. No rate limiting on dangerous operations (truncate, restore)
3. No audit logging for admin actions
---
## 9. JAVASCRIPT FUNCTIONALITY CHECK
The template has heavy JavaScript for:
- Backup creation (AJAX call to `/backup_now_btn`)
- Log cleanup (AJAX call to `/cleanup_logs_now_btn`)
- Table truncation (AJAX call to load and truncate tables)
- Storage info refresh
- Schedule management (create, edit, delete schedules)
- Backup restore operations
**Concerns:**
⚠️ No timeout on long operations
⚠️ No progress bars for backups (might appear frozen)
⚠️ No confirmation dialogs for dangerous operations (truncate table)
⚠️ AJAX calls don't validate authorization client-side
---
## 10. FORM SUBMISSIONS
### Forms Found:
1. **External Server Settings** - POST to `/save_external_db`
- No CSRF token visible
- No input validation
- No test connection button
2. **User Management** (JavaScript-based, not traditional form)
3. **Backup Management** (JavaScript/AJAX)
4. **Log Cleanup** (AJAX button)
---
## SUMMARY TABLE
| Aspect | Status | Risk Level | Notes |
|--------|--------|------------|-------|
| Authentication | ✅ Working | Low | Session checks present |
| Authorization | ❌ Broken | CRITICAL | Only superadmin allowed |
| Error Handling | ⚠️ Partial | Medium | Missing in places |
| Input Validation | ❌ Missing | High | No validation on forms |
| CSRF Protection | ❌ Missing | High | No tokens visible |
| SQL Injection Risk | ⚠️ Possible | High | Table names not validated |
| Code Organization | ❌ Poor | Medium | Massive template, inline CSS |
| Performance | ⚠️ Okay | Low | Might be slow on backups |
| Security | ❌ Weak | CRITICAL | Multiple vulnerabilities |
| Maintainability | ❌ Poor | Medium | Hard to modify |
---
## 11. SUGGESTED IMPROVEMENTS
### Priority 1 (CRITICAL - Fix immediately):
1. **Add CSRF Token to Forms**
```html
<form method="POST" action="...">
{{ csrf_token() }}
<!-- form fields -->
</form>
```
2. **Fix Authorization Logic**
```python
@admin_plus # Use decorator instead
def settings_handler():
# Remove manual superadmin check
```
3. **Validate All Inputs**
```python
# Validate table names against whitelist
ALLOWED_TABLES = ['scan1_orders', 'scanfg_orders', ...]
if table_name not in ALLOWED_TABLES:
return error("Invalid table")
```
4. **Hash/Obscure Password Field**
- Store encrypted in config file
- Show masked dots in form
- Add "show/hide" toggle
### Priority 2 (HIGH - Fix soon):
5. **Refactor to use Decorators**
```python
@bp.route('/settings')
@admin_plus
def settings():
# All admin checks in decorator
```
6. **Extract CSS to Separate File**
- Create `css/settings.css`
- Remove all inline styles
- Reduce template to ~500 lines
7. **Add Input Validation**
- Validate port is integer (1-65535)
- Validate server domain format
- Test connection before saving
8. **Fix Connection Pool**
```python
try:
conn = get_external_db_connection()
# operations
finally:
conn.close() # Ensure closes even on error
```
9. **Add Confirmation Dialogs**
- Truncate table warning
- Restore database warning
- Log cleanup confirmation
10. **Use Logger Instead of Print**
```python
logger = get_logger('settings')
logger.error(f"Error: {e}")
```
### Priority 3 (MEDIUM - Improve):
11. **Add Progress Indicators** for long operations
12. **Add Operation Timeouts** (prevent infinite hangs)
13. **Add Audit Logging** for all admin actions
14. **Add Rate Limiting** on dangerous operations
15. **Split Template** into multiple files (one per feature)
16. **Add Database Connection Test** button
17. **Show Last Backup Date/Size** in UI
18. **Add Backup Integrity Check** before restore
19. **Add Auto-Recovery** for failed backups
20. **Implement Admin-Only Pages** (not just superadmin)
---
## TESTING CHECKLIST
Before using this page:
1. **Security Tests:**
- [ ] Try accessing as non-superadmin user (should be denied)
- [ ] Check if CSRF token is present in network requests
- [ ] Try SQL injection in table name field
- [ ] Verify password field is masked
2. **Functionality Tests:**
- [ ] Create new user and verify in database
- [ ] Edit user and verify changes saved
- [ ] Delete user and verify removed
- [ ] Save external server settings and verify file created
- [ ] Create backup and verify file exists
- [ ] Restore backup and verify data restored
- [ ] Truncate table and verify data cleared
3. **Error Handling Tests:**
- [ ] Break database connection, try to load settings
- [ ] Provide invalid port number
- [ ] Try backup with no disk space
- [ ] Truncate table while backup running
4. **Performance Tests:**
- [ ] Load settings with 1000 users
- [ ] Create backup with large database (>1GB)
- [ ] Check browser memory usage over time
5. **UI/UX Tests:**
- [ ] Test on mobile (responsive)
- [ ] Test dark mode toggle
- [ ] Test all buttons are clickable
- [ ] Verify all status messages appear
---
## NEXT STEPS FOR USER REVIEW
1. **Critical**: Address authorization bug (line 200)
2. **Critical**: Add CSRF token to forms
3. **High**: Fix password visibility issue
4. **High**: Add input validation
5. **Medium**: Refactor template structure
6. **Medium**: Improve error handling
7. **Low**: Migrate to proper logger
8. **Low**: Add nice-to-have features
---