Skip to content

SeaweedFS is a distributed storage system for object storage (S3), file systems, Iceberg table buckets, and Lance vector buckets, designed to handle billions of files with O(1) disk access and effortless horizontal scaling.

Fix bucket permission persistence in Admin UI (#8049)

Chris Ludbde8983a71f
diff --git a/weed/admin/static/js/admin.js b/weed/admin/static/js/admin.js
index 5d74f6e40c..6dc11380cd 100644
--- a/weed/admin/static/js/admin.js
+++ b/weed/admin/static/js/admin.js
@@ -2095,388 +2095,95 @@ function escapeHtml(text) {
return text.replace(/[&<>"']/g, function (m) { return map[m]; });
}
+
// ============================================================================
-// USER MANAGEMENT FUNCTIONS
+// SHARED MODAL UTILITIES FOR ACCESS KEY MANAGEMENT
// ============================================================================
-// Global variables for user management
-let currentEditingUser = '';
-let currentAccessKeysUser = '';
-
-// User Management Functions
-
-async function handleCreateUser() {
- const form = document.getElementById('createUserForm');
- const formData = new FormData(form);
-
- // Get selected actions
- const actionsSelect = document.getElementById('actions');
- const selectedActions = Array.from(actionsSelect.selectedOptions).map(option => option.value);
-
- const userData = {
- username: formData.get('username'),
- email: formData.get('email'),
- actions: selectedActions,
- generate_key: formData.get('generateKey') === 'on'
- };
-
- try {
- const response = await fetch('/api/users', {
- method: 'POST',
- headers: {
- 'Content-Type': 'application/json',
- },
- body: JSON.stringify(userData)
- });
-
- if (response.ok) {
- const result = await response.json();
- showSuccessMessage('User created successfully');
-
- // Show the created access key if generated
- if (result.user && result.user.access_key) {
- showNewAccessKeyModal(result.user);
- }
-
- // Close modal and refresh page
- const modal = bootstrap.Modal.getInstance(document.getElementById('createUserModal'));
- modal.hide();
- form.reset();
- setTimeout(() => window.location.reload(), 1000);
- } else {
- const error = await response.json();
- showErrorMessage('Failed to create user: ' + (error.error || 'Unknown error'));
- }
- } catch (error) {
- console.error('Error creating user:', error);
- showErrorMessage('Failed to create user: ' + error.message);
- }
+// HTML escaping helper to prevent XSS
+function escapeHtmlForAttribute(text) {
+ if (!text) return '';
+ const div = document.createElement('div');
+ div.textContent = text;
+ return div.innerHTML.replace(/"/g, '&quot;').replace(/'/g, '&#39;');
}
-async function editUser(username) {
- currentEditingUser = username;
-
- try {
- const response = await fetch(`/api/users/${username}`);
- if (response.ok) {
- const user = await response.json();
-
- // Populate edit form
- document.getElementById('editUsername').value = username;
- document.getElementById('editEmail').value = user.email || '';
-
- // Set selected actions
- const actionsSelect = document.getElementById('editActions');
- Array.from(actionsSelect.options).forEach(option => {
- option.selected = user.actions && user.actions.includes(option.value);
- });
-
- // Set selected policies
- const policiesSelect = document.getElementById('editPolicies');
- if (policiesSelect) {
- Array.from(policiesSelect.options).forEach(option => {
- option.selected = user.policy_names && user.policy_names.includes(option.value);
- });
- }
-
- // Show modal
- const modal = new bootstrap.Modal(document.getElementById('editUserModal'));
- modal.show();
- } else {
- showErrorMessage('Failed to load user details');
- }
- } catch (error) {
- console.error('Error loading user:', error);
- showErrorMessage('Failed to load user details');
- }
-}
-
-async function handleUpdateUser() {
- const form = document.getElementById('editUserForm');
- const formData = new FormData(form);
-
- // Get selected actions
- const actionsSelect = document.getElementById('editActions');
- const selectedActions = Array.from(actionsSelect.selectedOptions).map(option => option.value);
-
- // Get selected policies
- const policiesSelect = document.getElementById('editPolicies');
- const selectedPolicies = policiesSelect ? Array.from(policiesSelect.selectedOptions).map(option => option.value) : [];
+function showModal(title, content) {
+ // Create a dynamic modal
+ const modalId = 'dynamicModal_' + Date.now();
- const userData = {
- email: formData.get('email'),
- actions: selectedActions,
- policy_names: selectedPolicies
- };
+ // Create modal structure using DOM to prevent XSS in title
+ const modalDiv = document.createElement('div');
+ modalDiv.className = 'modal fade';
+ modalDiv.id = modalId;
+ modalDiv.setAttribute('tabindex', '-1');
+ modalDiv.setAttribute('role', 'dialog');
- try {
- const response = await fetch(`/api/users/${currentEditingUser}`, {
- method: 'PUT',
- headers: {
- 'Content-Type': 'application/json',
- },
- body: JSON.stringify(userData)
- });
+ const modalDialog = document.createElement('div');
+ modalDialog.className = 'modal-dialog';
+ modalDialog.setAttribute('role', 'document');
- if (response.ok) {
- showSuccessMessage('User updated successfully');
+ const modalContent = document.createElement('div');
+ modalContent.className = 'modal-content';
- // Close modal and refresh page
- const modal = bootstrap.Modal.getInstance(document.getElementById('editUserModal'));
- modal.hide();
- setTimeout(() => window.location.reload(), 1000);
- } else {
- const error = await response.json();
- showErrorMessage('Failed to update user: ' + (error.error || 'Unknown error'));
- }
- } catch (error) {
- console.error('Error updating user:', error);
- showErrorMessage('Failed to update user: ' + error.message);
- }
-}
+ // Header
+ const modalHeader = document.createElement('div');
+ modalHeader.className = 'modal-header';
-function confirmDeleteUser(username) {
- confirmAction(
- `Are you sure you want to delete user "${username}"? This action cannot be undone.`,
- () => deleteUserConfirmed(username)
- );
-}
+ const modalTitle = document.createElement('h5');
+ modalTitle.className = 'modal-title';
+ modalTitle.textContent = title; // Safe - uses textContent
-function deleteUser(username) {
- confirmDeleteUser(username);
-}
+ const closeButton = document.createElement('button');
+ closeButton.type = 'button';
+ closeButton.className = 'btn-close';
+ closeButton.setAttribute('data-bs-dismiss', 'modal');
-async function deleteUserConfirmed(username) {
- try {
- const response = await fetch(`/api/users/${username}`, {
- method: 'DELETE'
- });
+ modalHeader.appendChild(modalTitle);
+ modalHeader.appendChild(closeButton);
- if (response.ok) {
- showSuccessMessage('User deleted successfully');
- setTimeout(() => window.location.reload(), 1000);
- } else {
- const error = await response.json();
- showErrorMessage('Failed to delete user: ' + (error.error || 'Unknown error'));
- }
- } catch (error) {
- console.error('Error deleting user:', error);
- showErrorMessage('Failed to delete user: ' + error.message);
- }
-}
+ // Body (content may contain HTML, so use innerHTML)
+ const modalBody = document.createElement('div');
+ modalBody.className = 'modal-body';
+ modalBody.innerHTML = content;
-async function showUserDetails(username) {
- try {
- const response = await fetch(`/api/users/${username}`);
- if (response.ok) {
- const user = await response.json();
+ // Footer
+ const modalFooter = document.createElement('div');
+ modalFooter.className = 'modal-footer';
- const content = createUserDetailsContent(user);
- document.getElementById('userDetailsContent').innerHTML = content;
+ const closeFooterButton = document.createElement('button');
+ closeFooterButton.type = 'button';
+ closeFooterButton.className = 'btn btn-secondary';
+ closeFooterButton.setAttribute('data-bs-dismiss', 'modal');
+ closeFooterButton.textContent = 'Close';
- const modal = new bootstrap.Modal(document.getElementById('userDetailsModal'));
- modal.show();
- } else {
- showErrorMessage('Failed to load user details');
- }
- } catch (error) {
- console.error('Error loading user details:', error);
- showErrorMessage('Failed to load user details');
- }
-}
+ modalFooter.appendChild(closeFooterButton);
-function createUserDetailsContent(user) {
- return `
- <div class="row">
- <div class="col-md-6">
- <h6 class="text-muted">Basic Information</h6>
- <table class="table table-sm">
- <tr>
- <td><strong>Username:</strong></td>
- <td>${escapeHtml(user.username)}</td>
- </tr>
- <tr>
- <td><strong>Email:</strong></td>
- <td>${escapeHtml(user.email || 'Not set')}</td>
- </tr>
- </table>
- </div>
- <div class="col-md-6">
- <h6 class="text-muted">Permissions</h6>
- <div class="mb-3">
- ${user.actions && user.actions.length > 0 ?
- user.actions.map(action => `<span class="badge bg-info me-1">${action}</span>`).join('') :
- '<span class="text-muted">No permissions assigned</span>'
- }
- </div>
-
- <h6 class="text-muted">Access Keys</h6>
- ${user.access_keys && user.access_keys.length > 0 ?
- createAccessKeysTable(user.access_keys) :
- '<p class="text-muted">No access keys</p>'
- }
- </div>
- </div>
- `;
-}
+ // Assemble modal
+ modalContent.appendChild(modalHeader);
+ modalContent.appendChild(modalBody);
+ modalContent.appendChild(modalFooter);
+ modalDialog.appendChild(modalContent);
+ modalDiv.appendChild(modalDialog);
-function createAccessKeysTable(accessKeys) {
- return `
- <div class="table-responsive">
- <table class="table table-sm">
- <thead>
- <tr>
- <th>Access Key</th>
- <th>Created</th>
- </tr>
- </thead>
- <tbody>
- ${accessKeys.map(key => `
- <tr>
- <td><code>${key.access_key}</code></td>
- <td>${new Date(key.created_at).toLocaleDateString()}</td>
- </tr>
- `).join('')}
- </tbody>
- </table>
- </div>
- `;
-}
-
-async function manageAccessKeys(username) {
- currentAccessKeysUser = username;
- document.getElementById('accessKeysUsername').textContent = username;
-
- await loadAccessKeys(username);
+ // Add modal to body
+ document.body.appendChild(modalDiv);
- const modal = new bootstrap.Modal(document.getElementById('accessKeysModal'));
+ // Show modal
+ const modal = new bootstrap.Modal(document.getElementById(modalId));
modal.show();
-}
-
-async function loadAccessKeys(username) {
- try {
- const response = await fetch(`/api/users/${username}`);
- if (response.ok) {
- const user = await response.json();
-
- const content = createAccessKeysManagementContent(user.access_keys || []);
- document.getElementById('accessKeysContent').innerHTML = content;
- } else {
- document.getElementById('accessKeysContent').innerHTML = '<p class="text-muted">Failed to load access keys</p>';
- }
- } catch (error) {
- console.error('Error loading access keys:', error);
- document.getElementById('accessKeysContent').innerHTML = '<p class="text-muted">Error loading access keys</p>';
- }
-}
-
-function createAccessKeysManagementContent(accessKeys) {
- if (accessKeys.length === 0) {
- return '<p class="text-muted">No access keys found. Create one to get started.</p>';
- }
-
- return `
- <div class="table-responsive">
- <table class="table table-hover">
- <thead>
- <tr>
- <th>Access Key</th>
- <th>Secret Key</th>
- <th>Created</th>
- <th>Actions</th>
- </tr>
- </thead>
- <tbody>
- ${accessKeys.map(key => `
- <tr>
- <td>
- <code>${key.access_key}</code>
- <button class="btn btn-sm btn-outline-secondary ms-2" onclick="adminCopyToClipboard('${key.access_key}')">
- <i class="fas fa-copy"></i>
- </button>
- </td>
- <td>
- <code class="text-muted">••••••••••••••••</code>
- <button class="btn btn-sm btn-outline-secondary ms-2" onclick="showSecretKey('${key.access_key}', '${key.secret_key}')">
- <i class="fas fa-eye"></i>
- </button>
- </td>
- <td>${new Date(key.created_at).toLocaleDateString()}</td>
- <td>
- <button class="btn btn-sm btn-outline-danger" onclick="confirmDeleteAccessKey('${key.access_key}')">
- <i class="fas fa-trash"></i>
- </button>
- </td>
- </tr>
- `).join('')}
- </tbody>
- </table>
- </div>
- `;
-}
-
-async function createAccessKey() {
- if (!currentAccessKeysUser) {
- showErrorMessage('No user selected');
- return;
- }
-
- try {
- const response = await fetch(`/api/users/${currentAccessKeysUser}/access-keys`, {
- method: 'POST',
- headers: {
- 'Content-Type': 'application/json',
- }
- });
-
- if (response.ok) {
- const result = await response.json();
- showSuccessMessage('Access key created successfully');
-
- // Show the new access key
- showNewAccessKeyModal(result.access_key);
-
- // Reload access keys
- await loadAccessKeys(currentAccessKeysUser);
- } else {
- const error = await response.json();
- showErrorMessage('Failed to create access key: ' + (error.error || 'Unknown error'));
- }
- } catch (error) {
- console.error('Error creating access key:', error);
- showErrorMessage('Failed to create access key: ' + error.message);
- }
-}
-
-function confirmDeleteAccessKey(accessKeyId) {
- confirmAction(
- `Are you sure you want to delete access key "${accessKeyId}"? This action cannot be undone.`,
- () => deleteAccessKeyConfirmed(accessKeyId)
- );
-}
-
-async function deleteAccessKeyConfirmed(accessKeyId) {
- try {
- const response = await fetch(`/api/users/${currentAccessKeysUser}/access-keys/${accessKeyId}`, {
- method: 'DELETE'
- });
-
- if (response.ok) {
- showSuccessMessage('Access key deleted successfully');
- // Reload access keys
- await loadAccessKeys(currentAccessKeysUser);
- } else {
- const error = await response.json();
- showErrorMessage('Failed to delete access key: ' + (error.error || 'Unknown error'));
- }
- } catch (error) {
- console.error('Error deleting access key:', error);
- showErrorMessage('Failed to delete access key: ' + error.message);
- }
+ // Remove modal from DOM when hidden
+ document.getElementById(modalId).addEventListener('hidden.bs.modal', function () {
+ this.remove();
+ });
}
function showSecretKey(accessKey, secretKey) {
+ const modalId = 'secretKeyModal_' + Date.now();
+ const escapedAccessKey = escapeHtmlForAttribute(accessKey);
+ const escapedSecretKey = escapeHtmlForAttribute(secretKey);
+
const content = `
<div class="alert alert-info">
<i class="fas fa-info-circle me-2"></i>
@@ -2485,8 +2192,8 @@ function showSecretKey(accessKey, secretKey) {
<div class="mb-3">
<label class="form-label"><strong>Access Key:</strong></label>
<div class="input-group">
- <input type="text" class="form-control" value="${accessKey}" readonly>
- <button class="btn btn-outline-secondary" onclick="adminCopyToClipboard('${accessKey}')">
+ <input type="text" id="${modalId}_accessKey" class="form-control" value="${escapedAccessKey}" readonly>
+ <button class="btn btn-outline-secondary" onclick="copyFromInput('${modalId}_accessKey')">
<i class="fas fa-copy"></i>
</button>
</div>
@@ -2494,8 +2201,8 @@ function showSecretKey(accessKey, secretKey) {
<div class="mb-3">
<label class="form-label"><strong>Secret Key:</strong></label>
<div class="input-group">
- <input type="text" class="form-control" value="${secretKey}" readonly>
- <button class="btn btn-outline-secondary" onclick="adminCopyToClipboard('${secretKey}')">
+ <input type="text" id="${modalId}_secretKey" class="form-control" value="${escapedSecretKey}" readonly>
+ <button class="btn btn-outline-secondary" onclick="copyFromInput('${modalId}_secretKey')">
<i class="fas fa-copy"></i>
</button>
</div>
@@ -2506,20 +2213,20 @@ function showSecretKey(accessKey, secretKey) {
}
function showNewAccessKeyModal(accessKeyData) {
+ const modalId = 'newKeyModal_' + Date.now();
+ const escapedAccessKey = escapeHtmlForAttribute(accessKeyData.access_key);
+ const escapedSecretKey = escapeHtmlForAttribute(accessKeyData.secret_key);
+
const content = `
<div class="alert alert-success">
<i class="fas fa-check-circle me-2"></i>
<strong>Success!</strong> Your new access key has been created.
</div>
- <div class="alert alert-info">
- <i class="fas fa-info-circle me-2"></i>
- <strong>Important:</strong> These credentials provide access to your object storage. Keep them secure and don't share them. You can view them again through the user management interface if needed.
- </div>
<div class="mb-3">
<label class="form-label"><strong>Access Key:</strong></label>
<div class="input-group">
- <input type="text" class="form-control" value="${accessKeyData.access_key}" readonly>
- <button class="btn btn-outline-secondary" onclick="adminCopyToClipboard('${accessKeyData.access_key}')">
+ <input type="text" id="${modalId}_accessKey" class="form-control" value="${escapedAccessKey}" readonly>
+ <button class="btn btn-outline-secondary" onclick="copyFromInput('${modalId}_accessKey')">
<i class="fas fa-copy"></i>
</button>
</div>
@@ -2527,8 +2234,8 @@ function showNewAccessKeyModal(accessKeyData) {
<div class="mb-3">
<label class="form-label"><strong>Secret Key:</strong></label>
<div class="input-group">
- <input type="text" class="form-control" value="${accessKeyData.secret_key}" readonly>
- <button class="btn btn-outline-secondary" onclick="adminCopyToClipboard('${accessKeyData.secret_key}')">
+ <input type="text" id="${modalId}_secretKey" class="form-control" value="${escapedSecretKey}" readonly>
+ <button class="btn btn-outline-secondary" onclick="copyFromInput('${modalId}_secretKey')">
<i class="fas fa-copy"></i>
</button>
</div>
@@ -2538,40 +2245,32 @@ function showNewAccessKeyModal(accessKeyData) {
showModal('New Access Key Created', content);
}
-function showModal(title, content) {
- // Create a dynamic modal
- const modalId = 'dynamicModal_' + Date.now();
- const modalHtml = `
- <div class="modal fade" id="${modalId}" tabindex="-1" role="dialog">
- <div class="modal-dialog" role="document">
- <div class="modal-content">
- <div class="modal-header">
- <h5 class="modal-title">${title}</h5>
- <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
- </div>
- <div class="modal-body">
- ${content}
- </div>
- <div class="modal-footer">
- <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
- </div>
- </div>
- </div>
- </div>
- `;
-
- // Add modal to body
- document.body.insertAdjacentHTML('beforeend', modalHtml);
-
- // Show modal
- const modal = new bootstrap.Modal(document.getElementById(modalId));
- modal.show();
+// Helper function to copy from an input field
+function copyFromInput(inputId) {
+ const input = document.getElementById(inputId);
+ if (input) {
+ input.select();
+ input.setSelectionRange(0, 99999); // For mobile devices
- // Remove modal from DOM when hidden
- document.getElementById(modalId).addEventListener('hidden.bs.modal', function () {
- this.remove();
- });
+ try {
+ const successful = document.execCommand('copy');
+ if (successful) {
+ showAlert('success', 'Copied to clipboard!');
+ } else {
+ // Try modern clipboard API as fallback
+ navigator.clipboard.writeText(input.value).then(() => {
+ showAlert('success', 'Copied to clipboard!');
+ }).catch(() => {
+ showAlert('danger', 'Failed to copy');
+ });
+ }
+ } catch (err) {
+ // Try modern clipboard API as fallback
+ navigator.clipboard.writeText(input.value).then(() => {
+ showAlert('success', 'Copied to clipboard!');
+ }).catch(() => {
+ showAlert('danger', 'Failed to copy');
+ });
+ }
+ }
}
-
-
-
diff --git a/weed/admin/view/app/object_store_users.templ b/weed/admin/view/app/object_store_users.templ
index e93f39d758..0f9a2d693d 100644
--- a/weed/admin/view/app/object_store_users.templ
+++ b/weed/admin/view/app/object_store_users.templ
@@ -223,6 +223,30 @@ templ ObjectStoreUsers(data dash.ObjectStoreUsersData) {
</select>
<small class="form-text text-muted">Hold Ctrl/Cmd to select multiple permissions</small>
</div>
+ <div class="mb-3">
+ <label class="form-label">Bucket Scope</label>
+ <small class="form-text text-muted d-block mb-2">Apply selected permissions to specific buckets or all buckets</small>
+
+ <div class="form-check mb-2">
+ <input class="form-check-input" type="radio" name="bucketScope" id="allBuckets" value="all" checked onchange="toggleBucketList()">
+ <label class="form-check-label" for="allBuckets">
+ All Buckets
+ </label>
+ </div>
+ <div class="form-check mb-2">
+ <input class="form-check-input" type="radio" name="bucketScope" id="specificBuckets" value="specific" onchange="toggleBucketList()">
+ <label class="form-check-label" for="specificBuckets">
+ Specific Buckets
+ </label>
+ </div>
+
+ <div id="bucketSelectionList" class="mt-2" style="display: none;">
+ <select multiple class="form-select" id="selectedBuckets" size="5">
+ <!-- Options loaded dynamically -->
+ </select>
+ <small class="form-text text-muted">Hold Ctrl/Cmd to select multiple buckets</small>
+ </div>
+ </div>
<div class="mb-3">
<label for="policies" class="form-label">Attached Policies</label>
<select multiple class="form-control" id="policies" name="policies" size="5">
@@ -282,6 +306,30 @@ templ ObjectStoreUsers(data dash.ObjectStoreUsersData) {
</optgroup>
</select>
</div>
+ <div class="mb-3">
+ <label class="form-label">Bucket Scope</label>
+ <small class="form-text text-muted d-block mb-2">Apply selected permissions to specific buckets or all buckets</small>
+
+ <div class="form-check mb-2">
+ <input class="form-check-input" type="radio" name="editBucketScope" id="editAllBuckets" value="all" checked onchange="toggleBucketList('edit')">
+ <label class="form-check-label" for="editAllBuckets">
+ All Buckets
+ </label>
+ </div>
+ <div class="form-check mb-2">
+ <input class="form-check-input" type="radio" name="editBucketScope" id="editSpecificBuckets" value="specific" onchange="toggleBucketList('edit')">
+ <label class="form-check-label" for="editSpecificBuckets">
+ Specific Buckets
+ </label>
+ </div>
+
+ <div id="editBucketSelectionList" class="mt-2" style="display: none;">
+ <select multiple class="form-select" id="editSelectedBuckets" size="5">
+ <!-- Options loaded dynamically -->
+ </select>
+ <small class="form-text text-muted">Hold Ctrl/Cmd to select multiple buckets</small>
+ </div>
+ </div>
<div class="mb-3">
<label for="editPolicies" class="form-label">Attached Policies</label>
<select multiple class="form-control" id="editPolicies" name="policies" size="5">
@@ -386,8 +434,35 @@ templ ObjectStoreUsers(data dash.ObjectStoreUsersData) {
// Load policies for dropdowns
loadPolicies();
+
+ // Load buckets for bucket permissions
+ loadBuckets();
});
+ // Global variable to store available buckets
+ var availableBuckets = [];
+ var bucketPermissionCounter = 0;
+
+ // Load buckets
+ async function loadBuckets() {
+ try {
+ const response = await fetch('/api/s3/buckets');
+ if (response.ok) {
+ const data = await response.json();
+ availableBuckets = data.buckets || [];
+ console.log('Loaded', availableBuckets.length, 'buckets');
+ // Populate bucket selection dropdowns
+ populateBucketSelections();
+ } else {
+ console.warn('Failed to load buckets');
+ availableBuckets = [];
+ }
+ } catch (error) {
+ console.error('Error loading buckets:', error);
+ availableBuckets = [];
+ }
+ }
+
// Load policies
async function loadPolicies() {
try {
@@ -434,6 +509,170 @@ templ ObjectStoreUsers(data dash.ObjectStoreUsersData) {
}
}
+ // Toggle bucket permission fields when Admin checkbox changes
+ function toggleBucketPermissionFields(mode) {
+ mode = mode || 'create';
+ const adminCheckbox = document.getElementById(mode === 'edit' ? 'editBucketAdmin' : 'bucketAdmin');
+ const permissionFields = document.getElementById(mode === 'edit' ? 'editBucketPermissionFields' : 'bucketPermissionFields');
+
+ if (adminCheckbox && permissionFields) {
+ permissionFields.style.display = adminCheckbox.checked ? 'none' : 'block';
+ }
+ }
+
+ // Toggle bucket list visibility when bucket scope changes
+ function toggleBucketList(mode) {
+ mode = mode || 'create';
+ const specificRadio = document.getElementById(mode === 'edit' ? 'editSpecificBuckets' : 'specificBuckets');
+ const bucketList = document.getElementById(mode === 'edit' ? 'editBucketSelectionList' : 'bucketSelectionList');
+
+ if (specificRadio && bucketList) {
+ bucketList.style.display = specificRadio.checked ? 'block' : 'none';
+ }
+ }
+
+ // Populate bucket selection dropdowns
+ function populateBucketSelections() {
+ const createSelect = document.getElementById('selectedBuckets');
+ const editSelect = document.getElementById('editSelectedBuckets');
+
+ [createSelect, editSelect].forEach(select => {
+ if (select) {
+ select.innerHTML = '';
+ availableBuckets.forEach(bucket => {
+ const option = document.createElement('option');
+ option.value = bucket.name;
+ option.textContent = bucket.name;
+ select.appendChild(option);
+ });
+ }
+ });
+ }
+
+ // Parse bucket permissions from actions array for new UI
+ function parseBucketPermissions(actions) {
+ const result = {
+ isAdmin: false,
+ permissions: [],
+ applyToAll: false,
+ specificBuckets: []
+ };
+
+ // Check if user has Admin permission
+ if (actions.includes('Admin')) {
+ result.isAdmin = true;
+ return result;
+ }
+
+ // Separate bucket-scoped from global actions
+ const bucketActions = [];
+ const globalBucketPerms = [];
+
+ actions.forEach(action => {
+ if (action.includes(':')) {
+ const parts = action.split(':');
+ const perm = parts[0];
+ const bucket = parts.slice(1).join(':').replace(/\/\*$/, '');
+ bucketActions.push({ permission: perm, bucket: bucket });
+ } else {
+ globalBucketPerms.push(action);
+ }
+ });
+
+ // If we have global bucket permissions (no colon), they apply to all buckets
+ if (globalBucketPerms.length > 0) {
+ result.permissions = globalBucketPerms;
+ result.applyToAll = true;
+ } else if (bucketActions.length > 0) {
+ // Get unique permissions and buckets
+ const perms = [...new Set(bucketActions.map(ba => ba.permission))];
+ const buckets = [...new Set(bucketActions.map(ba => ba.bucket))];
+
+ result.permissions = perms;
+ result.applyToAll = false;
+ result.specificBuckets = buckets;
+ }
+
+ return result;
+ }
+
+ // Build bucket permission action strings using original permissions dropdown
+ /**
+ * Builds bucket permission strings based on selected permissions and bucket scope.
+ * @param {string} mode - The operation mode, either 'create' or 'edit'.
+ * @returns {string[]|null} Array of permission strings (e.g., ['Read:bucket1']) or null if validation fails (specific scope selected but no buckets).
+ */
+ function buildBucketPermissions(mode) {
+ mode = mode || 'create';
+ const selectId = mode === 'edit' ? 'editActions' : 'actions';
+ const permSelect = document.getElementById(selectId);
+
+ if (!permSelect) return [];
+
+ // Get selected permissions from the original multi-select
+ const selectedPerms = Array.from(permSelect.selectedOptions).map(opt => opt.value);
+
+ // If Admin is selected, return just Admin (it overrides everything)
+ if (selectedPerms.includes('Admin')) {
+ return ['Admin'];
+ }
+
+ if (selectedPerms.length === 0) {
+ return [];
+ }
+
+ // Check if applying to all buckets or specific ones
+ // Use querySelector to find the checked radio button by name group
+ const scopeName = mode === 'edit' ? 'editBucketScope' : 'bucketScope';
+
+ // Try multiple methods to find the checked radio
+ let checkedRadio = document.querySelector(`input[name="${scopeName}"]:checked`);
+
+ // Fallback: check both radio buttons explicitly
+ if (!checkedRadio) {
+ const allBucketsId = mode === 'edit' ? 'editAllBuckets' : 'allBuckets';
+ const specificBucketsId = mode === 'edit' ? 'editSpecificBuckets' : 'specificBuckets';
+
+ const allBucketsRadio = document.getElementById(allBucketsId);
+ const specificBucketsRadio = document.getElementById(specificBucketsId);
+
+ if (specificBucketsRadio && specificBucketsRadio.checked) {
+ checkedRadio = specificBucketsRadio;
+ } else if (allBucketsRadio && allBucketsRadio.checked) {
+ checkedRadio = allBucketsRadio;
+ }
+ }
+
+ // Default to 'all' if nothing is checked (shouldn't happen) or if 'all' is checked
+ const applyToAll = !checkedRadio || checkedRadio.value === 'all';
+
+ if (applyToAll) {
+ // Return global permissions (no bucket specification)
+ return selectedPerms;
+ } else {
+ // Get selected specific buckets
+ const bucketSelect = document.getElementById(mode === 'edit' ? 'editSelectedBuckets' : 'selectedBuckets');
+ if (!bucketSelect) return null;
+
+ const selectedBuckets = Array.from(bucketSelect.selectedOptions).map(opt => opt.value);
+
+ // Return null to signal validation failure if no buckets selected
+ if (selectedBuckets.length === 0) {
+ return null;
+ }
+
+ // Build bucket-scoped permissions
+ const actions = [];
+ selectedPerms.forEach(perm => {
+ selectedBuckets.forEach(bucket => {
+ actions.push(perm + ':' + bucket);
+ });
+ });
+
+ return actions;
+ }
+ }
+
// Show user details modal
async function showUserDetails(username) {
try {
@@ -477,6 +716,44 @@ templ ObjectStoreUsers(data dash.ObjectStoreUsersData) {
});
}
+ // Populate bucket permissions using original permissions dropdown
+ if (user.actions && user.actions.length > 0) {
+ const bucketPerms = parseBucketPermissions(user.actions);
+
+ // Set permissions in the original multi-select
+ const actionsSelect = document.getElementById('editActions');
+ if (actionsSelect) {
+ Array.from(actionsSelect.options).forEach(option => {
+ if (bucketPerms.isAdmin && option.value === 'Admin') {
+ option.selected = true;
+ } else if (!bucketPerms.isAdmin && bucketPerms.permissions.includes(option.value)) {
+ option.selected = true;
+ }
+ });
+ }
+
+ // Set bucket scope (all or specific)
+ const allBucketsRadio = document.getElementById('editAllBuckets');
+ const specificBucketsRadio = document.getElementById('editSpecificBuckets');
+
+ if (!bucketPerms.isAdmin) {
+ if (bucketPerms.applyToAll) {
+ if (allBucketsRadio) allBucketsRadio.checked = true;
+ } else if (bucketPerms.specificBuckets.length > 0) {
+ if (specificBucketsRadio) specificBucketsRadio.checked = true;
+ toggleBucketList('edit');
+
+ // Select specific buckets
+ const bucketSelect = document.getElementById('editSelectedBuckets');
+ if (bucketSelect) {
+ Array.from(bucketSelect.options).forEach(option => {
+ option.selected = bucketPerms.specificBuckets.includes(option.value);
+ });
+ }
+ }
+ }
+ }
+
// Show modal
const modal = new bootstrap.Modal(document.getElementById('editUserModal'));
modal.show();
@@ -535,10 +812,13 @@ templ ObjectStoreUsers(data dash.ObjectStoreUsersData) {
const form = document.getElementById('createUserForm');
const formData = new FormData(form);
+ // Get permissions with bucket scope applied
+ const allActions = buildBucketPermissions('create');
+
const userData = {
username: formData.get('username'),
email: formData.get('email'),
- actions: Array.from(document.getElementById('actions').selectedOptions).map(option => option.value),
+ actions: allActions,
policy_names: Array.from(document.getElementById('policies').selectedOptions).map(option => option.value),
generate_key: document.getElementById('generateKey').checked
};
@@ -577,6 +857,62 @@ templ ObjectStoreUsers(data dash.ObjectStoreUsersData) {
}
+ // Handle update user form submission
+ async function handleUpdateUser() {
+ const username = document.getElementById('editUsername').value;
+ if (!username) {
+ showErrorMessage('Username is required');
+ return;
+ }
+
+ // Get permissions with bucket scope applied
+ const allActions = buildBucketPermissions('edit');
+
+ // Validate that permissions are not empty
+ if (!allActions || allActions.length === 0) {
+ showErrorMessage('At least one permission must be selected');
+ return;
+ }
+
+ // Check for null (validation failure from buildBucketPermissionsNew)
+ if (allActions === null) {
+ showErrorMessage('Please select at least one bucket when using specific bucket permissions');
+ return;
+ }
+
+ const userData = {
+ email: document.getElementById('editEmail').value,
+ actions: allActions,
+ policy_names: Array.from(document.getElementById('editPolicies').selectedOptions).map(option => option.value)
+ };
+
+ try {
+ const response = await fetch(`/api/users/${username}`, {
+ method: 'PUT',
+ headers: {
+ 'Content-Type': 'application/json',
+ },
+ body: JSON.stringify(userData)
+ });
+
+ if (response.ok) {
+ showSuccessMessage('User updated successfully');
+
+ // Close modal and refresh page
+ const modal = bootstrap.Modal.getInstance(document.getElementById('editUserModal'));
+ modal.hide();
+ setTimeout(() => window.location.reload(), 1000);
+ } else {
+ const error = await response.json();
+ showErrorMessage('Failed to update user: ' + (error.error || 'Unknown error'));
+ }
+ } catch (error) {
+ console.error('Error updating user:', error);
+ showErrorMessage('Failed to update user: ' + error.message);
+ }
+ }
+
+
// Create user details content
function createUserDetailsContent(user) {
var detailsHtml = '<div class="row">';
@@ -639,6 +975,11 @@ templ ObjectStoreUsers(data dash.ObjectStoreUsersData) {
keysHtml += '<td><code>' + escapeHtml(key.access_key) + '</code></td>';
keysHtml += '<td><span class="badge bg-success">Active</span></td>';
keysHtml += '<td>';
+ // Add "View Secret" button with data attributes
+ keysHtml += '<button class="btn btn-outline-secondary btn-sm me-2 view-secret-btn" data-access-key="' + escapeHtml(key.access_key) + '" data-secret-key="' + escapeHtml(key.secret_key) + '">';
+ keysHtml += '<i class="fas fa-eye"></i> View Secret';
+ keysHtml += '</button>';
+ // Delete button
keysHtml += '<button class="btn btn-outline-danger btn-sm delete-access-key-btn" data-username="' + escapeHtml(user.username) + '" data-access-key="' + escapeHtml(key.access_key) + '">';
keysHtml += '<i class="fas fa-trash"></i> Delete';
keysHtml += '</button>';
@@ -649,6 +990,18 @@ templ ObjectStoreUsers(data dash.ObjectStoreUsersData) {
keysHtml += '</tbody>';
keysHtml += '</table>';
keysHtml += '</div>';
+
+ // Add delegated event listener for view secret buttons
+ setTimeout(() => {
+ document.querySelectorAll('.view-secret-btn').forEach(btn => {
+ btn.addEventListener('click', function() {
+ const accessKey = this.getAttribute('data-access-key');
+ const secretKey = this.getAttribute('data-secret-key');
+ showSecretKey(accessKey, secretKey);
+ });
+ });
+ }, 100);
+
return keysHtml;
}
@@ -667,6 +1020,12 @@ templ ObjectStoreUsers(data dash.ObjectStoreUsersData) {
if (response.ok) {
const result = await response.json();
+
+ // Show the new access key details (IMPORTANT: secret key is only shown once!)
+ if (result.access_key) {
+ showNewAccessKeyModal(result.access_key);
+ }
+
showSuccessMessage('Access key created successfully');
// Refresh access keys display
@@ -713,16 +1072,6 @@ templ ObjectStoreUsers(data dash.ObjectStoreUsersData) {
}
}
- // Show new access key modal (when user is created with generated key)
- function showNewAccessKeyModal(user) {
- // Create a simple alert for now - could be enhanced with a dedicated modal
- var message = 'New user created!\n\n';
- message += 'Username: ' + user.username + '\n';
- message += 'Access Key: ' + user.access_key + '\n';
- message += 'Secret Key: ' + user.secret_key + '\n\n';
- message += 'Please save these credentials securely.';
- alert(message);
- }
// Utility functions
function showSuccessMessage(message) {
diff --git a/weed/admin/view/app/object_store_users_templ.go b/weed/admin/view/app/object_store_users_templ.go
index c60ae84fe0..1090e41e66 100644
--- a/weed/admin/view/app/object_store_users_templ.go
+++ b/weed/admin/view/app/object_store_users_templ.go
@@ -193,7 +193,7 @@ func ObjectStoreUsers(data dash.ObjectStoreUsersData) templ.Component {
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
- templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 15, "</small></div></div></div><!-- Create User Modal --><div class=\"modal fade\" id=\"createUserModal\" tabindex=\"-1\" role=\"dialog\"><div class=\"modal-dialog\" role=\"document\"><div class=\"modal-content\"><div class=\"modal-header\"><h5 class=\"modal-title\"><i class=\"fas fa-user-plus me-2\"></i>Create New User</h5><button type=\"button\" class=\"btn-close\" data-bs-dismiss=\"modal\"></button></div><div class=\"modal-body\"><form id=\"createUserForm\"><div class=\"mb-3\"><label for=\"username\" class=\"form-label\">Username *</label> <input type=\"text\" class=\"form-control\" id=\"username\" name=\"username\" required></div><div class=\"mb-3\"><label for=\"email\" class=\"form-label\">Email</label> <input type=\"email\" class=\"form-control\" id=\"email\" name=\"email\"></div><div class=\"mb-3\"><label for=\"actions\" class=\"form-label\">Permissions</label> <select multiple class=\"form-control\" id=\"actions\" name=\"actions\" size=\"10\"><option value=\"Admin\">Admin (Full Access)</option> <option value=\"Read\">Read</option> <option value=\"Write\">Write</option> <option value=\"List\">List</option> <option value=\"Tagging\">Tagging</option> <optgroup label=\"Object Lock Permissions\"><option value=\"BypassGovernanceRetention\">Bypass Governance Retention</option> <option value=\"GetObjectRetention\">Get Object Retention</option> <option value=\"PutObjectRetention\">Put Object Retention</option> <option value=\"GetObjectLegalHold\">Get Object Legal Hold</option> <option value=\"PutObjectLegalHold\">Put Object Legal Hold</option> <option value=\"GetBucketObjectLockConfiguration\">Get Bucket Object Lock Configuration</option> <option value=\"PutBucketObjectLockConfiguration\">Put Bucket Object Lock Configuration</option></optgroup></select> <small class=\"form-text text-muted\">Hold Ctrl/Cmd to select multiple permissions</small></div><div class=\"mb-3\"><label for=\"policies\" class=\"form-label\">Attached Policies</label> <select multiple class=\"form-control\" id=\"policies\" name=\"policies\" size=\"5\"><!-- Options loaded dynamically --></select> <small class=\"form-text text-muted\">Hold Ctrl/Cmd to select multiple policies</small></div><div class=\"mb-3 form-check\"><input type=\"checkbox\" class=\"form-check-input\" id=\"generateKey\" name=\"generateKey\" checked> <label class=\"form-check-label\" for=\"generateKey\">Generate access key automatically</label></div></form></div><div class=\"modal-footer\"><button type=\"button\" class=\"btn btn-secondary\" data-bs-dismiss=\"modal\">Cancel</button> <button type=\"button\" class=\"btn btn-primary\" onclick=\"handleCreateUser()\">Create User</button></div></div></div></div><!-- Edit User Modal --><div class=\"modal fade\" id=\"editUserModal\" tabindex=\"-1\" role=\"dialog\"><div class=\"modal-dialog\" role=\"document\"><div class=\"modal-content\"><div class=\"modal-header\"><h5 class=\"modal-title\"><i class=\"fas fa-user-edit me-2\"></i>Edit User</h5><button type=\"button\" class=\"btn-close\" data-bs-dismiss=\"modal\"></button></div><div class=\"modal-body\"><form id=\"editUserForm\"><input type=\"hidden\" id=\"editUsername\" name=\"username\"><div class=\"mb-3\"><label for=\"editEmail\" class=\"form-label\">Email</label> <input type=\"email\" class=\"form-control\" id=\"editEmail\" name=\"email\"></div><div class=\"mb-3\"><label for=\"editActions\" class=\"form-label\">Permissions</label> <select multiple class=\"form-control\" id=\"editActions\" name=\"actions\" size=\"10\"><option value=\"Admin\">Admin (Full Access)</option> <option value=\"Read\">Read</option> <option value=\"Write\">Write</option> <option value=\"List\">List</option> <option value=\"Tagging\">Tagging</option> <optgroup label=\"Object Lock Permissions\"><option value=\"BypassGovernanceRetention\">Bypass Governance Retention</option> <option value=\"GetObjectRetention\">Get Object Retention</option> <option value=\"PutObjectRetention\">Put Object Retention</option> <option value=\"GetObjectLegalHold\">Get Object Legal Hold</option> <option value=\"PutObjectLegalHold\">Put Object Legal Hold</option> <option value=\"GetBucketObjectLockConfiguration\">Get Bucket Object Lock Configuration</option> <option value=\"PutBucketObjectLockConfiguration\">Put Bucket Object Lock Configuration</option></optgroup></select></div><div class=\"mb-3\"><label for=\"editPolicies\" class=\"form-label\">Attached Policies</label> <select multiple class=\"form-control\" id=\"editPolicies\" name=\"policies\" size=\"5\"><!-- Options loaded dynamically --></select></div></form></div><div class=\"modal-footer\"><button type=\"button\" class=\"btn btn-secondary\" data-bs-dismiss=\"modal\">Cancel</button> <button type=\"button\" class=\"btn btn-primary\" onclick=\"handleUpdateUser()\">Update User</button></div></div></div></div><!-- User Details Modal --><div class=\"modal fade\" id=\"userDetailsModal\" tabindex=\"-1\" role=\"dialog\"><div class=\"modal-dialog modal-lg\" role=\"document\"><div class=\"modal-content\"><div class=\"modal-header\"><h5 class=\"modal-title\"><i class=\"fas fa-user me-2\"></i>User Details</h5><button type=\"button\" class=\"btn-close\" data-bs-dismiss=\"modal\"></button></div><div class=\"modal-body\" id=\"userDetailsContent\"><!-- Content will be loaded dynamically --></div><div class=\"modal-footer\"><button type=\"button\" class=\"btn btn-secondary\" data-bs-dismiss=\"modal\">Close</button></div></div></div></div><!-- Access Keys Management Modal --><div class=\"modal fade\" id=\"accessKeysModal\" tabindex=\"-1\" role=\"dialog\"><div class=\"modal-dialog modal-lg\" role=\"document\"><div class=\"modal-content\"><div class=\"modal-header\"><h5 class=\"modal-title\"><i class=\"fas fa-key me-2\"></i>Manage Access Keys</h5><button type=\"button\" class=\"btn-close\" data-bs-dismiss=\"modal\"></button></div><div class=\"modal-body\"><div class=\"d-flex justify-content-between align-items-center mb-3\"><h6>Access Keys for <span id=\"accessKeysUsername\"></span></h6><button type=\"button\" class=\"btn btn-primary btn-sm\" onclick=\"createAccessKey()\"><i class=\"fas fa-plus me-1\"></i>Create New Key</button></div><div id=\"accessKeysContent\"><!-- Content will be loaded dynamically --></div></div><div class=\"modal-footer\"><button type=\"button\" class=\"btn btn-secondary\" data-bs-dismiss=\"modal\">Close</button></div></div></div></div><!-- JavaScript for user management --><script>\n document.addEventListener('DOMContentLoaded', function() {\n \n // Event delegation for user action buttons\n document.addEventListener('click', function(e) {\n const button = e.target.closest('[data-action]');\n if (!button) return;\n \n const action = button.getAttribute('data-action');\n const username = button.getAttribute('data-username');\n \n switch (action) {\n case 'show-user-details':\n showUserDetails(username);\n break;\n case 'edit-user':\n editUser(username);\n break;\n case 'manage-access-keys':\n manageAccessKeys(username);\n break;\n case 'delete-user':\n deleteUser(username);\n break;\n }\n });\n\n // Event delegation for delete access key buttons\n document.addEventListener('click', function(e) {\n const deleteBtn = e.target.closest('.delete-access-key-btn');\n if (deleteBtn) {\n const username = deleteBtn.getAttribute('data-username');\n const accessKey = deleteBtn.getAttribute('data-access-key');\n deleteAccessKey(username, accessKey);\n }\n });\n\n // Load policies for dropdowns\n loadPolicies();\n });\n\n // Load policies\n async function loadPolicies() {\n try {\n const response = await fetch('/api/object-store/policies');\n if (response.ok) {\n const data = await response.json();\n const policies = data.policies || [];\n \n const createSelect = document.getElementById('policies');\n const editSelect = document.getElementById('editPolicies');\n \n // Check if elements exist\n if (!createSelect || !editSelect) {\n console.warn('Policy select elements not found');\n return;\n }\n \n // Clear existing options\n createSelect.innerHTML = '';\n editSelect.innerHTML = '';\n \n if (policies && policies.length > 0) {\n policies.forEach(policy => {\n const option = document.createElement('option');\n option.value = policy.name;\n option.textContent = policy.name;\n createSelect.appendChild(option);\n editSelect.appendChild(option.cloneNode(true));\n });\n } else {\n const emptyOption = document.createElement('option');\n emptyOption.disabled = true;\n emptyOption.textContent = 'No policies available';\n createSelect.appendChild(emptyOption);\n editSelect.appendChild(emptyOption.cloneNode(true));\n }\n } else {\n const error = await response.json().catch(() => ({}));\n showErrorMessage('Failed to load policies: ' + (error.error || 'Unknown error'));\n }\n } catch (error) {\n console.error('Error loading policies:', error);\n showErrorMessage('Failed to load policies: ' + error.message);\n }\n }\n\n // Show user details modal\n async function showUserDetails(username) {\n try {\n const response = await fetch(`/api/users/${username}`);\n if (response.ok) {\n const user = await response.json();\n document.getElementById('userDetailsContent').innerHTML = createUserDetailsContent(user);\n const modal = new bootstrap.Modal(document.getElementById('userDetailsModal'));\n modal.show();\n } else {\n showErrorMessage('Failed to load user details');\n }\n } catch (error) {\n console.error('Error loading user details:', error);\n showErrorMessage('Failed to load user details');\n }\n }\n\n // Edit user function\n async function editUser(username) {\n try {\n const response = await fetch(`/api/users/${username}`);\n if (response.ok) {\n const user = await response.json();\n \n // Populate edit form\n document.getElementById('editUsername').value = username;\n document.getElementById('editEmail').value = user.email || '';\n \n // Set selected actions\n const actionsSelect = document.getElementById('editActions');\n Array.from(actionsSelect.options).forEach(option => {\n option.selected = user.actions && user.actions.includes(option.value);\n });\n\n // Set selected policies\n const policiesSelect = document.getElementById('editPolicies');\n if (policiesSelect) {\n Array.from(policiesSelect.options).forEach(option => {\n option.selected = user.policy_names && user.policy_names.includes(option.value);\n });\n }\n \n // Show modal\n const modal = new bootstrap.Modal(document.getElementById('editUserModal'));\n modal.show();\n } else {\n showErrorMessage('Failed to load user details');\n }\n } catch (error) {\n console.error('Error loading user:', error);\n showErrorMessage('Failed to load user details');\n }\n }\n\n // Manage access keys function\n async function manageAccessKeys(username) {\n try {\n const response = await fetch(`/api/users/${username}`);\n if (response.ok) {\n const user = await response.json();\n document.getElementById('accessKeysUsername').textContent = username;\n document.getElementById('accessKeysContent').innerHTML = createAccessKeysContent(user);\n const modal = new bootstrap.Modal(document.getElementById('accessKeysModal'));\n modal.show();\n } else {\n showErrorMessage('Failed to load access keys');\n }\n } catch (error) {\n console.error('Error loading access keys:', error);\n showErrorMessage('Failed to load access keys');\n }\n }\n\n // Delete user function\n async function deleteUser(username) {\n if (confirm(`Are you sure you want to delete user \"${username}\"? This action cannot be undone.`)) {\n try {\n const response = await fetch(`/api/users/${username}`, {\n method: 'DELETE'\n });\n \n if (response.ok) {\n showSuccessMessage('User deleted successfully');\n setTimeout(() => window.location.reload(), 1000);\n } else {\n const error = await response.json();\n showErrorMessage('Failed to delete user: ' + (error.error || 'Unknown error'));\n }\n } catch (error) {\n console.error('Error deleting user:', error);\n showErrorMessage('Failed to delete user: ' + error.message);\n }\n }\n }\n\n // Handle create user form submission\n async function handleCreateUser() {\n const form = document.getElementById('createUserForm');\n const formData = new FormData(form);\n \n const userData = {\n username: formData.get('username'),\n email: formData.get('email'),\n actions: Array.from(document.getElementById('actions').selectedOptions).map(option => option.value),\n policy_names: Array.from(document.getElementById('policies').selectedOptions).map(option => option.value),\n generate_key: document.getElementById('generateKey').checked\n };\n \n try {\n const response = await fetch('/api/users', {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify(userData)\n });\n \n if (response.ok) {\n const result = await response.json();\n showSuccessMessage('User created successfully');\n \n // Show the created access key if generated\n if (result.user && result.user.access_key) {\n showNewAccessKeyModal(result.user);\n }\n \n // Close modal and refresh page\n const modal = bootstrap.Modal.getInstance(document.getElementById('createUserModal'));\n modal.hide();\n form.reset();\n setTimeout(() => window.location.reload(), 1000);\n } else {\n const error = await response.json();\n showErrorMessage('Failed to create user: ' + (error.error || 'Unknown error'));\n }\n } catch (error) {\n console.error('Error creating user:', error);\n showErrorMessage('Failed to create user: ' + error.message);\n }\n }\n\n\n // Create user details content\n function createUserDetailsContent(user) {\n var detailsHtml = '<div class=\"row\">';\n detailsHtml += '<div class=\"col-md-6\">';\n detailsHtml += '<h6 class=\"text-muted\">Basic Information</h6>';\n detailsHtml += '<table class=\"table table-sm\">';\n detailsHtml += '<tr><td><strong>Username:</strong></td><td>' + escapeHtml(user.username) + '</td></tr>';\n detailsHtml += '<tr><td><strong>Email:</strong></td><td>' + escapeHtml(user.email || 'Not set') + '</td></tr>';\n detailsHtml += '</table>';\n detailsHtml += '</div>';\n detailsHtml += '<div class=\"col-md-6\">';\n detailsHtml += '<h6 class=\"text-muted\">Permissions</h6>';\n detailsHtml += '<div class=\"mb-3\">';\n if (user.actions && user.actions.length > 0) {\n detailsHtml += user.actions.map(function(action) {\n return '<span class=\"badge bg-info me-1\">' + escapeHtml(action) + '</span>';\n }).join('');\n } else {\n detailsHtml += '<span class=\"text-muted\">No permissions assigned</span>';\n }\n detailsHtml += '</div>';\n detailsHtml += '<h6 class=\"text-muted\">Attached Policy Names</h6>';\n detailsHtml += '<div class=\"mb-3\">';\n if (user.policy_names && user.policy_names.length > 0) {\n detailsHtml += user.policy_names.map(function(policy) {\n return '<span class=\"badge bg-secondary me-1\">' + escapeHtml(policy) + '</span>';\n }).join('');\n } else {\n detailsHtml += '<span class=\"text-muted\">No policies attached</span>';\n }\n detailsHtml += '</div>';\n detailsHtml += '<h6 class=\"text-muted\">Access Keys</h6>';\n if (user.access_keys && user.access_keys.length > 0) {\n detailsHtml += '<div class=\"mb-2\">';\n user.access_keys.forEach(function(key) {\n detailsHtml += '<div><code class=\"text-muted\">' + escapeHtml(key.access_key) + '</code></div>';\n });\n detailsHtml += '</div>';\n } else {\n detailsHtml += '<p class=\"text-muted\">No access keys</p>';\n }\n detailsHtml += '</div>';\n detailsHtml += '</div>';\n return detailsHtml;\n }\n\n // Create access keys content\n function createAccessKeysContent(user) {\n if (!user.access_keys || user.access_keys.length === 0) {\n return '<p class=\"text-muted\">No access keys available</p>';\n }\n \n var keysHtml = '<div class=\"table-responsive\">';\n keysHtml += '<table class=\"table table-sm\">';\n keysHtml += '<thead><tr><th>Access Key</th><th>Status</th><th>Actions</th></tr></thead>';\n keysHtml += '<tbody>';\n \n user.access_keys.forEach(function(key) {\n keysHtml += '<tr>';\n keysHtml += '<td><code>' + escapeHtml(key.access_key) + '</code></td>';\n keysHtml += '<td><span class=\"badge bg-success\">Active</span></td>';\n keysHtml += '<td>';\n keysHtml += '<button class=\"btn btn-outline-danger btn-sm delete-access-key-btn\" data-username=\"' + escapeHtml(user.username) + '\" data-access-key=\"' + escapeHtml(key.access_key) + '\">';\n keysHtml += '<i class=\"fas fa-trash\"></i> Delete';\n keysHtml += '</button>';\n keysHtml += '</td>';\n keysHtml += '</tr>';\n });\n \n keysHtml += '</tbody>';\n keysHtml += '</table>';\n keysHtml += '</div>';\n return keysHtml;\n }\n\n // Create new access key\n async function createAccessKey() {\n const username = document.getElementById('accessKeysUsername').textContent;\n \n try {\n const response = await fetch(`/api/users/${username}/access-keys`, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify({})\n });\n \n if (response.ok) {\n const result = await response.json();\n showSuccessMessage('Access key created successfully');\n \n // Refresh access keys display\n const userResponse = await fetch(`/api/users/${username}`);\n if (userResponse.ok) {\n const user = await userResponse.json();\n document.getElementById('accessKeysContent').innerHTML = createAccessKeysContent(user);\n }\n } else {\n const error = await response.json();\n showErrorMessage('Failed to create access key: ' + (error.error || 'Unknown error'));\n }\n } catch (error) {\n console.error('Error creating access key:', error);\n showErrorMessage('Failed to create access key: ' + error.message);\n }\n }\n\n // Delete access key\n async function deleteAccessKey(username, accessKey) {\n if (confirm('Are you sure you want to delete this access key?')) {\n try {\n const response = await fetch(`/api/users/${username}/access-keys/${accessKey}`, {\n method: 'DELETE'\n });\n \n if (response.ok) {\n showSuccessMessage('Access key deleted successfully');\n \n // Refresh access keys display\n const userResponse = await fetch(`/api/users/${username}`);\n if (userResponse.ok) {\n const user = await userResponse.json();\n document.getElementById('accessKeysContent').innerHTML = createAccessKeysContent(user);\n }\n } else {\n const error = await response.json();\n showErrorMessage('Failed to delete access key: ' + (error.error || 'Unknown error'));\n }\n } catch (error) {\n console.error('Error deleting access key:', error);\n showErrorMessage('Failed to delete access key: ' + error.message);\n }\n }\n }\n\n // Show new access key modal (when user is created with generated key)\n function showNewAccessKeyModal(user) {\n // Create a simple alert for now - could be enhanced with a dedicated modal\n var message = 'New user created!\\n\\n';\n message += 'Username: ' + user.username + '\\n';\n message += 'Access Key: ' + user.access_key + '\\n';\n message += 'Secret Key: ' + user.secret_key + '\\n\\n';\n message += 'Please save these credentials securely.';\n alert(message);\n }\n\n // Utility functions\n function showSuccessMessage(message) {\n // Simple implementation - could be enhanced with toast notifications\n alert('Success: ' + message);\n }\n\n function showErrorMessage(message) {\n // Simple implementation - could be enhanced with toast notifications\n alert('Error: ' + message);\n }\n\n function escapeHtml(text) {\n if (!text) return '';\n const div = document.createElement('div');\n div.textContent = text;\n return div.innerHTML;\n }\n </script>")
+ templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 15, "</small></div></div></div><!-- Create User Modal --><div class=\"modal fade\" id=\"createUserModal\" tabindex=\"-1\" role=\"dialog\"><div class=\"modal-dialog\" role=\"document\"><div class=\"modal-content\"><div class=\"modal-header\"><h5 class=\"modal-title\"><i class=\"fas fa-user-plus me-2\"></i>Create New User</h5><button type=\"button\" class=\"btn-close\" data-bs-dismiss=\"modal\"></button></div><div class=\"modal-body\"><form id=\"createUserForm\"><div class=\"mb-3\"><label for=\"username\" class=\"form-label\">Username *</label> <input type=\"text\" class=\"form-control\" id=\"username\" name=\"username\" required></div><div class=\"mb-3\"><label for=\"email\" class=\"form-label\">Email</label> <input type=\"email\" class=\"form-control\" id=\"email\" name=\"email\"></div><div class=\"mb-3\"><label for=\"actions\" class=\"form-label\">Permissions</label> <select multiple class=\"form-control\" id=\"actions\" name=\"actions\" size=\"10\"><option value=\"Admin\">Admin (Full Access)</option> <option value=\"Read\">Read</option> <option value=\"Write\">Write</option> <option value=\"List\">List</option> <option value=\"Tagging\">Tagging</option> <optgroup label=\"Object Lock Permissions\"><option value=\"BypassGovernanceRetention\">Bypass Governance Retention</option> <option value=\"GetObjectRetention\">Get Object Retention</option> <option value=\"PutObjectRetention\">Put Object Retention</option> <option value=\"GetObjectLegalHold\">Get Object Legal Hold</option> <option value=\"PutObjectLegalHold\">Put Object Legal Hold</option> <option value=\"GetBucketObjectLockConfiguration\">Get Bucket Object Lock Configuration</option> <option value=\"PutBucketObjectLockConfiguration\">Put Bucket Object Lock Configuration</option></optgroup></select> <small class=\"form-text text-muted\">Hold Ctrl/Cmd to select multiple permissions</small></div><div class=\"mb-3\"><label class=\"form-label\">Bucket Scope</label> <small class=\"form-text text-muted d-block mb-2\">Apply selected permissions to specific buckets or all buckets</small><div class=\"form-check mb-2\"><input class=\"form-check-input\" type=\"radio\" name=\"bucketScope\" id=\"allBuckets\" value=\"all\" checked onchange=\"toggleBucketList()\"> <label class=\"form-check-label\" for=\"allBuckets\">All Buckets</label></div><div class=\"form-check mb-2\"><input class=\"form-check-input\" type=\"radio\" name=\"bucketScope\" id=\"specificBuckets\" value=\"specific\" onchange=\"toggleBucketList()\"> <label class=\"form-check-label\" for=\"specificBuckets\">Specific Buckets</label></div><div id=\"bucketSelectionList\" class=\"mt-2\" style=\"display: none;\"><select multiple class=\"form-select\" id=\"selectedBuckets\" size=\"5\"><!-- Options loaded dynamically --></select> <small class=\"form-text text-muted\">Hold Ctrl/Cmd to select multiple buckets</small></div></div><div class=\"mb-3\"><label for=\"policies\" class=\"form-label\">Attached Policies</label> <select multiple class=\"form-control\" id=\"policies\" name=\"policies\" size=\"5\"><!-- Options loaded dynamically --></select> <small class=\"form-text text-muted\">Hold Ctrl/Cmd to select multiple policies</small></div><div class=\"mb-3 form-check\"><input type=\"checkbox\" class=\"form-check-input\" id=\"generateKey\" name=\"generateKey\" checked> <label class=\"form-check-label\" for=\"generateKey\">Generate access key automatically</label></div></form></div><div class=\"modal-footer\"><button type=\"button\" class=\"btn btn-secondary\" data-bs-dismiss=\"modal\">Cancel</button> <button type=\"button\" class=\"btn btn-primary\" onclick=\"handleCreateUser()\">Create User</button></div></div></div></div><!-- Edit User Modal --><div class=\"modal fade\" id=\"editUserModal\" tabindex=\"-1\" role=\"dialog\"><div class=\"modal-dialog\" role=\"document\"><div class=\"modal-content\"><div class=\"modal-header\"><h5 class=\"modal-title\"><i class=\"fas fa-user-edit me-2\"></i>Edit User</h5><button type=\"button\" class=\"btn-close\" data-bs-dismiss=\"modal\"></button></div><div class=\"modal-body\"><form id=\"editUserForm\"><input type=\"hidden\" id=\"editUsername\" name=\"username\"><div class=\"mb-3\"><label for=\"editEmail\" class=\"form-label\">Email</label> <input type=\"email\" class=\"form-control\" id=\"editEmail\" name=\"email\"></div><div class=\"mb-3\"><label for=\"editActions\" class=\"form-label\">Permissions</label> <select multiple class=\"form-control\" id=\"editActions\" name=\"actions\" size=\"10\"><option value=\"Admin\">Admin (Full Access)</option> <option value=\"Read\">Read</option> <option value=\"Write\">Write</option> <option value=\"List\">List</option> <option value=\"Tagging\">Tagging</option> <optgroup label=\"Object Lock Permissions\"><option value=\"BypassGovernanceRetention\">Bypass Governance Retention</option> <option value=\"GetObjectRetention\">Get Object Retention</option> <option value=\"PutObjectRetention\">Put Object Retention</option> <option value=\"GetObjectLegalHold\">Get Object Legal Hold</option> <option value=\"PutObjectLegalHold\">Put Object Legal Hold</option> <option value=\"GetBucketObjectLockConfiguration\">Get Bucket Object Lock Configuration</option> <option value=\"PutBucketObjectLockConfiguration\">Put Bucket Object Lock Configuration</option></optgroup></select></div><div class=\"mb-3\"><label class=\"form-label\">Bucket Scope</label> <small class=\"form-text text-muted d-block mb-2\">Apply selected permissions to specific buckets or all buckets</small><div class=\"form-check mb-2\"><input class=\"form-check-input\" type=\"radio\" name=\"editBucketScope\" id=\"editAllBuckets\" value=\"all\" checked onchange=\"toggleBucketList('edit')\"> <label class=\"form-check-label\" for=\"editAllBuckets\">All Buckets</label></div><div class=\"form-check mb-2\"><input class=\"form-check-input\" type=\"radio\" name=\"editBucketScope\" id=\"editSpecificBuckets\" value=\"specific\" onchange=\"toggleBucketList('edit')\"> <label class=\"form-check-label\" for=\"editSpecificBuckets\">Specific Buckets</label></div><div id=\"editBucketSelectionList\" class=\"mt-2\" style=\"display: none;\"><select multiple class=\"form-select\" id=\"editSelectedBuckets\" size=\"5\"><!-- Options loaded dynamically --></select> <small class=\"form-text text-muted\">Hold Ctrl/Cmd to select multiple buckets</small></div></div><div class=\"mb-3\"><label for=\"editPolicies\" class=\"form-label\">Attached Policies</label> <select multiple class=\"form-control\" id=\"editPolicies\" name=\"policies\" size=\"5\"><!-- Options loaded dynamically --></select></div></form></div><div class=\"modal-footer\"><button type=\"button\" class=\"btn btn-secondary\" data-bs-dismiss=\"modal\">Cancel</button> <button type=\"button\" class=\"btn btn-primary\" onclick=\"handleUpdateUser()\">Update User</button></div></div></div></div><!-- User Details Modal --><div class=\"modal fade\" id=\"userDetailsModal\" tabindex=\"-1\" role=\"dialog\"><div class=\"modal-dialog modal-lg\" role=\"document\"><div class=\"modal-content\"><div class=\"modal-header\"><h5 class=\"modal-title\"><i class=\"fas fa-user me-2\"></i>User Details</h5><button type=\"button\" class=\"btn-close\" data-bs-dismiss=\"modal\"></button></div><div class=\"modal-body\" id=\"userDetailsContent\"><!-- Content will be loaded dynamically --></div><div class=\"modal-footer\"><button type=\"button\" class=\"btn btn-secondary\" data-bs-dismiss=\"modal\">Close</button></div></div></div></div><!-- Access Keys Management Modal --><div class=\"modal fade\" id=\"accessKeysModal\" tabindex=\"-1\" role=\"dialog\"><div class=\"modal-dialog modal-lg\" role=\"document\"><div class=\"modal-content\"><div class=\"modal-header\"><h5 class=\"modal-title\"><i class=\"fas fa-key me-2\"></i>Manage Access Keys</h5><button type=\"button\" class=\"btn-close\" data-bs-dismiss=\"modal\"></button></div><div class=\"modal-body\"><div class=\"d-flex justify-content-between align-items-center mb-3\"><h6>Access Keys for <span id=\"accessKeysUsername\"></span></h6><button type=\"button\" class=\"btn btn-primary btn-sm\" onclick=\"createAccessKey()\"><i class=\"fas fa-plus me-1\"></i>Create New Key</button></div><div id=\"accessKeysContent\"><!-- Content will be loaded dynamically --></div></div><div class=\"modal-footer\"><button type=\"button\" class=\"btn btn-secondary\" data-bs-dismiss=\"modal\">Close</button></div></div></div></div><!-- JavaScript for user management --><script>\n document.addEventListener('DOMContentLoaded', function() {\n \n // Event delegation for user action buttons\n document.addEventListener('click', function(e) {\n const button = e.target.closest('[data-action]');\n if (!button) return;\n \n const action = button.getAttribute('data-action');\n const username = button.getAttribute('data-username');\n \n switch (action) {\n case 'show-user-details':\n showUserDetails(username);\n break;\n case 'edit-user':\n editUser(username);\n break;\n case 'manage-access-keys':\n manageAccessKeys(username);\n break;\n case 'delete-user':\n deleteUser(username);\n break;\n }\n });\n\n // Event delegation for delete access key buttons\n document.addEventListener('click', function(e) {\n const deleteBtn = e.target.closest('.delete-access-key-btn');\n if (deleteBtn) {\n const username = deleteBtn.getAttribute('data-username');\n const accessKey = deleteBtn.getAttribute('data-access-key');\n deleteAccessKey(username, accessKey);\n }\n });\n\n // Load policies for dropdowns\n loadPolicies();\n \n // Load buckets for bucket permissions\n loadBuckets();\n });\n\n // Global variable to store available buckets\n var availableBuckets = [];\n var bucketPermissionCounter = 0;\n\n // Load buckets\n async function loadBuckets() {\n try {\n const response = await fetch('/api/s3/buckets');\n if (response.ok) {\n const data = await response.json();\n availableBuckets = data.buckets || [];\n console.log('Loaded', availableBuckets.length, 'buckets');\n // Populate bucket selection dropdowns\n populateBucketSelections();\n } else {\n console.warn('Failed to load buckets');\n availableBuckets = [];\n }\n } catch (error) {\n console.error('Error loading buckets:', error);\n availableBuckets = [];\n }\n }\n\n // Load policies\n async function loadPolicies() {\n try {\n const response = await fetch('/api/object-store/policies');\n if (response.ok) {\n const data = await response.json();\n const policies = data.policies || [];\n \n const createSelect = document.getElementById('policies');\n const editSelect = document.getElementById('editPolicies');\n \n // Check if elements exist\n if (!createSelect || !editSelect) {\n console.warn('Policy select elements not found');\n return;\n }\n \n // Clear existing options\n createSelect.innerHTML = '';\n editSelect.innerHTML = '';\n \n if (policies && policies.length > 0) {\n policies.forEach(policy => {\n const option = document.createElement('option');\n option.value = policy.name;\n option.textContent = policy.name;\n createSelect.appendChild(option);\n editSelect.appendChild(option.cloneNode(true));\n });\n } else {\n const emptyOption = document.createElement('option');\n emptyOption.disabled = true;\n emptyOption.textContent = 'No policies available';\n createSelect.appendChild(emptyOption);\n editSelect.appendChild(emptyOption.cloneNode(true));\n }\n } else {\n const error = await response.json().catch(() => ({}));\n showErrorMessage('Failed to load policies: ' + (error.error || 'Unknown error'));\n }\n } catch (error) {\n console.error('Error loading policies:', error);\n showErrorMessage('Failed to load policies: ' + error.message);\n }\n }\n\n // Toggle bucket permission fields when Admin checkbox changes\n function toggleBucketPermissionFields(mode) {\n mode = mode || 'create';\n const adminCheckbox = document.getElementById(mode === 'edit' ? 'editBucketAdmin' : 'bucketAdmin');\n const permissionFields = document.getElementById(mode === 'edit' ? 'editBucketPermissionFields' : 'bucketPermissionFields');\n \n if (adminCheckbox && permissionFields) {\n permissionFields.style.display = adminCheckbox.checked ? 'none' : 'block';\n }\n }\n\n // Toggle bucket list visibility when bucket scope changes\n function toggleBucketList(mode) {\n mode = mode || 'create';\n const specificRadio = document.getElementById(mode === 'edit' ? 'editSpecificBuckets' : 'specificBuckets');\n const bucketList = document.getElementById(mode === 'edit' ? 'editBucketSelectionList' : 'bucketSelectionList');\n \n if (specificRadio && bucketList) {\n bucketList.style.display = specificRadio.checked ? 'block' : 'none';\n }\n }\n\n // Populate bucket selection dropdowns\n function populateBucketSelections() {\n const createSelect = document.getElementById('selectedBuckets');\n const editSelect = document.getElementById('editSelectedBuckets');\n \n [createSelect, editSelect].forEach(select => {\n if (select) {\n select.innerHTML = '';\n availableBuckets.forEach(bucket => {\n const option = document.createElement('option');\n option.value = bucket.name;\n option.textContent = bucket.name;\n select.appendChild(option);\n });\n }\n });\n }\n\n // Parse bucket permissions from actions array for new UI\n function parseBucketPermissions(actions) {\n const result = {\n isAdmin: false,\n permissions: [],\n applyToAll: false,\n specificBuckets: []\n };\n \n // Check if user has Admin permission\n if (actions.includes('Admin')) {\n result.isAdmin = true;\n return result;\n }\n \n // Separate bucket-scoped from global actions\n const bucketActions = [];\n const globalBucketPerms = [];\n \n actions.forEach(action => {\n if (action.includes(':')) {\n const parts = action.split(':');\n const perm = parts[0];\n const bucket = parts.slice(1).join(':').replace(/\\/\\*$/, '');\n bucketActions.push({ permission: perm, bucket: bucket });\n } else {\n globalBucketPerms.push(action);\n }\n });\n \n // If we have global bucket permissions (no colon), they apply to all buckets\n if (globalBucketPerms.length > 0) {\n result.permissions = globalBucketPerms;\n result.applyToAll = true;\n } else if (bucketActions.length > 0) {\n // Get unique permissions and buckets\n const perms = [...new Set(bucketActions.map(ba => ba.permission))];\n const buckets = [...new Set(bucketActions.map(ba => ba.bucket))];\n \n result.permissions = perms;\n result.applyToAll = false;\n result.specificBuckets = buckets;\n }\n \n return result;\n }\n\n // Build bucket permission action strings using original permissions dropdown\n /**\n * Builds bucket permission strings based on selected permissions and bucket scope.\n * @param {string} mode - The operation mode, either 'create' or 'edit'.\n * @returns {string[]|null} Array of permission strings (e.g., ['Read:bucket1']) or null if validation fails (specific scope selected but no buckets).\n */\n function buildBucketPermissions(mode) {\n mode = mode || 'create';\n const selectId = mode === 'edit' ? 'editActions' : 'actions';\n const permSelect = document.getElementById(selectId);\n \n if (!permSelect) return [];\n \n // Get selected permissions from the original multi-select\n const selectedPerms = Array.from(permSelect.selectedOptions).map(opt => opt.value);\n \n // If Admin is selected, return just Admin (it overrides everything)\n if (selectedPerms.includes('Admin')) {\n return ['Admin'];\n }\n \n if (selectedPerms.length === 0) {\n return [];\n }\n \n // Check if applying to all buckets or specific ones\n // Use querySelector to find the checked radio button by name group\n const scopeName = mode === 'edit' ? 'editBucketScope' : 'bucketScope';\n \n // Try multiple methods to find the checked radio\n let checkedRadio = document.querySelector(`input[name=\"${scopeName}\"]:checked`);\n \n // Fallback: check both radio buttons explicitly\n if (!checkedRadio) {\n const allBucketsId = mode === 'edit' ? 'editAllBuckets' : 'allBuckets';\n const specificBucketsId = mode === 'edit' ? 'editSpecificBuckets' : 'specificBuckets';\n \n const allBucketsRadio = document.getElementById(allBucketsId);\n const specificBucketsRadio = document.getElementById(specificBucketsId);\n \n if (specificBucketsRadio && specificBucketsRadio.checked) {\n checkedRadio = specificBucketsRadio;\n } else if (allBucketsRadio && allBucketsRadio.checked) {\n checkedRadio = allBucketsRadio;\n }\n }\n\n // Default to 'all' if nothing is checked (shouldn't happen) or if 'all' is checked\n const applyToAll = !checkedRadio || checkedRadio.value === 'all';\n\n if (applyToAll) {\n // Return global permissions (no bucket specification)\n return selectedPerms;\n } else {\n // Get selected specific buckets\n const bucketSelect = document.getElementById(mode === 'edit' ? 'editSelectedBuckets' : 'selectedBuckets');\n if (!bucketSelect) return null;\n \n const selectedBuckets = Array.from(bucketSelect.selectedOptions).map(opt => opt.value);\n \n // Return null to signal validation failure if no buckets selected\n if (selectedBuckets.length === 0) {\n return null;\n }\n \n // Build bucket-scoped permissions\n const actions = [];\n selectedPerms.forEach(perm => {\n selectedBuckets.forEach(bucket => {\n actions.push(perm + ':' + bucket);\n });\n });\n \n return actions;\n }\n }\n\n // Show user details modal\n async function showUserDetails(username) {\n try {\n const response = await fetch(`/api/users/${username}`);\n if (response.ok) {\n const user = await response.json();\n document.getElementById('userDetailsContent').innerHTML = createUserDetailsContent(user);\n const modal = new bootstrap.Modal(document.getElementById('userDetailsModal'));\n modal.show();\n } else {\n showErrorMessage('Failed to load user details');\n }\n } catch (error) {\n console.error('Error loading user details:', error);\n showErrorMessage('Failed to load user details');\n }\n }\n\n // Edit user function\n async function editUser(username) {\n try {\n const response = await fetch(`/api/users/${username}`);\n if (response.ok) {\n const user = await response.json();\n \n // Populate edit form\n document.getElementById('editUsername').value = username;\n document.getElementById('editEmail').value = user.email || '';\n \n // Set selected actions\n const actionsSelect = document.getElementById('editActions');\n Array.from(actionsSelect.options).forEach(option => {\n option.selected = user.actions && user.actions.includes(option.value);\n });\n\n // Set selected policies\n const policiesSelect = document.getElementById('editPolicies');\n if (policiesSelect) {\n Array.from(policiesSelect.options).forEach(option => {\n option.selected = user.policy_names && user.policy_names.includes(option.value);\n });\n }\n \n // Populate bucket permissions using original permissions dropdown\n if (user.actions && user.actions.length > 0) {\n const bucketPerms = parseBucketPermissions(user.actions);\n \n // Set permissions in the original multi-select\n const actionsSelect = document.getElementById('editActions');\n if (actionsSelect) {\n Array.from(actionsSelect.options).forEach(option => {\n if (bucketPerms.isAdmin && option.value === 'Admin') {\n option.selected = true;\n } else if (!bucketPerms.isAdmin && bucketPerms.permissions.includes(option.value)) {\n option.selected = true;\n }\n });\n }\n \n // Set bucket scope (all or specific)\n const allBucketsRadio = document.getElementById('editAllBuckets');\n const specificBucketsRadio = document.getElementById('editSpecificBuckets');\n \n if (!bucketPerms.isAdmin) {\n if (bucketPerms.applyToAll) {\n if (allBucketsRadio) allBucketsRadio.checked = true;\n } else if (bucketPerms.specificBuckets.length > 0) {\n if (specificBucketsRadio) specificBucketsRadio.checked = true;\n toggleBucketList('edit');\n \n // Select specific buckets\n const bucketSelect = document.getElementById('editSelectedBuckets');\n if (bucketSelect) {\n Array.from(bucketSelect.options).forEach(option => {\n option.selected = bucketPerms.specificBuckets.includes(option.value);\n });\n }\n }\n }\n }\n \n // Show modal\n const modal = new bootstrap.Modal(document.getElementById('editUserModal'));\n modal.show();\n } else {\n showErrorMessage('Failed to load user details');\n }\n } catch (error) {\n console.error('Error loading user:', error);\n showErrorMessage('Failed to load user details');\n }\n }\n\n // Manage access keys function\n async function manageAccessKeys(username) {\n try {\n const response = await fetch(`/api/users/${username}`);\n if (response.ok) {\n const user = await response.json();\n document.getElementById('accessKeysUsername').textContent = username;\n document.getElementById('accessKeysContent').innerHTML = createAccessKeysContent(user);\n const modal = new bootstrap.Modal(document.getElementById('accessKeysModal'));\n modal.show();\n } else {\n showErrorMessage('Failed to load access keys');\n }\n } catch (error) {\n console.error('Error loading access keys:', error);\n showErrorMessage('Failed to load access keys');\n }\n }\n\n // Delete user function\n async function deleteUser(username) {\n if (confirm(`Are you sure you want to delete user \"${username}\"? This action cannot be undone.`)) {\n try {\n const response = await fetch(`/api/users/${username}`, {\n method: 'DELETE'\n });\n \n if (response.ok) {\n showSuccessMessage('User deleted successfully');\n setTimeout(() => window.location.reload(), 1000);\n } else {\n const error = await response.json();\n showErrorMessage('Failed to delete user: ' + (error.error || 'Unknown error'));\n }\n } catch (error) {\n console.error('Error deleting user:', error);\n showErrorMessage('Failed to delete user: ' + error.message);\n }\n }\n }\n\n // Handle create user form submission\n async function handleCreateUser() {\n const form = document.getElementById('createUserForm');\n const formData = new FormData(form);\n \n // Get permissions with bucket scope applied\n const allActions = buildBucketPermissions('create');\n \n const userData = {\n username: formData.get('username'),\n email: formData.get('email'),\n actions: allActions,\n policy_names: Array.from(document.getElementById('policies').selectedOptions).map(option => option.value),\n generate_key: document.getElementById('generateKey').checked\n };\n \n try {\n const response = await fetch('/api/users', {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify(userData)\n });\n \n if (response.ok) {\n const result = await response.json();\n showSuccessMessage('User created successfully');\n \n // Show the created access key if generated\n if (result.user && result.user.access_key) {\n showNewAccessKeyModal(result.user);\n }\n \n // Close modal and refresh page\n const modal = bootstrap.Modal.getInstance(document.getElementById('createUserModal'));\n modal.hide();\n form.reset();\n setTimeout(() => window.location.reload(), 1000);\n } else {\n const error = await response.json();\n showErrorMessage('Failed to create user: ' + (error.error || 'Unknown error'));\n }\n } catch (error) {\n console.error('Error creating user:', error);\n showErrorMessage('Failed to create user: ' + error.message);\n }\n }\n\n\n // Handle update user form submission\n async function handleUpdateUser() {\n const username = document.getElementById('editUsername').value;\n if (!username) {\n showErrorMessage('Username is required');\n return;\n }\n \n // Get permissions with bucket scope applied\n const allActions = buildBucketPermissions('edit');\n \n // Validate that permissions are not empty\n if (!allActions || allActions.length === 0) {\n showErrorMessage('At least one permission must be selected');\n return;\n }\n \n // Check for null (validation failure from buildBucketPermissionsNew)\n if (allActions === null) {\n showErrorMessage('Please select at least one bucket when using specific bucket permissions');\n return;\n }\n \n const userData = {\n email: document.getElementById('editEmail').value,\n actions: allActions,\n policy_names: Array.from(document.getElementById('editPolicies').selectedOptions).map(option => option.value)\n };\n \n try {\n const response = await fetch(`/api/users/${username}`, {\n method: 'PUT',\n headers: {\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify(userData)\n });\n \n if (response.ok) {\n showSuccessMessage('User updated successfully');\n \n // Close modal and refresh page\n const modal = bootstrap.Modal.getInstance(document.getElementById('editUserModal'));\n modal.hide();\n setTimeout(() => window.location.reload(), 1000);\n } else {\n const error = await response.json();\n showErrorMessage('Failed to update user: ' + (error.error || 'Unknown error'));\n }\n } catch (error) {\n console.error('Error updating user:', error);\n showErrorMessage('Failed to update user: ' + error.message);\n }\n }\n\n\n // Create user details content\n function createUserDetailsContent(user) {\n var detailsHtml = '<div class=\"row\">';\n detailsHtml += '<div class=\"col-md-6\">';\n detailsHtml += '<h6 class=\"text-muted\">Basic Information</h6>';\n detailsHtml += '<table class=\"table table-sm\">';\n detailsHtml += '<tr><td><strong>Username:</strong></td><td>' + escapeHtml(user.username) + '</td></tr>';\n detailsHtml += '<tr><td><strong>Email:</strong></td><td>' + escapeHtml(user.email || 'Not set') + '</td></tr>';\n detailsHtml += '</table>';\n detailsHtml += '</div>';\n detailsHtml += '<div class=\"col-md-6\">';\n detailsHtml += '<h6 class=\"text-muted\">Permissions</h6>';\n detailsHtml += '<div class=\"mb-3\">';\n if (user.actions && user.actions.length > 0) {\n detailsHtml += user.actions.map(function(action) {\n return '<span class=\"badge bg-info me-1\">' + escapeHtml(action) + '</span>';\n }).join('');\n } else {\n detailsHtml += '<span class=\"text-muted\">No permissions assigned</span>';\n }\n detailsHtml += '</div>';\n detailsHtml += '<h6 class=\"text-muted\">Attached Policy Names</h6>';\n detailsHtml += '<div class=\"mb-3\">';\n if (user.policy_names && user.policy_names.length > 0) {\n detailsHtml += user.policy_names.map(function(policy) {\n return '<span class=\"badge bg-secondary me-1\">' + escapeHtml(policy) + '</span>';\n }).join('');\n } else {\n detailsHtml += '<span class=\"text-muted\">No policies attached</span>';\n }\n detailsHtml += '</div>';\n detailsHtml += '<h6 class=\"text-muted\">Access Keys</h6>';\n if (user.access_keys && user.access_keys.length > 0) {\n detailsHtml += '<div class=\"mb-2\">';\n user.access_keys.forEach(function(key) {\n detailsHtml += '<div><code class=\"text-muted\">' + escapeHtml(key.access_key) + '</code></div>';\n });\n detailsHtml += '</div>';\n } else {\n detailsHtml += '<p class=\"text-muted\">No access keys</p>';\n }\n detailsHtml += '</div>';\n detailsHtml += '</div>';\n return detailsHtml;\n }\n\n // Create access keys content\n function createAccessKeysContent(user) {\n if (!user.access_keys || user.access_keys.length === 0) {\n return '<p class=\"text-muted\">No access keys available</p>';\n }\n \n var keysHtml = '<div class=\"table-responsive\">';\n keysHtml += '<table class=\"table table-sm\">';\n keysHtml += '<thead><tr><th>Access Key</th><th>Status</th><th>Actions</th></tr></thead>';\n keysHtml += '<tbody>';\n \n user.access_keys.forEach(function(key) {\n keysHtml += '<tr>';\n keysHtml += '<td><code>' + escapeHtml(key.access_key) + '</code></td>';\n keysHtml += '<td><span class=\"badge bg-success\">Active</span></td>';\n keysHtml += '<td>';\n // Add \"View Secret\" button with data attributes\n keysHtml += '<button class=\"btn btn-outline-secondary btn-sm me-2 view-secret-btn\" data-access-key=\"' + escapeHtml(key.access_key) + '\" data-secret-key=\"' + escapeHtml(key.secret_key) + '\">';\n keysHtml += '<i class=\"fas fa-eye\"></i> View Secret';\n keysHtml += '</button>';\n // Delete button\n keysHtml += '<button class=\"btn btn-outline-danger btn-sm delete-access-key-btn\" data-username=\"' + escapeHtml(user.username) + '\" data-access-key=\"' + escapeHtml(key.access_key) + '\">';\n keysHtml += '<i class=\"fas fa-trash\"></i> Delete';\n keysHtml += '</button>';\n keysHtml += '</td>';\n keysHtml += '</tr>';\n });\n \n keysHtml += '</tbody>';\n keysHtml += '</table>';\n keysHtml += '</div>';\n \n // Add delegated event listener for view secret buttons\n setTimeout(() => {\n document.querySelectorAll('.view-secret-btn').forEach(btn => {\n btn.addEventListener('click', function() {\n const accessKey = this.getAttribute('data-access-key');\n const secretKey = this.getAttribute('data-secret-key');\n showSecretKey(accessKey, secretKey);\n });\n });\n }, 100);\n \n return keysHtml;\n }\n\n // Create new access key\n async function createAccessKey() {\n const username = document.getElementById('accessKeysUsername').textContent;\n \n try {\n const response = await fetch(`/api/users/${username}/access-keys`, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify({})\n });\n \n if (response.ok) {\n const result = await response.json();\n \n // Show the new access key details (IMPORTANT: secret key is only shown once!)\n if (result.access_key) {\n showNewAccessKeyModal(result.access_key);\n }\n \n showSuccessMessage('Access key created successfully');\n \n // Refresh access keys display\n const userResponse = await fetch(`/api/users/${username}`);\n if (userResponse.ok) {\n const user = await userResponse.json();\n document.getElementById('accessKeysContent').innerHTML = createAccessKeysContent(user);\n }\n } else {\n const error = await response.json();\n showErrorMessage('Failed to create access key: ' + (error.error || 'Unknown error'));\n }\n } catch (error) {\n console.error('Error creating access key:', error);\n showErrorMessage('Failed to create access key: ' + error.message);\n }\n }\n\n // Delete access key\n async function deleteAccessKey(username, accessKey) {\n if (confirm('Are you sure you want to delete this access key?')) {\n try {\n const response = await fetch(`/api/users/${username}/access-keys/${accessKey}`, {\n method: 'DELETE'\n });\n \n if (response.ok) {\n showSuccessMessage('Access key deleted successfully');\n \n // Refresh access keys display\n const userResponse = await fetch(`/api/users/${username}`);\n if (userResponse.ok) {\n const user = await userResponse.json();\n document.getElementById('accessKeysContent').innerHTML = createAccessKeysContent(user);\n }\n } else {\n const error = await response.json();\n showErrorMessage('Failed to delete access key: ' + (error.error || 'Unknown error'));\n }\n } catch (error) {\n console.error('Error deleting access key:', error);\n showErrorMessage('Failed to delete access key: ' + error.message);\n }\n }\n }\n\n\n // Utility functions\n function showSuccessMessage(message) {\n // Simple implementation - could be enhanced with toast notifications\n alert('Success: ' + message);\n }\n\n function showErrorMessage(message) {\n // Simple implementation - could be enhanced with toast notifications\n alert('Error: ' + message);\n }\n\n function escapeHtml(text) {\n if (!text) return '';\n const div = document.createElement('div');\n div.textContent = text;\n return div.innerHTML;\n }\n </script>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}