RBAC and Doc updates

This commit is contained in:
James Pattinson
2025-10-13 14:05:01 +00:00
parent f721be7280
commit d4b88e0952
13 changed files with 1400 additions and 208 deletions

View File

@@ -38,23 +38,29 @@ web/
## Usage
### Development
1. Ensure the API is running on port 8000
2. Open `index.html` in a web browser
3. Enter your API token to authenticate
4. Start managing your mailing lists!
### Production (Docker)
The web frontend is served using Nginx and included in the Docker Compose setup.
### Accessing the Interface
**Via Docker (Recommended):**
```bash
# Build and start all services
docker-compose up --build
# Ensure all services are running
sudo docker-compose up -d
# Access the web interface
open http://localhost:3000
```
**For Development:**
You can also open `index.html` directly in a browser, but the API must be running on port 8000.
### Getting Started
1. **Authenticate**: Enter your API_TOKEN (from `.env` file) when prompted
2. **Manage Lists**: Click the "Lists" tab to view and manage mailing lists
3. **Manage Members**: Click the "Members" tab to add and edit member information
4. **Manage Subscriptions**: Click "Subscriptions" button on any member to toggle their list memberships
The interface saves your token in browser storage, so you won't need to re-enter it on subsequent visits.
## Features Overview
### Authentication
@@ -65,24 +71,39 @@ open http://localhost:3000
### Subscription Management (New & Improved!)
#### Member-Centric Subscription Management
The subscription management has been completely overhauled for a much better user experience:
The subscription management has been completely redesigned for the best user experience:
1. **Access Member Subscriptions**: In the Members tab, click the "Subscriptions" button next to any member
2. **Visual Toggle Interface**: See all available mailing lists with modern toggle switches
3. **Intuitive Controls**:
- Green toggle = Member is subscribed
- Gray toggle = Member is not subscribed
- Click anywhere on a list item to toggle subscription
4. **Batch Operations**: Make multiple changes and save them all at once
5. **Real-time Feedback**: The save button shows how many changes you've made
**How to Use:**
1. Navigate to the **Members** tab
2. Find the member you want to manage
3. Click the **"Subscriptions"** button next to their name
4. A modal appears showing all available mailing lists with toggle switches
#### Benefits Over Previous System
- **Much faster** - No need to add subscriptions one by one
**Visual Interface:**
- **Green toggle** = Member is subscribed to this list
- **Gray toggle** = Member is not subscribed to this list
- **Click anywhere** on a list item to toggle subscription on/off
**Batch Operations:**
- Make multiple changes (subscribe to some lists, unsubscribe from others)
- The "Save Changes" button shows how many changes you've made (e.g., "Save 3 Changes")
- All changes are saved together when you click "Save Changes"
- Click "Cancel" to discard all changes
**Benefits:**
-**Fast** - Toggle multiple subscriptions at once
-**Visual** - See all subscriptions at a glance with color coding
-**Intuitive** - Toggle switches work like modern mobile apps
-**Batch operations** - Change multiple subscriptions simultaneously
-**Less error-prone** - Clear visual feedback prevents mistakes
-**Change tracking** - Only saves actual changes, not unchanged items
-**Intuitive** - Works like modern mobile app switches
-**Smart** - Only saves actual changes, not unchanged items
-**Clear** - Shows exactly how many changes you're about to save
#### Alternative: Legacy Bulk Subscription
For power users who prefer the old approach:
1. Go to the **Subscriptions** tab
2. Select list and member from dropdowns
3. Click "Add Subscription"
This is still available but the member-centric approach is much more efficient for managing multiple subscriptions.
### Mailing Lists
- View all mailing lists in a clean table

View File

@@ -19,14 +19,15 @@
</h1>
<div class="auth-section">
<div class="auth-controls" id="authControls">
<input type="password" id="apiToken" placeholder="Enter API Token" class="token-input">
<input type="text" id="username" placeholder="Username" class="token-input">
<input type="password" id="password" placeholder="Password" class="token-input">
<button class="btn btn-primary" id="loginBtn">Login</button>
</div>
<div class="user-info" id="userInfo" style="display: none;">
<span class="status-indicator">
<i class="fas fa-check-circle"></i>
Connected
</span>
<div class="user-details">
<span class="user-name" id="currentUsername">User</span>
<span class="user-role" id="currentUserRole">role</span>
</div>
<button class="btn btn-secondary" id="logoutBtn">Logout</button>
</div>
</div>
@@ -38,7 +39,7 @@
<main class="main-content" id="mainContent" style="display: none;">
<div class="container">
<!-- Navigation Tabs -->
<nav class="tab-nav">
<nav class="tab-nav" id="tabNav">
<button class="tab-btn active" data-tab="lists">
<i class="fas fa-list"></i>
Mailing Lists
@@ -47,6 +48,10 @@
<i class="fas fa-users"></i>
Members
</button>
<button class="tab-btn" data-tab="users" id="usersTab" style="display: none;">
<i class="fas fa-user-shield"></i>
Users
</button>
</nav>
<!-- Notification Area -->
@@ -126,6 +131,35 @@
</div>
</div>
<!-- Users Tab (Admin Only) -->
<div class="tab-content" id="users-tab">
<div class="section-header">
<h2>User Management</h2>
<button class="btn btn-primary" id="addUserBtn">
<i class="fas fa-plus"></i>
Add User
</button>
</div>
<div class="data-table">
<table class="table" id="usersTable">
<thead>
<tr>
<th>Username</th>
<th>Role</th>
<th>Created</th>
<th>Last Login</th>
<th>Status</th>
<th>Actions</th>
</tr>
</thead>
<tbody id="usersTableBody">
<!-- Dynamic content -->
</tbody>
</table>
</div>
</div>
</div>
</main>
@@ -462,6 +496,51 @@
</div>
</div>
<!-- Add/Edit User Modal -->
<div class="modal" id="userModal">
<div class="modal-content">
<div class="modal-header">
<h3 id="userModalTitle">Add User</h3>
<button class="modal-close" id="userModalClose">
<i class="fas fa-times"></i>
</button>
</div>
<form id="userForm">
<div class="form-group">
<label for="userName">Username *</label>
<input type="text" id="userName" name="userName" required>
</div>
<div class="form-group">
<label for="userPassword">Password *</label>
<input type="password" id="userPassword" name="userPassword" required>
<div class="form-help" id="passwordHelp">
Leave blank to keep current password (when editing)
</div>
</div>
<div class="form-group">
<label for="userRole">Role *</label>
<select id="userRole" name="userRole" required>
<option value="">Select a role...</option>
<option value="administrator">Administrator - Full access including user management</option>
<option value="operator">Operator - Read/write access to lists and members</option>
<option value="read-only">Read-Only - View-only access</option>
</select>
</div>
<div class="form-group">
<label class="checkbox-label">
<input type="checkbox" id="userActive" name="userActive" checked>
<span class="checkmark"></span>
Active
</label>
</div>
<div class="modal-actions">
<button type="button" class="btn btn-secondary" id="userCancelBtn">Cancel</button>
<button type="submit" class="btn btn-primary" id="userSubmitBtn">Save</button>
</div>
</form>
</div>
</div>
<!-- Confirmation Modal -->
<div class="modal" id="confirmModal">
<div class="modal-content">

View File

@@ -145,6 +145,25 @@ body {
gap: var(--space-3);
}
.user-details {
display: flex;
flex-direction: column;
align-items: flex-end;
gap: var(--space-1);
}
.user-name {
font-weight: 500;
font-size: var(--font-size-sm);
color: var(--gray-900);
}
.user-role {
font-size: var(--font-size-xs);
color: var(--gray-500);
text-transform: capitalize;
}
.status-indicator {
display: flex;
align-items: center;
@@ -402,6 +421,32 @@ body {
color: var(--gray-600);
}
/* Role badges */
.role-badge {
display: inline-flex;
align-items: center;
padding: var(--space-1) var(--space-2);
border-radius: var(--radius-sm);
font-size: var(--font-size-xs);
font-weight: 500;
text-transform: capitalize;
}
.role-badge.role-administrator {
background: #fef3c7;
color: #92400e;
}
.role-badge.role-operator {
background: #dbeafe;
color: #1e40af;
}
.role-badge.role-read-only {
background: var(--gray-100);
color: var(--gray-600);
}
/* Action buttons in tables */
.action-buttons {
display: flex;

View File

@@ -104,6 +104,63 @@ class APIClient {
return this.request('/');
}
// Authentication API
async login(username, password) {
const response = await this.request('/auth/login', {
method: 'POST',
body: JSON.stringify({
username: username,
password: password
})
});
if (response.access_token) {
this.setToken(response.access_token);
}
return response;
}
async logout() {
try {
await this.request('/auth/logout', {
method: 'POST'
});
} catch (error) {
// Ignore logout errors, we'll clear the token anyway
}
this.clearToken();
}
async getCurrentUser() {
return this.request('/auth/me');
}
// User management API
async getUsers() {
return this.request('/users');
}
async createUser(userData) {
return this.request('/users', {
method: 'POST',
body: JSON.stringify(userData)
});
}
async updateUser(userId, userData) {
return this.request(`/users/${userId}`, {
method: 'PATCH',
body: JSON.stringify(userData)
});
}
async deleteUser(userId) {
return this.request(`/users/${userId}`, {
method: 'DELETE'
});
}
// Mailing Lists API
async getLists() {
return this.request('/lists');

View File

@@ -6,8 +6,10 @@
class MailingListApp {
constructor() {
this.isAuthenticated = false;
this.currentUser = null;
this.lists = [];
this.members = [];
this.users = [];
this.subscriptions = new Map(); // list_id -> members[]
this.initializeApp();
@@ -20,9 +22,10 @@ class MailingListApp {
this.setupEventListeners();
// Check for saved token
const savedToken = localStorage.getItem('apiToken');
const savedToken = localStorage.getItem('authToken');
if (savedToken) {
await this.login(savedToken, false);
apiClient.setToken(savedToken);
await this.checkCurrentUser();
}
}
@@ -39,8 +42,14 @@ class MailingListApp {
this.logout();
});
// Enter key in token input
document.getElementById('apiToken').addEventListener('keypress', (e) => {
// Enter key in login inputs
document.getElementById('username').addEventListener('keypress', (e) => {
if (e.key === 'Enter') {
this.handleLogin();
}
});
document.getElementById('password').addEventListener('keypress', (e) => {
if (e.key === 'Enter') {
this.handleLogin();
}
@@ -50,54 +59,72 @@ class MailingListApp {
document.getElementById('showBulkImportBtn').addEventListener('click', () => {
uiManager.showBulkImportModal();
});
// Add user button (admin only)
document.getElementById('addUserBtn').addEventListener('click', () => {
uiManager.showUserModal();
});
}
/**
* Check if current user is still valid
*/
async checkCurrentUser() {
try {
const user = await apiClient.getCurrentUser();
this.currentUser = user;
this.isAuthenticated = true;
this.showAuthenticatedUI();
await this.loadData();
} catch (error) {
// Token is invalid, clear it
this.logout();
}
}
/**
* Handle login button click
*/
async handleLogin() {
const tokenInput = document.getElementById('apiToken');
const token = tokenInput.value.trim();
const usernameInput = document.getElementById('username');
const passwordInput = document.getElementById('password');
const username = usernameInput.value.trim();
const password = passwordInput.value.trim();
if (!token) {
uiManager.showNotification('Please enter an API token', 'error');
if (!username || !password) {
uiManager.showNotification('Please enter both username and password', 'error');
return;
}
await this.login(token, true);
await this.login(username, password);
}
/**
* Authenticate with API
*/
async login(token, saveToken = true) {
async login(username, password) {
try {
uiManager.setLoading(true);
// Set token and test authentication
apiClient.setToken(token);
await apiClient.testAuth();
// Authentication successful
// Login and get token
const response = await apiClient.login(username, password);
this.currentUser = response.user;
this.isAuthenticated = true;
if (saveToken) {
localStorage.setItem('apiToken', token);
}
// Save token
localStorage.setItem('authToken', response.access_token);
this.showAuthenticatedUI();
await this.loadData();
uiManager.showNotification('Successfully connected to API', 'success');
uiManager.showNotification(`Welcome back, ${this.currentUser.username}!`, 'success');
} catch (error) {
this.isAuthenticated = false;
this.currentUser = null;
apiClient.clearToken();
localStorage.removeItem('authToken');
if (saveToken) {
localStorage.removeItem('apiToken');
}
uiManager.handleError(error, 'Authentication failed');
uiManager.handleError(error, 'Login failed');
} finally {
uiManager.setLoading(false);
}
@@ -106,10 +133,17 @@ class MailingListApp {
/**
* Logout
*/
logout() {
async logout() {
try {
await apiClient.logout();
} catch (error) {
// Ignore logout errors
}
this.isAuthenticated = false;
this.currentUser = null;
apiClient.clearToken();
localStorage.removeItem('apiToken');
localStorage.removeItem('authToken');
this.showUnauthenticatedUI();
uiManager.showNotification('Logged out successfully', 'info');
@@ -123,8 +157,23 @@ class MailingListApp {
document.getElementById('userInfo').style.display = 'flex';
document.getElementById('mainContent').style.display = 'block';
// Clear token input
document.getElementById('apiToken').value = '';
// Clear login inputs
document.getElementById('username').value = '';
document.getElementById('password').value = '';
// Update user info display
if (this.currentUser) {
document.getElementById('currentUsername').textContent = this.currentUser.username;
document.getElementById('currentUserRole').textContent = this.currentUser.role;
// Show/hide admin-only features
const isAdmin = this.currentUser.role === 'administrator';
document.getElementById('usersTab').style.display = isAdmin ? 'block' : 'none';
// Show/hide write access features
const hasWriteAccess = this.currentUser.role === 'administrator' || this.currentUser.role === 'operator';
this.updateUIForPermissions(hasWriteAccess);
}
}
/**
@@ -136,6 +185,22 @@ class MailingListApp {
document.getElementById('mainContent').style.display = 'none';
}
/**
* Update UI elements based on user permissions
*/
updateUIForPermissions(hasWriteAccess) {
// Disable/enable write action buttons
const writeButtons = document.querySelectorAll('[data-requires-write]');
writeButtons.forEach(button => {
button.style.display = hasWriteAccess ? '' : 'none';
});
// Update button attributes for later reference
document.getElementById('addListBtn').setAttribute('data-requires-write', '');
document.getElementById('addMemberBtn').setAttribute('data-requires-write', '');
document.getElementById('showBulkImportBtn').setAttribute('data-requires-write', '');
}
/**
* Load all data from API
*/
@@ -154,12 +219,25 @@ class MailingListApp {
this.lists = lists;
this.members = members;
// Load users if admin
if (this.currentUser && this.currentUser.role === 'administrator') {
try {
this.users = await apiClient.getUsers();
} catch (error) {
console.warn('Failed to load users:', error);
this.users = [];
}
}
// Load subscriptions for each list
await this.loadSubscriptions();
// Render all views
this.renderLists();
this.renderMembers();
if (this.currentUser && this.currentUser.role === 'administrator') {
this.renderUsers();
}
} catch (error) {
uiManager.handleError(error, 'Failed to load data');
@@ -210,6 +288,8 @@ class MailingListApp {
return;
}
const hasWriteAccess = this.currentUser && (this.currentUser.role === 'administrator' || this.currentUser.role === 'operator');
this.lists.forEach(list => {
const row = document.createElement('tr');
const memberCount = this.subscriptions.get(list.list_id)?.length || 0;
@@ -242,24 +322,27 @@ class MailingListApp {
const statusCell = row.cells[4];
statusCell.appendChild(uiManager.createStatusBadge(list.active));
// Add action buttons
// Add action buttons only for users with write access
const actionsCell = row.cells[5].querySelector('.action-buttons');
const editBtn = uiManager.createActionButton('Edit', 'edit', 'btn-secondary', () => {
uiManager.showListModal(list);
});
if (hasWriteAccess) {
const editBtn = uiManager.createActionButton('Edit', 'edit', 'btn-secondary', () => {
uiManager.showListModal(list);
});
const deleteBtn = uiManager.createActionButton('Delete', 'trash', 'btn-danger', () => {
uiManager.showConfirmation(
`Are you sure you want to delete the mailing list "${list.list_name}"? This action cannot be undone.`,
async () => {
await this.deleteList(list.list_id);
}
);
});
actionsCell.appendChild(editBtn);
actionsCell.appendChild(deleteBtn);
}
const deleteBtn = uiManager.createActionButton('Delete', 'trash', 'btn-danger', () => {
uiManager.showConfirmation(
`Are you sure you want to delete the mailing list "${list.list_name}"? This action cannot be undone.`,
async () => {
await this.deleteList(list.list_id);
}
);
});
actionsCell.appendChild(editBtn);
actionsCell.appendChild(deleteBtn);
tbody.appendChild(row);
});
}
@@ -287,6 +370,8 @@ class MailingListApp {
return;
}
const hasWriteAccess = this.currentUser && (this.currentUser.role === 'administrator' || this.currentUser.role === 'operator');
this.members.forEach(member => {
const row = document.createElement('tr');
@@ -340,23 +425,108 @@ class MailingListApp {
uiManager.showMemberSubscriptionsModal(member);
});
// Only show edit/delete buttons for users with write access
if (hasWriteAccess) {
const editBtn = uiManager.createActionButton('Edit', 'edit', 'btn-secondary', () => {
uiManager.showMemberModal(member);
});
const deleteBtn = uiManager.createActionButton('Delete', 'trash', 'btn-danger', () => {
uiManager.showConfirmation(
`Are you sure you want to delete the member "${member.name}"? This will remove them from all mailing lists.`,
async () => {
await this.deleteMember(member.member_id);
}
);
});
actionsCell.appendChild(subscriptionsBtn);
actionsCell.appendChild(editBtn);
actionsCell.appendChild(deleteBtn);
} else {
actionsCell.appendChild(subscriptionsBtn);
}
tbody.appendChild(row);
});
}
/**
* Render users table (admin only)
*/
renderUsers() {
const tbody = document.getElementById('usersTableBody');
tbody.innerHTML = '';
if (this.users.length === 0) {
tbody.innerHTML = `
<tr>
<td colspan="6" class="text-center text-muted">
No users found. <a href="#" id="createFirstUser">Create your first user</a>
</td>
</tr>
`;
document.getElementById('createFirstUser').addEventListener('click', (e) => {
e.preventDefault();
uiManager.showUserModal();
});
return;
}
this.users.forEach(user => {
const row = document.createElement('tr');
// Format dates
const createdAt = new Date(user.created_at).toLocaleDateString();
const lastLogin = user.last_login ? new Date(user.last_login).toLocaleDateString() : 'Never';
row.innerHTML = `
<td>
<div class="font-medium">${uiManager.escapeHtml(user.username)}</div>
</td>
<td>
<span class="role-badge role-${user.role}">${user.role.replace('-', ' ')}</span>
</td>
<td>
<div class="text-sm text-muted">${createdAt}</div>
</td>
<td>
<div class="text-sm text-muted">${lastLogin}</div>
</td>
<td></td>
<td>
<div class="action-buttons"></div>
</td>
`;
// Add status badge
const statusCell = row.cells[4];
statusCell.appendChild(uiManager.createStatusBadge(user.active));
// Add action buttons
const actionsCell = row.cells[5].querySelector('.action-buttons');
const editBtn = uiManager.createActionButton('Edit', 'edit', 'btn-secondary', () => {
uiManager.showMemberModal(member);
uiManager.showUserModal(user);
});
const deleteBtn = uiManager.createActionButton('Delete', 'trash', 'btn-danger', () => {
uiManager.showConfirmation(
`Are you sure you want to delete the member "${member.name}"? This will remove them from all mailing lists.`,
async () => {
await this.deleteMember(member.member_id);
}
);
});
// Don't allow deletion of current user
if (user.user_id !== this.currentUser.user_id) {
const deleteBtn = uiManager.createActionButton('Delete', 'trash', 'btn-danger', () => {
uiManager.showConfirmation(
`Are you sure you want to delete the user "${user.username}"? This action cannot be undone.`,
async () => {
await this.deleteUser(user.user_id);
}
);
});
actionsCell.appendChild(editBtn);
actionsCell.appendChild(deleteBtn);
} else {
actionsCell.appendChild(editBtn);
}
// Append all buttons
actionsCell.appendChild(subscriptionsBtn);
actionsCell.appendChild(editBtn);
actionsCell.appendChild(deleteBtn);
tbody.appendChild(row);
});
}
@@ -410,6 +580,22 @@ class MailingListApp {
uiManager.setLoading(false);
}
}
/**
* Delete a user
*/
async deleteUser(userId) {
try {
uiManager.setLoading(true);
await apiClient.deleteUser(userId);
uiManager.showNotification('User deleted successfully', 'success');
await this.loadData();
} catch (error) {
uiManager.handleError(error, 'Failed to delete user');
} finally {
uiManager.setLoading(false);
}
}
}
// Initialize the application when DOM is loaded

View File

@@ -57,6 +57,10 @@ class UIManager {
this.showMemberModal();
});
document.getElementById('addUserBtn').addEventListener('click', () => {
this.showUserModal();
});
// Member subscriptions modal
@@ -88,6 +92,11 @@ class UIManager {
this.handleSubscriptionFormSubmit();
});
document.getElementById('userForm').addEventListener('submit', (e) => {
e.preventDefault();
this.handleUserFormSubmit();
});
// Confirmation modal
document.getElementById('confirmOkBtn').addEventListener('click', () => {
if (this.confirmCallback) {
@@ -245,6 +254,42 @@ class UIManager {
this.showModal(modal);
}
/**
* Show user modal (add/edit)
*/
showUserModal(userData = null) {
const modal = document.getElementById('userModal');
const title = document.getElementById('userModalTitle');
const form = document.getElementById('userForm');
const passwordHelp = document.getElementById('passwordHelp');
const passwordField = document.getElementById('userPassword');
if (userData) {
// Edit mode
title.textContent = 'Edit User';
document.getElementById('userName').value = userData.username;
document.getElementById('userName').readOnly = true; // Can't change username
passwordField.placeholder = 'Leave blank to keep current password';
passwordField.required = false;
passwordHelp.style.display = 'block';
document.getElementById('userRole').value = userData.role;
document.getElementById('userActive').checked = userData.active;
this.currentEditingItem = userData;
} else {
// Add mode
title.textContent = 'Add User';
form.reset();
document.getElementById('userName').readOnly = false;
passwordField.placeholder = 'Password';
passwordField.required = true;
passwordHelp.style.display = 'none';
document.getElementById('userActive').checked = true;
this.currentEditingItem = null;
}
this.showModal(modal);
}
/**
* Show subscription modal
*/
@@ -400,6 +445,50 @@ class UIManager {
}
}
/**
* Handle user form submission
*/
async handleUserFormSubmit() {
const form = document.getElementById('userForm');
const formData = new FormData(form);
const userData = {
username: formData.get('userName'),
role: formData.get('userRole'),
active: formData.get('userActive') === 'on'
};
// Only include password if it's provided (for updates, empty means no change)
const password = formData.get('userPassword');
if (password) {
userData.password = password;
}
try {
this.setLoading(true);
if (this.currentEditingItem) {
// Update existing user
await apiClient.updateUser(this.currentEditingItem.user_id, userData);
this.showNotification('User updated successfully', 'success');
} else {
// Create new user
if (!userData.password) {
throw new Error('Password is required for new users');
}
await apiClient.createUser(userData);
this.showNotification('User created successfully', 'success');
}
this.closeModal(document.getElementById('userModal'));
await window.app.loadData();
} catch (error) {
this.handleError(error, 'Failed to save user');
} finally {
this.setLoading(false);
}
}
/**
* Show member subscriptions modal
*/