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.
Go blob-storagecloud-drivedistributed-file-systemdistributed-storageerasure-codingfusehadoop-hdfshdfskuberneteslancelancedbobject-storageposixs3s3-storageseaweedfstiered-file-systemvector-search
fix(admin): use basePath for API fetches when urlPrefix is set (#9197)
faspix0fcd5173be40
diff --git a/weed/admin/view/app/groups.templ b/weed/admin/view/app/groups.templindex fe3c1b8d96..1e6cfab84b 100644--- a/weed/admin/view/app/groups.templ+++ b/weed/admin/view/app/groups.templ@@ -231,7 +231,6 @@ templ Groups(data dash.GroupsPageData) {</div></div>- <script src="/static/js/iam-utils.js"></script><script>// Groups page JavaScriptlet currentGroupName = '';@@ -243,7 +242,7 @@ templ Groups(data dash.GroupsPageData) {return;}try {- const response = await fetch('/api/groups', {+ const response = await fetch(basePath('/api/groups'), {method: 'POST',headers: { 'Content-Type': 'application/json' },body: JSON.stringify({ name: name })@@ -269,7 +268,7 @@ templ Groups(data dash.GroupsPageData) {async function refreshGroupDetails(requestedName) {try {- const response = await fetch('/api/groups/' + encodeURIComponent(requestedName));+ const response = await fetch(basePath('/api/groups/' + encodeURIComponent(requestedName)));if (!response.ok) throw new Error('Failed to fetch group');if (requestedName !== currentGroupName) return; // stale responseconst group = await response.json();@@ -339,7 +338,7 @@ templ Groups(data dash.GroupsPageData) {const username = document.getElementById('addMemberSelect').value;if (!username) return;try {- const response = await fetch('/api/groups/' + encodeURIComponent(currentGroupName) + '/members', {+ const response = await fetch(basePath('/api/groups/' + encodeURIComponent(currentGroupName) + '/members'), {method: 'POST',headers: { 'Content-Type': 'application/json' },body: JSON.stringify({ username: username })@@ -358,7 +357,7 @@ templ Groups(data dash.GroupsPageData) {async function removeMember(username) {try {- const response = await fetch('/api/groups/' + encodeURIComponent(currentGroupName) + '/members/' + encodeURIComponent(username), {+ const response = await fetch(basePath('/api/groups/' + encodeURIComponent(currentGroupName) + '/members/' + encodeURIComponent(username)), {method: 'DELETE'});if (response.ok) {@@ -377,7 +376,7 @@ templ Groups(data dash.GroupsPageData) {const policyName = document.getElementById('attachPolicySelect').value;if (!policyName) return;try {- const response = await fetch('/api/groups/' + encodeURIComponent(currentGroupName) + '/policies', {+ const response = await fetch(basePath('/api/groups/' + encodeURIComponent(currentGroupName) + '/policies'), {method: 'POST',headers: { 'Content-Type': 'application/json' },body: JSON.stringify({ policy_name: policyName })@@ -396,7 +395,7 @@ templ Groups(data dash.GroupsPageData) {async function detachPolicy(policyName) {try {- const response = await fetch('/api/groups/' + encodeURIComponent(currentGroupName) + '/policies/' + encodeURIComponent(policyName), {+ const response = await fetch(basePath('/api/groups/' + encodeURIComponent(currentGroupName) + '/policies/' + encodeURIComponent(policyName)), {method: 'DELETE'});if (response.ok) {@@ -414,7 +413,7 @@ templ Groups(data dash.GroupsPageData) {async function toggleGroupStatus() {const enabled = document.getElementById('groupEnabledSwitch').checked;try {- const response = await fetch('/api/groups/' + encodeURIComponent(currentGroupName) + '/status', {+ const response = await fetch(basePath('/api/groups/' + encodeURIComponent(currentGroupName) + '/status'), {method: 'PUT',headers: { 'Content-Type': 'application/json' },body: JSON.stringify({ enabled: enabled })diff --git a/weed/admin/view/app/groups_templ.go b/weed/admin/view/app/groups_templ.goindex 7b7cccccbe..26619a9d11 100644--- a/weed/admin/view/app/groups_templ.go+++ b/weed/admin/view/app/groups_templ.go@@ -1,6 +1,6 @@// Code generated by templ - DO NOT EDIT.-// templ: version: v0.3.977+// templ: version: v0.3.1001package app//lint:file-ignore SA4006 This context is only used if a nested component is present.@@ -41,7 +41,7 @@ func Groups(data dash.GroupsPageData) templ.Component {var templ_7745c5c3_Var2 stringtempl_7745c5c3_Var2, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%d", data.TotalGroups))if templ_7745c5c3_Err != nil {- return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/groups.templ`, Line: 38, Col: 72}+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/groups.templ`, Line: 38, Col: 72}}_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var2))if templ_7745c5c3_Err != nil {@@ -54,7 +54,7 @@ func Groups(data dash.GroupsPageData) templ.Component {var templ_7745c5c3_Var3 stringtempl_7745c5c3_Var3, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%d", data.ActiveGroups))if templ_7745c5c3_Err != nil {- return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/groups.templ`, Line: 57, Col: 73}+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/groups.templ`, Line: 57, Col: 73}}_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var3))if templ_7745c5c3_Err != nil {@@ -82,7 +82,7 @@ func Groups(data dash.GroupsPageData) templ.Component {var templ_7745c5c3_Var4 stringtempl_7745c5c3_Var4, templ_7745c5c3_Err = templ.JoinStringErrs(group.Name)if templ_7745c5c3_Err != nil {- return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/groups.templ`, Line: 96, Col: 63}+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/groups.templ`, Line: 96, Col: 63}}_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var4))if templ_7745c5c3_Err != nil {@@ -95,7 +95,7 @@ func Groups(data dash.GroupsPageData) templ.Component {var templ_7745c5c3_Var5 stringtempl_7745c5c3_Var5, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%d", group.MemberCount))if templ_7745c5c3_Err != nil {- return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/groups.templ`, Line: 99, Col: 109}+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/groups.templ`, Line: 99, Col: 109}}_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var5))if templ_7745c5c3_Err != nil {@@ -108,7 +108,7 @@ func Groups(data dash.GroupsPageData) templ.Component {var templ_7745c5c3_Var6 stringtempl_7745c5c3_Var6, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%d", group.PolicyCount))if templ_7745c5c3_Err != nil {- return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/groups.templ`, Line: 102, Col: 114}+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/groups.templ`, Line: 102, Col: 114}}_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var6))if templ_7745c5c3_Err != nil {@@ -136,7 +136,7 @@ func Groups(data dash.GroupsPageData) templ.Component {var templ_7745c5c3_Var7 stringtempl_7745c5c3_Var7, templ_7745c5c3_Err = templ.JoinStringErrs(group.Name)if templ_7745c5c3_Err != nil {- return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/groups.templ`, Line: 113, Col: 79}+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/groups.templ`, Line: 113, Col: 79}}_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var7))if templ_7745c5c3_Err != nil {@@ -149,7 +149,7 @@ func Groups(data dash.GroupsPageData) templ.Component {var templ_7745c5c3_Var8 stringtempl_7745c5c3_Var8, templ_7745c5c3_Err = templ.JoinStringErrs("View group " + group.Name)if templ_7745c5c3_Err != nil {- return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/groups.templ`, Line: 115, Col: 90}+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/groups.templ`, Line: 115, Col: 90}}_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var8))if templ_7745c5c3_Err != nil {@@ -162,7 +162,7 @@ func Groups(data dash.GroupsPageData) templ.Component {var templ_7745c5c3_Var9 stringtempl_7745c5c3_Var9, templ_7745c5c3_Err = templ.JoinStringErrs("View " + group.Name)if templ_7745c5c3_Err != nil {- return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/groups.templ`, Line: 116, Col: 79}+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/groups.templ`, Line: 116, Col: 79}}_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var9))if templ_7745c5c3_Err != nil {@@ -175,7 +175,7 @@ func Groups(data dash.GroupsPageData) templ.Component {var templ_7745c5c3_Var10 stringtempl_7745c5c3_Var10, templ_7745c5c3_Err = templ.JoinStringErrs(group.Name)if templ_7745c5c3_Err != nil {- return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/groups.templ`, Line: 120, Col: 79}+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/groups.templ`, Line: 120, Col: 79}}_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var10))if templ_7745c5c3_Err != nil {@@ -188,7 +188,7 @@ func Groups(data dash.GroupsPageData) templ.Component {var templ_7745c5c3_Var11 stringtempl_7745c5c3_Var11, templ_7745c5c3_Err = templ.JoinStringErrs("Delete group " + group.Name)if templ_7745c5c3_Err != nil {- return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/groups.templ`, Line: 122, Col: 92}+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/groups.templ`, Line: 122, Col: 92}}_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var11))if templ_7745c5c3_Err != nil {@@ -201,7 +201,7 @@ func Groups(data dash.GroupsPageData) templ.Component {var templ_7745c5c3_Var12 stringtempl_7745c5c3_Var12, templ_7745c5c3_Err = templ.JoinStringErrs("Delete " + group.Name)if templ_7745c5c3_Err != nil {- return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/groups.templ`, Line: 123, Col: 81}+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/groups.templ`, Line: 123, Col: 81}}_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var12))if templ_7745c5c3_Err != nil {@@ -229,7 +229,7 @@ func Groups(data dash.GroupsPageData) templ.Component {var templ_7745c5c3_Var13 stringtempl_7745c5c3_Var13, templ_7745c5c3_Err = templ.JoinStringErrs(user)if templ_7745c5c3_Err != nil {- return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/groups.templ`, Line: 189, Col: 67}+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/groups.templ`, Line: 189, Col: 67}}_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var13))if templ_7745c5c3_Err != nil {@@ -242,7 +242,7 @@ func Groups(data dash.GroupsPageData) templ.Component {var templ_7745c5c3_Var14 stringtempl_7745c5c3_Var14, templ_7745c5c3_Err = templ.JoinStringErrs(user)if templ_7745c5c3_Err != nil {- return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/groups.templ`, Line: 189, Col: 74}+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/groups.templ`, Line: 189, Col: 74}}_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var14))if templ_7745c5c3_Err != nil {@@ -265,7 +265,7 @@ func Groups(data dash.GroupsPageData) templ.Component {var templ_7745c5c3_Var15 stringtempl_7745c5c3_Var15, templ_7745c5c3_Err = templ.JoinStringErrs(policy)if templ_7745c5c3_Err != nil {- return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/groups.templ`, Line: 206, Col: 69}+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/groups.templ`, Line: 206, Col: 69}}_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var15))if templ_7745c5c3_Err != nil {@@ -278,7 +278,7 @@ func Groups(data dash.GroupsPageData) templ.Component {var templ_7745c5c3_Var16 stringtempl_7745c5c3_Var16, templ_7745c5c3_Err = templ.JoinStringErrs(policy)if templ_7745c5c3_Err != nil {- return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/groups.templ`, Line: 206, Col: 78}+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/groups.templ`, Line: 206, Col: 78}}_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var16))if templ_7745c5c3_Err != nil {@@ -289,7 +289,7 @@ func Groups(data dash.GroupsPageData) templ.Component {return templ_7745c5c3_Err}}- templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 28, "</select> <button class=\"btn btn-outline-primary\" type=\"button\" onclick=\"attachPolicyToGroup()\"><i class=\"fas fa-plus\"></i> Attach</button></div></div><div id=\"policiesList\"></div></div><!-- Settings Tab --><div class=\"tab-pane fade\" id=\"settingsPane\" role=\"tabpanel\"><div class=\"form-check form-switch mb-3\"><input class=\"form-check-input\" type=\"checkbox\" id=\"groupEnabledSwitch\" checked onchange=\"toggleGroupStatus()\"> <label class=\"form-check-label\" for=\"groupEnabledSwitch\">Group Enabled</label></div></div></div></div><div class=\"modal-footer\"><button type=\"button\" class=\"btn btn-secondary\" data-bs-dismiss=\"modal\">Close</button></div></div></div></div></div><script src=\"/static/js/iam-utils.js\"></script><script>\n // Groups page JavaScript\n let currentGroupName = '';\n\n async function createGroup() {\n const name = document.getElementById('groupName').value.trim();\n if (!name) {\n showAlert('Group name is required', 'error');\n return;\n }\n try {\n const response = await fetch('/api/groups', {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ name: name })\n });\n if (response.ok) {\n showAlert('Group created successfully', 'success');\n setTimeout(() => window.location.reload(), 1000);\n } else {\n const error = await response.json().catch(() => ({}));\n showAlert('Failed to create group: ' + (error.error || 'Unknown error'), 'error');\n }\n } catch (error) {\n showAlert('Failed to create group: ' + error.message, 'error');\n }\n }\n\n async function viewGroup(name) {\n currentGroupName = name;\n document.getElementById('viewGroupTitle').textContent = 'Group: ' + name;\n await refreshGroupDetails(name);\n new bootstrap.Modal(document.getElementById('viewGroupModal')).show();\n }\n\n async function refreshGroupDetails(requestedName) {\n try {\n const response = await fetch('/api/groups/' + encodeURIComponent(requestedName));\n if (!response.ok) throw new Error('Failed to fetch group');\n if (requestedName !== currentGroupName) return; // stale response\n const group = await response.json();\n\n // Render members using DOM APIs to prevent XSS\n const membersList = document.getElementById('membersList');\n membersList.innerHTML = '';\n const membersTable = document.createElement('table');\n membersTable.className = 'table table-sm';\n const membersTbody = document.createElement('tbody');\n if (group.members && group.members.length > 0) {\n for (const member of group.members) {\n const tr = membersTbody.insertRow();\n const td1 = tr.insertCell();\n td1.textContent = member;\n const td2 = tr.insertCell();\n const btn = document.createElement('button');\n btn.className = 'btn btn-sm btn-outline-danger';\n btn.onclick = () => removeMember(member);\n btn.innerHTML = '<i class=\"fas fa-times\"></i>';\n td2.appendChild(btn);\n }\n } else {\n const tr = membersTbody.insertRow();\n const td = tr.insertCell();\n td.className = 'text-muted';\n td.textContent = 'No members';\n }\n membersTable.appendChild(membersTbody);\n membersList.appendChild(membersTable);\n\n // Render policies using DOM APIs to prevent XSS\n const policiesList = document.getElementById('policiesList');\n policiesList.innerHTML = '';\n const policiesTable = document.createElement('table');\n policiesTable.className = 'table table-sm';\n const policiesTbody = document.createElement('tbody');\n if (group.policy_names && group.policy_names.length > 0) {\n for (const policy of group.policy_names) {\n const tr = policiesTbody.insertRow();\n const td1 = tr.insertCell();\n td1.textContent = policy;\n const td2 = tr.insertCell();\n const btn = document.createElement('button');\n btn.className = 'btn btn-sm btn-outline-danger';\n btn.onclick = () => detachPolicy(policy);\n btn.innerHTML = '<i class=\"fas fa-times\"></i>';\n td2.appendChild(btn);\n }\n } else {\n const tr = policiesTbody.insertRow();\n const td = tr.insertCell();\n td.className = 'text-muted';\n td.textContent = 'No policies attached';\n }\n policiesTable.appendChild(policiesTbody);\n policiesList.appendChild(policiesTable);\n\n // Update status toggle\n document.getElementById('groupEnabledSwitch').checked = (group.status === 'enabled');\n } catch (error) {\n console.error('Error fetching group details:', error);\n }\n }\n\n async function addMemberToGroup() {\n const username = document.getElementById('addMemberSelect').value;\n if (!username) return;\n try {\n const response = await fetch('/api/groups/' + encodeURIComponent(currentGroupName) + '/members', {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ username: username })\n });\n if (response.ok) {\n await refreshGroupDetails(currentGroupName);\n showAlert('Member added', 'success');\n } else {\n const error = await response.json().catch(() => ({}));\n showAlert('Failed to add member: ' + (error.error || 'Unknown error'), 'error');\n }\n } catch (error) {\n showAlert('Failed to add member: ' + error.message, 'error');\n }\n }\n\n async function removeMember(username) {\n try {\n const response = await fetch('/api/groups/' + encodeURIComponent(currentGroupName) + '/members/' + encodeURIComponent(username), {\n method: 'DELETE'\n });\n if (response.ok) {\n await refreshGroupDetails(currentGroupName);\n showAlert('Member removed', 'success');\n } else {\n const error = await response.json().catch(() => ({}));\n showAlert('Failed to remove member: ' + (error.error || 'Unknown error'), 'error');\n }\n } catch (error) {\n showAlert('Failed to remove member: ' + error.message, 'error');\n }\n }\n\n async function attachPolicyToGroup() {\n const policyName = document.getElementById('attachPolicySelect').value;\n if (!policyName) return;\n try {\n const response = await fetch('/api/groups/' + encodeURIComponent(currentGroupName) + '/policies', {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ policy_name: policyName })\n });\n if (response.ok) {\n await refreshGroupDetails(currentGroupName);\n showAlert('Policy attached', 'success');\n } else {\n const error = await response.json().catch(() => ({}));\n showAlert('Failed to attach policy: ' + (error.error || 'Unknown error'), 'error');\n }\n } catch (error) {\n showAlert('Failed to attach policy: ' + error.message, 'error');\n }\n }\n\n async function detachPolicy(policyName) {\n try {\n const response = await fetch('/api/groups/' + encodeURIComponent(currentGroupName) + '/policies/' + encodeURIComponent(policyName), {\n method: 'DELETE'\n });\n if (response.ok) {\n await refreshGroupDetails(currentGroupName);\n showAlert('Policy detached', 'success');\n } else {\n const error = await response.json().catch(() => ({}));\n showAlert('Failed to detach policy: ' + (error.error || 'Unknown error'), 'error');\n }\n } catch (error) {\n showAlert('Failed to detach policy: ' + error.message, 'error');\n }\n }\n\n async function toggleGroupStatus() {\n const enabled = document.getElementById('groupEnabledSwitch').checked;\n try {\n const response = await fetch('/api/groups/' + encodeURIComponent(currentGroupName) + '/status', {\n method: 'PUT',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ enabled: enabled })\n });\n if (response.ok) {\n showAlert('Group status updated', 'success');\n } else {\n const error = await response.json().catch(() => ({}));\n showAlert('Failed to update status: ' + (error.error || 'Unknown error'), 'error');\n }\n } catch (error) {\n showAlert('Failed to update status: ' + error.message, 'error');\n }\n }\n\n // Event delegation for group action buttons\n document.addEventListener('click', function(e) {\n const btn = e.target.closest('[data-action]');\n if (!btn) return;\n const name = btn.dataset.groupName;\n if (!name) return;\n if (btn.dataset.action === 'view') viewGroup(name);\n else if (btn.dataset.action === 'delete') deleteGroup(name);\n });\n </script>")+ templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 28, "</select> <button class=\"btn btn-outline-primary\" type=\"button\" onclick=\"attachPolicyToGroup()\"><i class=\"fas fa-plus\"></i> Attach</button></div></div><div id=\"policiesList\"></div></div><!-- Settings Tab --><div class=\"tab-pane fade\" id=\"settingsPane\" role=\"tabpanel\"><div class=\"form-check form-switch mb-3\"><input class=\"form-check-input\" type=\"checkbox\" id=\"groupEnabledSwitch\" checked onchange=\"toggleGroupStatus()\"> <label class=\"form-check-label\" for=\"groupEnabledSwitch\">Group Enabled</label></div></div></div></div><div class=\"modal-footer\"><button type=\"button\" class=\"btn btn-secondary\" data-bs-dismiss=\"modal\">Close</button></div></div></div></div></div><script>\n // Groups page JavaScript\n let currentGroupName = '';\n\n async function createGroup() {\n const name = document.getElementById('groupName').value.trim();\n if (!name) {\n showAlert('Group name is required', 'error');\n return;\n }\n try {\n const response = await fetch(basePath('/api/groups'), {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ name: name })\n });\n if (response.ok) {\n showAlert('Group created successfully', 'success');\n setTimeout(() => window.location.reload(), 1000);\n } else {\n const error = await response.json().catch(() => ({}));\n showAlert('Failed to create group: ' + (error.error || 'Unknown error'), 'error');\n }\n } catch (error) {\n showAlert('Failed to create group: ' + error.message, 'error');\n }\n }\n\n async function viewGroup(name) {\n currentGroupName = name;\n document.getElementById('viewGroupTitle').textContent = 'Group: ' + name;\n await refreshGroupDetails(name);\n new bootstrap.Modal(document.getElementById('viewGroupModal')).show();\n }\n\n async function refreshGroupDetails(requestedName) {\n try {\n const response = await fetch(basePath('/api/groups/' + encodeURIComponent(requestedName)));\n if (!response.ok) throw new Error('Failed to fetch group');\n if (requestedName !== currentGroupName) return; // stale response\n const group = await response.json();\n\n // Render members using DOM APIs to prevent XSS\n const membersList = document.getElementById('membersList');\n membersList.innerHTML = '';\n const membersTable = document.createElement('table');\n membersTable.className = 'table table-sm';\n const membersTbody = document.createElement('tbody');\n if (group.members && group.members.length > 0) {\n for (const member of group.members) {\n const tr = membersTbody.insertRow();\n const td1 = tr.insertCell();\n td1.textContent = member;\n const td2 = tr.insertCell();\n const btn = document.createElement('button');\n btn.className = 'btn btn-sm btn-outline-danger';\n btn.onclick = () => removeMember(member);\n btn.innerHTML = '<i class=\"fas fa-times\"></i>';\n td2.appendChild(btn);\n }\n } else {\n const tr = membersTbody.insertRow();\n const td = tr.insertCell();\n td.className = 'text-muted';\n td.textContent = 'No members';\n }\n membersTable.appendChild(membersTbody);\n membersList.appendChild(membersTable);\n\n // Render policies using DOM APIs to prevent XSS\n const policiesList = document.getElementById('policiesList');\n policiesList.innerHTML = '';\n const policiesTable = document.createElement('table');\n policiesTable.className = 'table table-sm';\n const policiesTbody = document.createElement('tbody');\n if (group.policy_names && group.policy_names.length > 0) {\n for (const policy of group.policy_names) {\n const tr = policiesTbody.insertRow();\n const td1 = tr.insertCell();\n td1.textContent = policy;\n const td2 = tr.insertCell();\n const btn = document.createElement('button');\n btn.className = 'btn btn-sm btn-outline-danger';\n btn.onclick = () => detachPolicy(policy);\n btn.innerHTML = '<i class=\"fas fa-times\"></i>';\n td2.appendChild(btn);\n }\n } else {\n const tr = policiesTbody.insertRow();\n const td = tr.insertCell();\n td.className = 'text-muted';\n td.textContent = 'No policies attached';\n }\n policiesTable.appendChild(policiesTbody);\n policiesList.appendChild(policiesTable);\n\n // Update status toggle\n document.getElementById('groupEnabledSwitch').checked = (group.status === 'enabled');\n } catch (error) {\n console.error('Error fetching group details:', error);\n }\n }\n\n async function addMemberToGroup() {\n const username = document.getElementById('addMemberSelect').value;\n if (!username) return;\n try {\n const response = await fetch(basePath('/api/groups/' + encodeURIComponent(currentGroupName) + '/members'), {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ username: username })\n });\n if (response.ok) {\n await refreshGroupDetails(currentGroupName);\n showAlert('Member added', 'success');\n } else {\n const error = await response.json().catch(() => ({}));\n showAlert('Failed to add member: ' + (error.error || 'Unknown error'), 'error');\n }\n } catch (error) {\n showAlert('Failed to add member: ' + error.message, 'error');\n }\n }\n\n async function removeMember(username) {\n try {\n const response = await fetch(basePath('/api/groups/' + encodeURIComponent(currentGroupName) + '/members/' + encodeURIComponent(username)), {\n method: 'DELETE'\n });\n if (response.ok) {\n await refreshGroupDetails(currentGroupName);\n showAlert('Member removed', 'success');\n } else {\n const error = await response.json().catch(() => ({}));\n showAlert('Failed to remove member: ' + (error.error || 'Unknown error'), 'error');\n }\n } catch (error) {\n showAlert('Failed to remove member: ' + error.message, 'error');\n }\n }\n\n async function attachPolicyToGroup() {\n const policyName = document.getElementById('attachPolicySelect').value;\n if (!policyName) return;\n try {\n const response = await fetch(basePath('/api/groups/' + encodeURIComponent(currentGroupName) + '/policies'), {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ policy_name: policyName })\n });\n if (response.ok) {\n await refreshGroupDetails(currentGroupName);\n showAlert('Policy attached', 'success');\n } else {\n const error = await response.json().catch(() => ({}));\n showAlert('Failed to attach policy: ' + (error.error || 'Unknown error'), 'error');\n }\n } catch (error) {\n showAlert('Failed to attach policy: ' + error.message, 'error');\n }\n }\n\n async function detachPolicy(policyName) {\n try {\n const response = await fetch(basePath('/api/groups/' + encodeURIComponent(currentGroupName) + '/policies/' + encodeURIComponent(policyName)), {\n method: 'DELETE'\n });\n if (response.ok) {\n await refreshGroupDetails(currentGroupName);\n showAlert('Policy detached', 'success');\n } else {\n const error = await response.json().catch(() => ({}));\n showAlert('Failed to detach policy: ' + (error.error || 'Unknown error'), 'error');\n }\n } catch (error) {\n showAlert('Failed to detach policy: ' + error.message, 'error');\n }\n }\n\n async function toggleGroupStatus() {\n const enabled = document.getElementById('groupEnabledSwitch').checked;\n try {\n const response = await fetch(basePath('/api/groups/' + encodeURIComponent(currentGroupName) + '/status'), {\n method: 'PUT',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ enabled: enabled })\n });\n if (response.ok) {\n showAlert('Group status updated', 'success');\n } else {\n const error = await response.json().catch(() => ({}));\n showAlert('Failed to update status: ' + (error.error || 'Unknown error'), 'error');\n }\n } catch (error) {\n showAlert('Failed to update status: ' + error.message, 'error');\n }\n }\n\n // Event delegation for group action buttons\n document.addEventListener('click', function(e) {\n const btn = e.target.closest('[data-action]');\n if (!btn) return;\n const name = btn.dataset.groupName;\n if (!name) return;\n if (btn.dataset.action === 'view') viewGroup(name);\n else if (btn.dataset.action === 'delete') deleteGroup(name);\n });\n </script>")if templ_7745c5c3_Err != nil {return templ_7745c5c3_Err}diff --git a/weed/admin/view/app/object_store_users.templ b/weed/admin/view/app/object_store_users.templindex 56639522f9..8842cb96aa 100644--- a/weed/admin/view/app/object_store_users.templ+++ b/weed/admin/view/app/object_store_users.templ@@ -504,6 +504,7 @@ templ ObjectStoreUsers(data dash.ObjectStoreUsersData) {const STATUS_ACTIVE = 'Active';const STATUS_INACTIVE = 'Inactive';+ // Use basePath() from admin.js for -urlPrefix; it is loaded in the layout footer before DOMContentLoaded fires.document.addEventListener('DOMContentLoaded', function() {// Event delegation for user action buttons@@ -591,7 +592,7 @@ templ ObjectStoreUsers(data dash.ObjectStoreUsersData) {// Load bucketsasync function loadBuckets() {try {- const response = await fetch('/api/s3/buckets');+ const response = await fetch(basePath('/api/s3/buckets'));if (response.ok) {const data = await response.json();availableBuckets = (data.buckets || []).map(bucket => ({ name: bucket.name, type: 's3' }));@@ -605,7 +606,7 @@ templ ObjectStoreUsers(data dash.ObjectStoreUsersData) {availableBuckets = [];}try {- const response = await fetch('/api/s3tables/buckets');+ const response = await fetch(basePath('/api/s3tables/buckets'));if (response.ok) {const data = await response.json();const tableBuckets = (data.buckets || data.tableBuckets || []).map(bucket => ({ name: bucket.name, type: 's3tables' }));@@ -623,7 +624,7 @@ templ ObjectStoreUsers(data dash.ObjectStoreUsersData) {// Load policiesasync function loadPolicies() {try {- const response = await fetch('/api/object-store/policies');+ const response = await fetch(basePath('/api/object-store/policies'));if (response.ok) {const data = await response.json();const policies = data.policies || [];@@ -910,7 +911,7 @@ templ ObjectStoreUsers(data dash.ObjectStoreUsersData) {async function showUserDetails(username) {try {const encodedUsername = encodeURIComponent(username);- const response = await fetch(`/api/users/${encodedUsername}`);+ const response = await fetch(basePath(`/api/users/${encodedUsername}`));if (response.ok) {const user = await response.json();document.getElementById('userDetailsContent').innerHTML = createUserDetailsContent(user);@@ -929,7 +930,7 @@ templ ObjectStoreUsers(data dash.ObjectStoreUsersData) {async function editUser(username) {try {const encodedUsername = encodeURIComponent(username);- const response = await fetch(`/api/users/${encodedUsername}`);+ const response = await fetch(basePath(`/api/users/${encodedUsername}`));if (response.ok) {const user = await response.json();@@ -1008,7 +1009,7 @@ templ ObjectStoreUsers(data dash.ObjectStoreUsersData) {async function manageAccessKeys(username) {try {const encodedUsername = encodeURIComponent(username);- const response = await fetch(`/api/users/${encodedUsername}`);+ const response = await fetch(basePath(`/api/users/${encodedUsername}`));if (response.ok) {const user = await response.json();document.getElementById('accessKeysUsername').textContent = username;@@ -1029,7 +1030,7 @@ templ ObjectStoreUsers(data dash.ObjectStoreUsersData) {showDeleteConfirm(username, async function() {try {const encodedUsername = encodeURIComponent(username);- const response = await fetch(`/api/users/${encodedUsername}`, {+ const response = await fetch(basePath(`/api/users/${encodedUsername}`), {method: 'DELETE'});@@ -1074,7 +1075,7 @@ templ ObjectStoreUsers(data dash.ObjectStoreUsersData) {};try {- const response = await fetch('/api/users', {+ const response = await fetch(basePath('/api/users'), {method: 'POST',headers: {'Content-Type': 'application/json',@@ -1118,13 +1119,13 @@ templ ObjectStoreUsers(data dash.ObjectStoreUsersData) {try {// Fetch all groups- const groupsResp = await fetch('/api/groups');+ const groupsResp = await fetch(basePath('/api/groups'));if (!groupsResp.ok) return;const groupsData = await groupsResp.json();const allGroups = groupsData.groups || [];// Fetch user details to get current groups- const userResp = await fetch(`/api/users/${encodeURIComponent(username)}`);+ const userResp = await fetch(basePath(`/api/users/${encodeURIComponent(username)}`));if (!userResp.ok) return;const user = await userResp.json();const userGroups = user.groups || [];@@ -1172,7 +1173,7 @@ templ ObjectStoreUsers(data dash.ObjectStoreUsersData) {if (!groupName) return;try {- const response = await fetch(`/api/groups/${encodeURIComponent(groupName)}/members`, {+ const response = await fetch(basePath(`/api/groups/${encodeURIComponent(groupName)}/members`), {method: 'POST',headers: { 'Content-Type': 'application/json' },body: JSON.stringify({ username: username })@@ -1192,7 +1193,7 @@ templ ObjectStoreUsers(data dash.ObjectStoreUsersData) {async function removeUserFromGroupInEdit(groupName) {const username = document.getElementById('editUsername').value;try {- const response = await fetch(`/api/groups/${encodeURIComponent(groupName)}/members/${encodeURIComponent(username)}`, {+ const response = await fetch(basePath(`/api/groups/${encodeURIComponent(groupName)}/members/${encodeURIComponent(username)}`), {method: 'DELETE'});if (response.ok) {@@ -1237,7 +1238,7 @@ templ ObjectStoreUsers(data dash.ObjectStoreUsersData) {try {const encodedUsername = encodeURIComponent(username);- const response = await fetch(`/api/users/${encodedUsername}`, {+ const response = await fetch(basePath(`/api/users/${encodedUsername}`), {method: 'PUT',headers: {'Content-Type': 'application/json',@@ -1374,7 +1375,7 @@ templ ObjectStoreUsers(data dash.ObjectStoreUsersData) {async function refreshAccessKeysList(username) {try {const encodedUsername = encodeURIComponent(username);- const response = await fetch(`/api/users/${encodedUsername}`);+ const response = await fetch(basePath(`/api/users/${encodedUsername}`));if (response.ok) {const user = await response.json();document.getElementById('accessKeysContent').innerHTML = createAccessKeysContent(user);@@ -1387,7 +1388,7 @@ templ ObjectStoreUsers(data dash.ObjectStoreUsersData) {// Update access key statusasync function updateAccessKeyStatus(username, accessKey, status) {try {- const response = await fetch(`/api/users/${encodeURIComponent(username)}/access-keys/${encodeURIComponent(accessKey)}/status`, {+ const response = await fetch(basePath(`/api/users/${encodeURIComponent(username)}/access-keys/${encodeURIComponent(accessKey)}/status`), {method: 'PUT',headers: {'Content-Type': 'application/json',@@ -1473,7 +1474,7 @@ templ ObjectStoreUsers(data dash.ObjectStoreUsersData) {try {const encodedUsername = encodeURIComponent(username);- const response = await fetch(`/api/users/${encodedUsername}/access-keys`, {+ const response = await fetch(basePath(`/api/users/${encodedUsername}/access-keys`), {method: 'POST',headers: {'Content-Type': 'application/json',@@ -1514,7 +1515,7 @@ templ ObjectStoreUsers(data dash.ObjectStoreUsersData) {try {const encodedUsername = encodeURIComponent(username);const encodedAccessKey = encodeURIComponent(accessKey);- const response = await fetch(`/api/users/${encodedUsername}/access-keys/${encodedAccessKey}`, {+ const response = await fetch(basePath(`/api/users/${encodedUsername}/access-keys/${encodedAccessKey}`), {method: 'DELETE'});diff --git a/weed/admin/view/app/object_store_users_templ.go b/weed/admin/view/app/object_store_users_templ.goindex c5227ed6c1..20ba912f5e 100644--- a/weed/admin/view/app/object_store_users_templ.go+++ b/weed/admin/view/app/object_store_users_templ.go@@ -1,6 +1,6 @@// Code generated by templ - DO NOT EDIT.-// templ: version: v0.3.977+// templ: version: v0.3.1001package app//lint:file-ignore SA4006 This context is only used if a nested component is present.@@ -41,7 +41,7 @@ func ObjectStoreUsers(data dash.ObjectStoreUsersData) templ.Component {var templ_7745c5c3_Var2 stringtempl_7745c5c3_Var2, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%d", data.TotalUsers))if templ_7745c5c3_Err != nil {- return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/object_store_users.templ`, Line: 38, Col: 71}+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/object_store_users.templ`, Line: 38, Col: 71}}_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var2))if templ_7745c5c3_Err != nil {@@ -54,7 +54,7 @@ func ObjectStoreUsers(data dash.ObjectStoreUsersData) templ.Component {var templ_7745c5c3_Var3 stringtempl_7745c5c3_Var3, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%d", len(data.Users)))if templ_7745c5c3_Err != nil {- return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/object_store_users.templ`, Line: 58, Col: 71}+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/object_store_users.templ`, Line: 58, Col: 71}}_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var3))if templ_7745c5c3_Err != nil {@@ -67,7 +67,7 @@ func ObjectStoreUsers(data dash.ObjectStoreUsersData) templ.Component {var templ_7745c5c3_Var4 stringtempl_7745c5c3_Var4, templ_7745c5c3_Err = templ.JoinStringErrs(data.LastUpdated.Format("15:04"))if templ_7745c5c3_Err != nil {- return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/object_store_users.templ`, Line: 78, Col: 69}+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/object_store_users.templ`, Line: 78, Col: 69}}_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var4))if templ_7745c5c3_Err != nil {@@ -85,7 +85,7 @@ func ObjectStoreUsers(data dash.ObjectStoreUsersData) templ.Component {var templ_7745c5c3_Var5 stringtempl_7745c5c3_Var5, templ_7745c5c3_Err = templ.JoinStringErrs(user.Username)if templ_7745c5c3_Err != nil {- return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/object_store_users.templ`, Line: 127, Col: 74}+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/object_store_users.templ`, Line: 127, Col: 74}}_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var5))if templ_7745c5c3_Err != nil {@@ -108,7 +108,7 @@ func ObjectStoreUsers(data dash.ObjectStoreUsersData) templ.Component {var templ_7745c5c3_Var6 stringtempl_7745c5c3_Var6, templ_7745c5c3_Err = templ.JoinStringErrs(user.Email)if templ_7745c5c3_Err != nil {- return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/object_store_users.templ`, Line: 133, Col: 59}+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/object_store_users.templ`, Line: 133, Col: 59}}_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var6))if templ_7745c5c3_Err != nil {@@ -121,7 +121,7 @@ func ObjectStoreUsers(data dash.ObjectStoreUsersData) templ.Component {var templ_7745c5c3_Var7 stringtempl_7745c5c3_Var7, templ_7745c5c3_Err = templ.JoinStringErrs(user.AccessKey)if templ_7745c5c3_Err != nil {- return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/object_store_users.templ`, Line: 135, Col: 88}+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/object_store_users.templ`, Line: 135, Col: 88}}_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var7))if templ_7745c5c3_Err != nil {@@ -134,7 +134,7 @@ func ObjectStoreUsers(data dash.ObjectStoreUsersData) templ.Component {var templ_7745c5c3_Var8 stringtempl_7745c5c3_Var8, templ_7745c5c3_Err = templ.JoinStringErrs(user.Username)if templ_7745c5c3_Err != nil {- return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/object_store_users.templ`, Line: 140, Col: 121}+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/object_store_users.templ`, Line: 140, Col: 121}}_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var8))if templ_7745c5c3_Err != nil {@@ -152,7 +152,7 @@ func ObjectStoreUsers(data dash.ObjectStoreUsersData) templ.Component {var templ_7745c5c3_Var9 stringtempl_7745c5c3_Var9, templ_7745c5c3_Err = templ.JoinStringErrs(user.Username)if templ_7745c5c3_Err != nil {- return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/object_store_users.templ`, Line: 145, Col: 117}+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/object_store_users.templ`, Line: 145, Col: 117}}_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var9))if templ_7745c5c3_Err != nil {@@ -171,7 +171,7 @@ func ObjectStoreUsers(data dash.ObjectStoreUsersData) templ.Component {var templ_7745c5c3_Var10 stringtempl_7745c5c3_Var10, templ_7745c5c3_Err = templ.JoinStringErrs(user.Username)if templ_7745c5c3_Err != nil {- return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/object_store_users.templ`, Line: 151, Col: 126}+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/object_store_users.templ`, Line: 151, Col: 126}}_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var10))if templ_7745c5c3_Err != nil {@@ -190,7 +190,7 @@ func ObjectStoreUsers(data dash.ObjectStoreUsersData) templ.Component {var templ_7745c5c3_Var11 stringtempl_7745c5c3_Var11, templ_7745c5c3_Err = templ.JoinStringErrs(user.Username)if templ_7745c5c3_Err != nil {- return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/object_store_users.templ`, Line: 157, Col: 119}+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/object_store_users.templ`, Line: 157, Col: 119}}_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var11))if templ_7745c5c3_Err != nil {@@ -219,7 +219,7 @@ func ObjectStoreUsers(data dash.ObjectStoreUsersData) templ.Component {var templ_7745c5c3_Var12 stringtempl_7745c5c3_Var12, templ_7745c5c3_Err = templ.JoinStringErrs(data.LastUpdated.Format("2006-01-02 15:04:05"))if templ_7745c5c3_Err != nil {- return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/object_store_users.templ`, Line: 189, Col: 81}+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/object_store_users.templ`, Line: 189, Col: 81}}_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var12))if templ_7745c5c3_Err != nil {@@ -240,7 +240,7 @@ func ObjectStoreUsers(data dash.ObjectStoreUsersData) templ.Component {return templ_7745c5c3_Err}}- templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 24, "</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> <optgroup label=\"S3 Tables Permissions\"><option value=\"S3TablesAdmin\">S3 Tables Admin (Full Access)</option> <option value=\"CreateTableBucket\">Create Table Bucket</option> <option value=\"GetTableBucket\">Get Table Bucket</option> <option value=\"ListTableBuckets\">List Table Buckets</option> <option value=\"DeleteTableBucket\">Delete Table Bucket</option> <option value=\"PutTableBucketPolicy\">Put Table Bucket Policy</option> <option value=\"GetTableBucketPolicy\">Get Table Bucket Policy</option> <option value=\"DeleteTableBucketPolicy\">Delete Table Bucket Policy</option> <option value=\"CreateNamespace\">Create Namespace</option> <option value=\"GetNamespace\">Get Namespace</option> <option value=\"ListNamespaces\">List Namespaces</option> <option value=\"DeleteNamespace\">Delete Namespace</option> <option value=\"CreateTable\">Create Table</option> <option value=\"GetTable\">Get Table</option> <option value=\"ListTables\">List Tables</option> <option value=\"DeleteTable\">Delete Table</option> <option value=\"PutTablePolicy\">Put Table Policy</option> <option value=\"GetTablePolicy\">Get Table Policy</option> <option value=\"DeleteTablePolicy\">Delete Table Policy</option> <option value=\"TagResource\">Tag Resource</option> <option value=\"ListTagsForResource\">List Tags</option> <option value=\"UntagResource\">Untag Resource</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> <optgroup label=\"S3 Tables Permissions\"><option value=\"S3TablesAdmin\">S3 Tables Admin (Full Access)</option> <option value=\"CreateTableBucket\">Create Table Bucket</option> <option value=\"GetTableBucket\">Get Table Bucket</option> <option value=\"ListTableBuckets\">List Table Buckets</option> <option value=\"DeleteTableBucket\">Delete Table Bucket</option> <option value=\"PutTableBucketPolicy\">Put Table Bucket Policy</option> <option value=\"GetTableBucketPolicy\">Get Table Bucket Policy</option> <option value=\"DeleteTableBucketPolicy\">Delete Table Bucket Policy</option> <option value=\"CreateNamespace\">Create Namespace</option> <option value=\"GetNamespace\">Get Namespace</option> <option value=\"ListNamespaces\">List Namespaces</option> <option value=\"DeleteNamespace\">Delete Namespace</option> <option value=\"CreateTable\">Create Table</option> <option value=\"GetTable\">Get Table</option> <option value=\"ListTables\">List Tables</option> <option value=\"DeleteTable\">Delete Table</option> <option value=\"PutTablePolicy\">Put Table Policy</option> <option value=\"GetTablePolicy\">Get Table Policy</option> <option value=\"DeleteTablePolicy\">Delete Table Policy</option> <option value=\"TagResource\">Tag Resource</option> <option value=\"ListTagsForResource\">List Tags</option> <option value=\"UntagResource\">Untag Resource</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><div class=\"mb-3\"><label class=\"form-label\">Groups</label><div id=\"editUserGroups\"><!-- Groups loaded dynamically --></div><div class=\"input-group mt-2\"><select class=\"form-select\" id=\"editGroupSelect\"><option value=\"\">Add to group...</option></select> <button class=\"btn btn-outline-primary\" type=\"button\" onclick=\"addUserToGroupFromEdit()\" aria-label=\"Add user to group\" title=\"Add user to group\"><i class=\"fas fa-plus\"></i></button></div></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=\"toggleCreateKeyForm()\"><i class=\"fas fa-plus me-1\"></i>Create New Key</button></div><div id=\"createKeyForm\" class=\"card mb-3\" style=\"display: none;\"><div class=\"card-body\"><p class=\"text-muted small mb-2\">Leave blank to auto-generate.</p><div class=\"mb-2\"><label for=\"newAccessKeyInput\" class=\"form-label form-label-sm\">Access Key</label> <input type=\"text\" class=\"form-control form-control-sm\" id=\"newAccessKeyInput\" placeholder=\"Auto-generated if empty\" minlength=\"4\" maxlength=\"128\"></div><div class=\"mb-2\"><label for=\"newSecretKeyInput\" class=\"form-label form-label-sm\">Secret Key</label><div class=\"input-group input-group-sm\"><input type=\"password\" class=\"form-control form-control-sm\" id=\"newSecretKeyInput\" placeholder=\"Auto-generated if empty\" minlength=\"8\" maxlength=\"128\"> <button class=\"btn btn-outline-secondary\" type=\"button\" onclick=\"toggleSecretKeyVisibility()\" aria-label=\"Toggle secret key visibility\"><i class=\"fas fa-eye\" id=\"secretKeyToggleIcon\"></i></button></div></div><div class=\"d-flex gap-2\"><button type=\"button\" class=\"btn btn-primary btn-sm\" onclick=\"createAccessKey()\">Create</button> <button type=\"button\" class=\"btn btn-secondary btn-sm\" onclick=\"toggleCreateKeyForm()\">Cancel</button></div></div></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 // Access key status constants\n const STATUS_ACTIVE = 'Active';\n const STATUS_INACTIVE = 'Inactive';\n\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 // Event delegation for access key status changes\n document.addEventListener('change', function(e) {\n const statusSelect = e.target.closest('.access-key-status-select');\n if (statusSelect) {\n const username = statusSelect.getAttribute('data-username');\n const accessKey = statusSelect.getAttribute('data-access-key');\n const newStatus = statusSelect.value;\n updateAccessKeyStatus(username, accessKey, newStatus);\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 const s3TablesPermissions = new Set([\n 'CreateTableBucket',\n 'GetTableBucket',\n 'ListTableBuckets',\n 'DeleteTableBucket',\n 'PutTableBucketPolicy',\n 'GetTableBucketPolicy',\n 'DeleteTableBucketPolicy',\n 'CreateNamespace',\n 'GetNamespace',\n 'ListNamespaces',\n 'DeleteNamespace',\n 'CreateTable',\n 'GetTable',\n 'ListTables',\n 'DeleteTable',\n 'PutTablePolicy',\n 'GetTablePolicy',\n 'DeleteTablePolicy',\n 'TagResource',\n 'ListTagsForResource',\n 'UntagResource'\n ]);\n function isS3TablesPermission(permission) {\n return permission === 'S3TablesAdmin' || s3TablesPermissions.has(permission);\n }\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 || []).map(bucket => ({ name: bucket.name, type: 's3' }));\n console.log('Loaded', availableBuckets.length, 'buckets');\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 try {\n const response = await fetch('/api/s3tables/buckets');\n if (response.ok) {\n const data = await response.json();\n const tableBuckets = (data.buckets || data.tableBuckets || []).map(bucket => ({ name: bucket.name, type: 's3tables' }));\n availableBuckets = availableBuckets.concat(tableBuckets);\n } else {\n console.warn('Failed to load table buckets');\n }\n } catch (error) {\n console.warn('Error loading table buckets:', error);\n }\n // Populate bucket selection dropdowns\n populateBucketSelections();\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 showAlert('Failed to load policies: ' + (error.error || 'Unknown error'), 'error');\n }\n } catch (error) {\n console.error('Error loading policies:', error);\n showAlert('Failed to load policies: ' + error.message, 'error');\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 // Toggle anonymous user checkbox\n function toggleAnonymousUser() {\n const checkbox = document.getElementById('anonymousCheck');\n const usernameInput = document.getElementById('username');\n const generateKey = document.getElementById('generateKey');\n if (checkbox.checked) {\n usernameInput.value = 'anonymous';\n usernameInput.readOnly = true;\n generateKey.checked = false;\n generateKey.disabled = true;\n } else {\n usernameInput.value = '';\n usernameInput.readOnly = false;\n generateKey.disabled = false;\n generateKey.checked = true;\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.type + ':' + bucket.name;\n option.textContent = bucket.type === 's3tables' ? `Table: ${bucket.name}` : 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.startsWith('s3tables:')) {\n const actionValue = action.slice('s3tables:'.length);\n if (actionValue === '*') {\n globalBucketPerms.push('S3TablesAdmin');\n return;\n }\n const parts = actionValue.split(':');\n const perm = parts[0];\n const bucket = parts.length > 1 ? parts.slice(1).join(':').replace(/\\/\\*$/, '') : '';\n if (bucket) {\n bucketActions.push({ permission: perm, bucketId: 's3tables:' + bucket });\n } else {\n globalBucketPerms.push(perm);\n }\n } else 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, bucketId: 's3:' + 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.bucketId))];\n\n result.permissions = perms;\n result.applyToAll = false;\n result.specificBuckets = buckets;\n }\n\n return result;\n }\n\n function parseBucketOptionValue(value) {\n if (value.startsWith('s3tables:')) {\n return { type: 's3tables', name: value.slice('s3tables:'.length) };\n }\n if (value.startsWith('s3:')) {\n return { type: 's3', name: value.slice('s3:'.length) };\n }\n return { type: 's3', name: value };\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 const hasAdmin = selectedPerms.includes('Admin');\n const hasS3TablesAdmin = selectedPerms.includes('S3TablesAdmin');\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 const actions = [];\n if (hasAdmin) {\n actions.push('Admin');\n }\n if (hasS3TablesAdmin) {\n actions.push('s3tables:*');\n }\n selectedPerms.forEach(perm => {\n if (perm === 'Admin' || perm === 'S3TablesAdmin') {\n return;\n }\n if (isS3TablesPermission(perm)) {\n actions.push('s3tables:' + perm);\n } else {\n actions.push(perm);\n }\n });\n return actions;\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 = [...new Set(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 if (hasAdmin) {\n selectedBuckets.forEach((bucket) => {\n const bucketInfo = parseBucketOptionValue(bucket);\n actions.push(\"Admin:\" + bucketInfo.name);\n });\n }\n if (hasS3TablesAdmin) {\n actions.push('s3tables:*');\n }\n selectedPerms.forEach(perm => {\n if (perm === 'Admin' || perm === 'S3TablesAdmin') {\n return;\n }\n selectedBuckets.forEach(bucket => {\n const bucketInfo = parseBucketOptionValue(bucket);\n if (isS3TablesPermission(perm)) {\n if (bucketInfo.type === 's3tables') {\n actions.push('s3tables:' + perm + ':' + bucketInfo.name);\n }\n } else if (bucketInfo.type === 's3') {\n actions.push(perm + ':' + bucketInfo.name);\n }\n });\n });\n\n return [...new Set(actions)];\n }\n }\n\n // Show user details modal\n async function showUserDetails(username) {\n try {\n const encodedUsername = encodeURIComponent(username);\n const response = await fetch(`/api/users/${encodedUsername}`);\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 showAlert('Failed to load user details', 'error');\n }\n } catch (error) {\n console.error('Error loading user details:', error);\n showAlert('Failed to load user details', 'error');\n }\n }\n\n // Edit user function\n async function editUser(username) {\n try {\n const encodedUsername = encodeURIComponent(username);\n const response = await fetch(`/api/users/${encodedUsername}`);\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 // Populate groups\n await populateEditUserGroups(username);\n\n // Show modal\n const modal = new bootstrap.Modal(document.getElementById('editUserModal'));\n modal.show();\n } else {\n showAlert('Failed to load user details', 'error');\n }\n } catch (error) {\n console.error('Error loading user:', error);\n showAlert('Failed to load user details', 'error');\n }\n }\n\n // Manage access keys function\n async function manageAccessKeys(username) {\n try {\n const encodedUsername = encodeURIComponent(username);\n const response = await fetch(`/api/users/${encodedUsername}`);\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 showAlert('Failed to load access keys', 'error');\n }\n } catch (error) {\n console.error('Error loading access keys:', error);\n showAlert('Failed to load access keys', 'error');\n }\n }\n\n // Delete user function\n async function deleteUser(username) {\n showDeleteConfirm(username, async function() {\n try {\n const encodedUsername = encodeURIComponent(username);\n const response = await fetch(`/api/users/${encodedUsername}`, {\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 }, 'Are you sure you want to delete this user? This action cannot be undone.');\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 if (allActions === null) {\n showAlert('Please select at least one bucket when using specific bucket permissions', 'error');\n return;\n }\n\n if (!allActions || allActions.length === 0) {\n showAlert('At least one permission must be selected', 'error');\n return;\n }\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 document.getElementById('username').readOnly = false;\n document.getElementById('generateKey').disabled = false;\n setTimeout(() => window.location.reload(), 1000);\n } else {\n const error = await response.json();\n showAlert('Failed to create user: ' + (error.error || 'Unknown error'), 'error');\n }\n } catch (error) {\n console.error('Error creating user:', error);\n showAlert('Failed to create user: ' + error.message, 'error');\n }\n }\n\n\n // Populate groups in the edit user modal\n async function populateEditUserGroups(username) {\n const container = document.getElementById('editUserGroups');\n const groupSelect = document.getElementById('editGroupSelect');\n container.innerHTML = '';\n groupSelect.innerHTML = '<option value=\"\">Add to group...</option>';\n\n try {\n // Fetch all groups\n const groupsResp = await fetch('/api/groups');\n if (!groupsResp.ok) return;\n const groupsData = await groupsResp.json();\n const allGroups = groupsData.groups || [];\n\n // Fetch user details to get current groups\n const userResp = await fetch(`/api/users/${encodeURIComponent(username)}`);\n if (!userResp.ok) return;\n const user = await userResp.json();\n const userGroups = user.groups || [];\n\n // Show current group badges with remove button\n if (userGroups.length > 0) {\n userGroups.forEach(function(group) {\n const badge = document.createElement('span');\n badge.className = 'badge bg-primary me-1 mb-1';\n badge.textContent = group + ' ';\n const removeIcon = document.createElement('i');\n removeIcon.className = 'fas fa-times ms-1';\n removeIcon.style.cursor = 'pointer';\n removeIcon.setAttribute('aria-label', 'Remove from group ' + group);\n removeIcon.setAttribute('title', 'Remove from group');\n removeIcon.addEventListener('click', function() {\n removeUserFromGroupInEdit(group);\n });\n badge.appendChild(removeIcon);\n container.appendChild(badge);\n });\n } else {\n container.innerHTML = '<span class=\"text-muted\">No groups</span>';\n }\n\n // Populate dropdown with groups the user is NOT in\n allGroups.forEach(function(g) {\n if (!userGroups.includes(g.name)) {\n const opt = document.createElement('option');\n opt.value = g.name;\n opt.textContent = g.name;\n groupSelect.appendChild(opt);\n }\n });\n } catch (error) {\n console.error('Error loading groups:', error);\n }\n }\n\n // Add user to group from edit modal\n async function addUserToGroupFromEdit() {\n const username = document.getElementById('editUsername').value;\n const groupSelect = document.getElementById('editGroupSelect');\n const groupName = groupSelect.value;\n if (!groupName) return;\n\n try {\n const response = await fetch(`/api/groups/${encodeURIComponent(groupName)}/members`, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ username: username })\n });\n if (response.ok) {\n await populateEditUserGroups(username);\n } else {\n const error = await response.json();\n showAlert('Failed to add to group: ' + (error.error || 'Unknown error'), 'error');\n }\n } catch (error) {\n showAlert('Failed to add to group: ' + error.message, 'error');\n }\n }\n\n // Remove user from group in edit modal\n async function removeUserFromGroupInEdit(groupName) {\n const username = document.getElementById('editUsername').value;\n try {\n const response = await fetch(`/api/groups/${encodeURIComponent(groupName)}/members/${encodeURIComponent(username)}`, {\n method: 'DELETE'\n });\n if (response.ok) {\n await populateEditUserGroups(username);\n } else {\n const error = await response.json();\n showAlert('Failed to remove from group: ' + (error.error || 'Unknown error'), 'error');\n }\n } catch (error) {\n showAlert('Failed to remove from group: ' + error.message, 'error');\n }\n }\n\n // Handle update user form submission\n async function handleUpdateUser() {\n const username = document.getElementById('editUsername').value;\n if (!username) {\n showAlert('Username is required', 'error');\n return;\n }\n\n // Get permissions with bucket scope applied\n const allActions = buildBucketPermissions('edit');\n\n // Check for null (validation failure from buildBucketPermissions)\n if (allActions === null) {\n showAlert('Please select at least one bucket when using specific bucket permissions', 'error');\n return;\n }\n\n // Validate that permissions are not empty\n if (!allActions || allActions.length === 0) {\n showAlert('At least one permission must be selected', 'error');\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 encodedUsername = encodeURIComponent(username);\n const response = await fetch(`/api/users/${encodedUsername}`, {\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 showAlert('Failed to update user: ' + (error.error || 'Unknown error'), 'error');\n }\n } catch (error) {\n console.error('Error updating user:', error);\n showAlert('Failed to update user: ' + error.message, 'error');\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\">Groups</h6>';\n detailsHtml += '<div class=\"mb-3\">';\n if (user.groups && user.groups.length > 0) {\n detailsHtml += user.groups.map(function(group) {\n return '<span class=\"badge bg-primary me-1\">' + escapeHtml(group) + '</span>';\n }).join('');\n } else {\n detailsHtml += '<span class=\"text-muted\">No groups</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>';\n keysHtml += '<select class=\"form-select form-select-sm access-key-status-select\" data-username=\"' + escapeHtml(user.username) + '\" data-access-key=\"' + escapeHtml(key.access_key) + '\" style=\"width: 110px;\">';\n keysHtml += '<option value=\"' + STATUS_ACTIVE + '\" ' + (key.status === STATUS_ACTIVE || !key.status ? 'selected' : '') + '>' + STATUS_ACTIVE + '</option>';\n keysHtml += '<option value=\"' + STATUS_INACTIVE + '\" ' + (key.status === STATUS_INACTIVE ? 'selected' : '') + '>' + STATUS_INACTIVE + '</option>';\n keysHtml += '</select>';\n keysHtml += '</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 // Refresh access keys list content\n async function refreshAccessKeysList(username) {\n try {\n const encodedUsername = encodeURIComponent(username);\n const response = await fetch(`/api/users/${encodedUsername}`);\n if (response.ok) {\n const user = await response.json();\n document.getElementById('accessKeysContent').innerHTML = createAccessKeysContent(user);\n }\n } catch (error) {\n console.error('Error refreshing access keys:', error);\n }\n }\n\n // Update access key status\n async function updateAccessKeyStatus(username, accessKey, status) {\n try {\n const response = await fetch(`/api/users/${encodeURIComponent(username)}/access-keys/${encodeURIComponent(accessKey)}/status`, {\n method: 'PUT',\n headers: {\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify({ status: status })\n });\n\n if (response.ok) {\n showSuccessMessage('Access key status updated successfully');\n // Refresh access keys display without toggling modal\n refreshAccessKeysList(username);\n } else {\n const error = await response.json();\n showAlert('Failed to update access key status: ' + (error.error || 'Unknown error'), 'error');\n refreshAccessKeysList(username);\n }\n } catch (error) {\n console.error('Error updating access key status:', error);\n showAlert('Failed to update access key status: ' + error.message, 'error');\n refreshAccessKeysList(username);\n }\n }\n\n // Reset and hide the create key form\n function resetCreateKeyForm() {\n document.getElementById('createKeyForm').style.display = 'none';\n document.getElementById('newAccessKeyInput').value = '';\n document.getElementById('newSecretKeyInput').value = '';\n document.getElementById('newSecretKeyInput').type = 'password';\n document.getElementById('secretKeyToggleIcon').className = 'fas fa-eye';\n }\n\n // Toggle create key form visibility\n function toggleCreateKeyForm() {\n const form = document.getElementById('createKeyForm');\n if (form.style.display === 'none') {\n form.style.display = 'block';\n } else {\n resetCreateKeyForm();\n }\n }\n\n // Toggle secret key input visibility\n function toggleSecretKeyVisibility() {\n const input = document.getElementById('newSecretKeyInput');\n const icon = document.getElementById('secretKeyToggleIcon');\n if (input.type === 'password') {\n input.type = 'text';\n icon.className = 'fas fa-eye-slash';\n } else {\n input.type = 'password';\n icon.className = 'fas fa-eye';\n }\n }\n\n // Reset form when modal is dismissed\n document.getElementById('accessKeysModal').addEventListener('hidden.bs.modal', resetCreateKeyForm);\n\n // Create new access key\n var isCreatingKey = false;\n async function createAccessKey() {\n if (isCreatingKey) return;\n\n const username = document.getElementById('accessKeysUsername').textContent;\n const accessKeyInput = document.getElementById('newAccessKeyInput');\n const secretKeyInput = document.getElementById('newSecretKeyInput');\n if ((accessKeyInput.value.trim() && !accessKeyInput.reportValidity()) ||\n (secretKeyInput.value.trim() && !secretKeyInput.reportValidity())) {\n return;\n }\n const accessKey = accessKeyInput.value.trim();\n const secretKey = secretKeyInput.value.trim();\n\n const body = {};\n if (accessKey) body.access_key = accessKey;\n if (secretKey) body.secret_key = secretKey;\n\n isCreatingKey = true;\n const createBtn = document.querySelector('#createKeyForm .btn-primary');\n const cancelBtn = document.querySelector('#createKeyForm .btn-secondary');\n if (createBtn) createBtn.disabled = true;\n if (cancelBtn) cancelBtn.disabled = true;\n\n try {\n const encodedUsername = encodeURIComponent(username);\n const response = await fetch(`/api/users/${encodedUsername}/access-keys`, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify(body)\n });\n\n if (response.ok) {\n const result = await response.json();\n\n // Show the new access key details\n if (result.access_key) {\n showNewAccessKeyModal(result.access_key);\n }\n\n showSuccessMessage('Access key created successfully');\n resetCreateKeyForm();\n\n // Refresh access keys display\n refreshAccessKeysList(username);\n } else {\n const error = await response.json();\n showAlert('Failed to create access key: ' + (error.error || 'Unknown error'), 'error');\n }\n } catch (error) {\n console.error('Error creating access key:', error);\n showAlert('Failed to create access key: ' + error.message, 'error');\n } finally {\n isCreatingKey = false;\n if (createBtn) createBtn.disabled = false;\n if (cancelBtn) cancelBtn.disabled = false;\n }\n }\n\n // Delete access key\n async function deleteAccessKey(username, accessKey) {\n showDeleteConfirm(accessKey, async function() {\n try {\n const encodedUsername = encodeURIComponent(username);\n const encodedAccessKey = encodeURIComponent(accessKey);\n const response = await fetch(`/api/users/${encodedUsername}/access-keys/${encodedAccessKey}`, {\n method: 'DELETE'\n });\n\n if (response.ok) {\n showSuccessMessage('Access key deleted successfully');\n\n // Refresh access keys display\n refreshAccessKeysList(username);\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 }, 'Are you sure you want to delete this access key?');\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 showAlert(message, 'error');\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, 24, "</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> <optgroup label=\"S3 Tables Permissions\"><option value=\"S3TablesAdmin\">S3 Tables Admin (Full Access)</option> <option value=\"CreateTableBucket\">Create Table Bucket</option> <option value=\"GetTableBucket\">Get Table Bucket</option> <option value=\"ListTableBuckets\">List Table Buckets</option> <option value=\"DeleteTableBucket\">Delete Table Bucket</option> <option value=\"PutTableBucketPolicy\">Put Table Bucket Policy</option> <option value=\"GetTableBucketPolicy\">Get Table Bucket Policy</option> <option value=\"DeleteTableBucketPolicy\">Delete Table Bucket Policy</option> <option value=\"CreateNamespace\">Create Namespace</option> <option value=\"GetNamespace\">Get Namespace</option> <option value=\"ListNamespaces\">List Namespaces</option> <option value=\"DeleteNamespace\">Delete Namespace</option> <option value=\"CreateTable\">Create Table</option> <option value=\"GetTable\">Get Table</option> <option value=\"ListTables\">List Tables</option> <option value=\"DeleteTable\">Delete Table</option> <option value=\"PutTablePolicy\">Put Table Policy</option> <option value=\"GetTablePolicy\">Get Table Policy</option> <option value=\"DeleteTablePolicy\">Delete Table Policy</option> <option value=\"TagResource\">Tag Resource</option> <option value=\"ListTagsForResource\">List Tags</option> <option value=\"UntagResource\">Untag Resource</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> <optgroup label=\"S3 Tables Permissions\"><option value=\"S3TablesAdmin\">S3 Tables Admin (Full Access)</option> <option value=\"CreateTableBucket\">Create Table Bucket</option> <option value=\"GetTableBucket\">Get Table Bucket</option> <option value=\"ListTableBuckets\">List Table Buckets</option> <option value=\"DeleteTableBucket\">Delete Table Bucket</option> <option value=\"PutTableBucketPolicy\">Put Table Bucket Policy</option> <option value=\"GetTableBucketPolicy\">Get Table Bucket Policy</option> <option value=\"DeleteTableBucketPolicy\">Delete Table Bucket Policy</option> <option value=\"CreateNamespace\">Create Namespace</option> <option value=\"GetNamespace\">Get Namespace</option> <option value=\"ListNamespaces\">List Namespaces</option> <option value=\"DeleteNamespace\">Delete Namespace</option> <option value=\"CreateTable\">Create Table</option> <option value=\"GetTable\">Get Table</option> <option value=\"ListTables\">List Tables</option> <option value=\"DeleteTable\">Delete Table</option> <option value=\"PutTablePolicy\">Put Table Policy</option> <option value=\"GetTablePolicy\">Get Table Policy</option> <option value=\"DeleteTablePolicy\">Delete Table Policy</option> <option value=\"TagResource\">Tag Resource</option> <option value=\"ListTagsForResource\">List Tags</option> <option value=\"UntagResource\">Untag Resource</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><div class=\"mb-3\"><label class=\"form-label\">Groups</label><div id=\"editUserGroups\"><!-- Groups loaded dynamically --></div><div class=\"input-group mt-2\"><select class=\"form-select\" id=\"editGroupSelect\"><option value=\"\">Add to group...</option></select> <button class=\"btn btn-outline-primary\" type=\"button\" onclick=\"addUserToGroupFromEdit()\" aria-label=\"Add user to group\" title=\"Add user to group\"><i class=\"fas fa-plus\"></i></button></div></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=\"toggleCreateKeyForm()\"><i class=\"fas fa-plus me-1\"></i>Create New Key</button></div><div id=\"createKeyForm\" class=\"card mb-3\" style=\"display: none;\"><div class=\"card-body\"><p class=\"text-muted small mb-2\">Leave blank to auto-generate.</p><div class=\"mb-2\"><label for=\"newAccessKeyInput\" class=\"form-label form-label-sm\">Access Key</label> <input type=\"text\" class=\"form-control form-control-sm\" id=\"newAccessKeyInput\" placeholder=\"Auto-generated if empty\" minlength=\"4\" maxlength=\"128\"></div><div class=\"mb-2\"><label for=\"newSecretKeyInput\" class=\"form-label form-label-sm\">Secret Key</label><div class=\"input-group input-group-sm\"><input type=\"password\" class=\"form-control form-control-sm\" id=\"newSecretKeyInput\" placeholder=\"Auto-generated if empty\" minlength=\"8\" maxlength=\"128\"> <button class=\"btn btn-outline-secondary\" type=\"button\" onclick=\"toggleSecretKeyVisibility()\" aria-label=\"Toggle secret key visibility\"><i class=\"fas fa-eye\" id=\"secretKeyToggleIcon\"></i></button></div></div><div class=\"d-flex gap-2\"><button type=\"button\" class=\"btn btn-primary btn-sm\" onclick=\"createAccessKey()\">Create</button> <button type=\"button\" class=\"btn btn-secondary btn-sm\" onclick=\"toggleCreateKeyForm()\">Cancel</button></div></div></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 // Access key status constants\n const STATUS_ACTIVE = 'Active';\n const STATUS_INACTIVE = 'Inactive';\n\n // Use basePath() from admin.js for -urlPrefix; it is loaded in the layout footer before DOMContentLoaded fires.\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 // Event delegation for access key status changes\n document.addEventListener('change', function(e) {\n const statusSelect = e.target.closest('.access-key-status-select');\n if (statusSelect) {\n const username = statusSelect.getAttribute('data-username');\n const accessKey = statusSelect.getAttribute('data-access-key');\n const newStatus = statusSelect.value;\n updateAccessKeyStatus(username, accessKey, newStatus);\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 const s3TablesPermissions = new Set([\n 'CreateTableBucket',\n 'GetTableBucket',\n 'ListTableBuckets',\n 'DeleteTableBucket',\n 'PutTableBucketPolicy',\n 'GetTableBucketPolicy',\n 'DeleteTableBucketPolicy',\n 'CreateNamespace',\n 'GetNamespace',\n 'ListNamespaces',\n 'DeleteNamespace',\n 'CreateTable',\n 'GetTable',\n 'ListTables',\n 'DeleteTable',\n 'PutTablePolicy',\n 'GetTablePolicy',\n 'DeleteTablePolicy',\n 'TagResource',\n 'ListTagsForResource',\n 'UntagResource'\n ]);\n function isS3TablesPermission(permission) {\n return permission === 'S3TablesAdmin' || s3TablesPermissions.has(permission);\n }\n\n // Load buckets\n async function loadBuckets() {\n try {\n const response = await fetch(basePath('/api/s3/buckets'));\n if (response.ok) {\n const data = await response.json();\n availableBuckets = (data.buckets || []).map(bucket => ({ name: bucket.name, type: 's3' }));\n console.log('Loaded', availableBuckets.length, 'buckets');\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 try {\n const response = await fetch(basePath('/api/s3tables/buckets'));\n if (response.ok) {\n const data = await response.json();\n const tableBuckets = (data.buckets || data.tableBuckets || []).map(bucket => ({ name: bucket.name, type: 's3tables' }));\n availableBuckets = availableBuckets.concat(tableBuckets);\n } else {\n console.warn('Failed to load table buckets');\n }\n } catch (error) {\n console.warn('Error loading table buckets:', error);\n }\n // Populate bucket selection dropdowns\n populateBucketSelections();\n }\n\n // Load policies\n async function loadPolicies() {\n try {\n const response = await fetch(basePath('/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 showAlert('Failed to load policies: ' + (error.error || 'Unknown error'), 'error');\n }\n } catch (error) {\n console.error('Error loading policies:', error);\n showAlert('Failed to load policies: ' + error.message, 'error');\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 // Toggle anonymous user checkbox\n function toggleAnonymousUser() {\n const checkbox = document.getElementById('anonymousCheck');\n const usernameInput = document.getElementById('username');\n const generateKey = document.getElementById('generateKey');\n if (checkbox.checked) {\n usernameInput.value = 'anonymous';\n usernameInput.readOnly = true;\n generateKey.checked = false;\n generateKey.disabled = true;\n } else {\n usernameInput.value = '';\n usernameInput.readOnly = false;\n generateKey.disabled = false;\n generateKey.checked = true;\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.type + ':' + bucket.name;\n option.textContent = bucket.type === 's3tables' ? `Table: ${bucket.name}` : 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.startsWith('s3tables:')) {\n const actionValue = action.slice('s3tables:'.length);\n if (actionValue === '*') {\n globalBucketPerms.push('S3TablesAdmin');\n return;\n }\n const parts = actionValue.split(':');\n const perm = parts[0];\n const bucket = parts.length > 1 ? parts.slice(1).join(':').replace(/\\/\\*$/, '') : '';\n if (bucket) {\n bucketActions.push({ permission: perm, bucketId: 's3tables:' + bucket });\n } else {\n globalBucketPerms.push(perm);\n }\n } else 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, bucketId: 's3:' + 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.bucketId))];\n\n result.permissions = perms;\n result.applyToAll = false;\n result.specificBuckets = buckets;\n }\n\n return result;\n }\n\n function parseBucketOptionValue(value) {\n if (value.startsWith('s3tables:')) {\n return { type: 's3tables', name: value.slice('s3tables:'.length) };\n }\n if (value.startsWith('s3:')) {\n return { type: 's3', name: value.slice('s3:'.length) };\n }\n return { type: 's3', name: value };\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 const hasAdmin = selectedPerms.includes('Admin');\n const hasS3TablesAdmin = selectedPerms.includes('S3TablesAdmin');\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 const actions = [];\n if (hasAdmin) {\n actions.push('Admin');\n }\n if (hasS3TablesAdmin) {\n actions.push('s3tables:*');\n }\n selectedPerms.forEach(perm => {\n if (perm === 'Admin' || perm === 'S3TablesAdmin') {\n return;\n }\n if (isS3TablesPermission(perm)) {\n actions.push('s3tables:' + perm);\n } else {\n actions.push(perm);\n }\n });\n return actions;\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 = [...new Set(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 if (hasAdmin) {\n selectedBuckets.forEach((bucket) => {\n const bucketInfo = parseBucketOptionValue(bucket);\n actions.push(\"Admin:\" + bucketInfo.name);\n });\n }\n if (hasS3TablesAdmin) {\n actions.push('s3tables:*');\n }\n selectedPerms.forEach(perm => {\n if (perm === 'Admin' || perm === 'S3TablesAdmin') {\n return;\n }\n selectedBuckets.forEach(bucket => {\n const bucketInfo = parseBucketOptionValue(bucket);\n if (isS3TablesPermission(perm)) {\n if (bucketInfo.type === 's3tables') {\n actions.push('s3tables:' + perm + ':' + bucketInfo.name);\n }\n } else if (bucketInfo.type === 's3') {\n actions.push(perm + ':' + bucketInfo.name);\n }\n });\n });\n\n return [...new Set(actions)];\n }\n }\n\n // Show user details modal\n async function showUserDetails(username) {\n try {\n const encodedUsername = encodeURIComponent(username);\n const response = await fetch(basePath(`/api/users/${encodedUsername}`));\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 showAlert('Failed to load user details', 'error');\n }\n } catch (error) {\n console.error('Error loading user details:', error);\n showAlert('Failed to load user details', 'error');\n }\n }\n\n // Edit user function\n async function editUser(username) {\n try {\n const encodedUsername = encodeURIComponent(username);\n const response = await fetch(basePath(`/api/users/${encodedUsername}`));\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 // Populate groups\n await populateEditUserGroups(username);\n\n // Show modal\n const modal = new bootstrap.Modal(document.getElementById('editUserModal'));\n modal.show();\n } else {\n showAlert('Failed to load user details', 'error');\n }\n } catch (error) {\n console.error('Error loading user:', error);\n showAlert('Failed to load user details', 'error');\n }\n }\n\n // Manage access keys function\n async function manageAccessKeys(username) {\n try {\n const encodedUsername = encodeURIComponent(username);\n const response = await fetch(basePath(`/api/users/${encodedUsername}`));\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 showAlert('Failed to load access keys', 'error');\n }\n } catch (error) {\n console.error('Error loading access keys:', error);\n showAlert('Failed to load access keys', 'error');\n }\n }\n\n // Delete user function\n async function deleteUser(username) {\n showDeleteConfirm(username, async function() {\n try {\n const encodedUsername = encodeURIComponent(username);\n const response = await fetch(basePath(`/api/users/${encodedUsername}`), {\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 }, 'Are you sure you want to delete this user? This action cannot be undone.');\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 if (allActions === null) {\n showAlert('Please select at least one bucket when using specific bucket permissions', 'error');\n return;\n }\n\n if (!allActions || allActions.length === 0) {\n showAlert('At least one permission must be selected', 'error');\n return;\n }\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(basePath('/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 document.getElementById('username').readOnly = false;\n document.getElementById('generateKey').disabled = false;\n setTimeout(() => window.location.reload(), 1000);\n } else {\n const error = await response.json();\n showAlert('Failed to create user: ' + (error.error || 'Unknown error'), 'error');\n }\n } catch (error) {\n console.error('Error creating user:', error);\n showAlert('Failed to create user: ' + error.message, 'error');\n }\n }\n\n\n // Populate groups in the edit user modal\n async function populateEditUserGroups(username) {\n const container = document.getElementById('editUserGroups');\n const groupSelect = document.getElementById('editGroupSelect');\n container.innerHTML = '';\n groupSelect.innerHTML = '<option value=\"\">Add to group...</option>';\n\n try {\n // Fetch all groups\n const groupsResp = await fetch(basePath('/api/groups'));\n if (!groupsResp.ok) return;\n const groupsData = await groupsResp.json();\n const allGroups = groupsData.groups || [];\n\n // Fetch user details to get current groups\n const userResp = await fetch(basePath(`/api/users/${encodeURIComponent(username)}`));\n if (!userResp.ok) return;\n const user = await userResp.json();\n const userGroups = user.groups || [];\n\n // Show current group badges with remove button\n if (userGroups.length > 0) {\n userGroups.forEach(function(group) {\n const badge = document.createElement('span');\n badge.className = 'badge bg-primary me-1 mb-1';\n badge.textContent = group + ' ';\n const removeIcon = document.createElement('i');\n removeIcon.className = 'fas fa-times ms-1';\n removeIcon.style.cursor = 'pointer';\n removeIcon.setAttribute('aria-label', 'Remove from group ' + group);\n removeIcon.setAttribute('title', 'Remove from group');\n removeIcon.addEventListener('click', function() {\n removeUserFromGroupInEdit(group);\n });\n badge.appendChild(removeIcon);\n container.appendChild(badge);\n });\n } else {\n container.innerHTML = '<span class=\"text-muted\">No groups</span>';\n }\n\n // Populate dropdown with groups the user is NOT in\n allGroups.forEach(function(g) {\n if (!userGroups.includes(g.name)) {\n const opt = document.createElement('option');\n opt.value = g.name;\n opt.textContent = g.name;\n groupSelect.appendChild(opt);\n }\n });\n } catch (error) {\n console.error('Error loading groups:', error);\n }\n }\n\n // Add user to group from edit modal\n async function addUserToGroupFromEdit() {\n const username = document.getElementById('editUsername').value;\n const groupSelect = document.getElementById('editGroupSelect');\n const groupName = groupSelect.value;\n if (!groupName) return;\n\n try {\n const response = await fetch(basePath(`/api/groups/${encodeURIComponent(groupName)}/members`), {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ username: username })\n });\n if (response.ok) {\n await populateEditUserGroups(username);\n } else {\n const error = await response.json();\n showAlert('Failed to add to group: ' + (error.error || 'Unknown error'), 'error');\n }\n } catch (error) {\n showAlert('Failed to add to group: ' + error.message, 'error');\n }\n }\n\n // Remove user from group in edit modal\n async function removeUserFromGroupInEdit(groupName) {\n const username = document.getElementById('editUsername').value;\n try {\n const response = await fetch(basePath(`/api/groups/${encodeURIComponent(groupName)}/members/${encodeURIComponent(username)}`), {\n method: 'DELETE'\n });\n if (response.ok) {\n await populateEditUserGroups(username);\n } else {\n const error = await response.json();\n showAlert('Failed to remove from group: ' + (error.error || 'Unknown error'), 'error');\n }\n } catch (error) {\n showAlert('Failed to remove from group: ' + error.message, 'error');\n }\n }\n\n // Handle update user form submission\n async function handleUpdateUser() {\n const username = document.getElementById('editUsername').value;\n if (!username) {\n showAlert('Username is required', 'error');\n return;\n }\n\n // Get permissions with bucket scope applied\n const allActions = buildBucketPermissions('edit');\n\n // Check for null (validation failure from buildBucketPermissions)\n if (allActions === null) {\n showAlert('Please select at least one bucket when using specific bucket permissions', 'error');\n return;\n }\n\n // Validate that permissions are not empty\n if (!allActions || allActions.length === 0) {\n showAlert('At least one permission must be selected', 'error');\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 encodedUsername = encodeURIComponent(username);\n const response = await fetch(basePath(`/api/users/${encodedUsername}`), {\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 showAlert('Failed to update user: ' + (error.error || 'Unknown error'), 'error');\n }\n } catch (error) {\n console.error('Error updating user:', error);\n showAlert('Failed to update user: ' + error.message, 'error');\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\">Groups</h6>';\n detailsHtml += '<div class=\"mb-3\">';\n if (user.groups && user.groups.length > 0) {\n detailsHtml += user.groups.map(function(group) {\n return '<span class=\"badge bg-primary me-1\">' + escapeHtml(group) + '</span>';\n }).join('');\n } else {\n detailsHtml += '<span class=\"text-muted\">No groups</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>';\n keysHtml += '<select class=\"form-select form-select-sm access-key-status-select\" data-username=\"' + escapeHtml(user.username) + '\" data-access-key=\"' + escapeHtml(key.access_key) + '\" style=\"width: 110px;\">';\n keysHtml += '<option value=\"' + STATUS_ACTIVE + '\" ' + (key.status === STATUS_ACTIVE || !key.status ? 'selected' : '') + '>' + STATUS_ACTIVE + '</option>';\n keysHtml += '<option value=\"' + STATUS_INACTIVE + '\" ' + (key.status === STATUS_INACTIVE ? 'selected' : '') + '>' + STATUS_INACTIVE + '</option>';\n keysHtml += '</select>';\n keysHtml += '</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 // Refresh access keys list content\n async function refreshAccessKeysList(username) {\n try {\n const encodedUsername = encodeURIComponent(username);\n const response = await fetch(basePath(`/api/users/${encodedUsername}`));\n if (response.ok) {\n const user = await response.json();\n document.getElementById('accessKeysContent').innerHTML = createAccessKeysContent(user);\n }\n } catch (error) {\n console.error('Error refreshing access keys:', error);\n }\n }\n\n // Update access key status\n async function updateAccessKeyStatus(username, accessKey, status) {\n try {\n const response = await fetch(basePath(`/api/users/${encodeURIComponent(username)}/access-keys/${encodeURIComponent(accessKey)}/status`), {\n method: 'PUT',\n headers: {\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify({ status: status })\n });\n\n if (response.ok) {\n showSuccessMessage('Access key status updated successfully');\n // Refresh access keys display without toggling modal\n refreshAccessKeysList(username);\n } else {\n const error = await response.json();\n showAlert('Failed to update access key status: ' + (error.error || 'Unknown error'), 'error');\n refreshAccessKeysList(username);\n }\n } catch (error) {\n console.error('Error updating access key status:', error);\n showAlert('Failed to update access key status: ' + error.message, 'error');\n refreshAccessKeysList(username);\n }\n }\n\n // Reset and hide the create key form\n function resetCreateKeyForm() {\n document.getElementById('createKeyForm').style.display = 'none';\n document.getElementById('newAccessKeyInput').value = '';\n document.getElementById('newSecretKeyInput').value = '';\n document.getElementById('newSecretKeyInput').type = 'password';\n document.getElementById('secretKeyToggleIcon').className = 'fas fa-eye';\n }\n\n // Toggle create key form visibility\n function toggleCreateKeyForm() {\n const form = document.getElementById('createKeyForm');\n if (form.style.display === 'none') {\n form.style.display = 'block';\n } else {\n resetCreateKeyForm();\n }\n }\n\n // Toggle secret key input visibility\n function toggleSecretKeyVisibility() {\n const input = document.getElementById('newSecretKeyInput');\n const icon = document.getElementById('secretKeyToggleIcon');\n if (input.type === 'password') {\n input.type = 'text';\n icon.className = 'fas fa-eye-slash';\n } else {\n input.type = 'password';\n icon.className = 'fas fa-eye';\n }\n }\n\n // Reset form when modal is dismissed\n document.getElementById('accessKeysModal').addEventListener('hidden.bs.modal', resetCreateKeyForm);\n\n // Create new access key\n var isCreatingKey = false;\n async function createAccessKey() {\n if (isCreatingKey) return;\n\n const username = document.getElementById('accessKeysUsername').textContent;\n const accessKeyInput = document.getElementById('newAccessKeyInput');\n const secretKeyInput = document.getElementById('newSecretKeyInput');\n if ((accessKeyInput.value.trim() && !accessKeyInput.reportValidity()) ||\n (secretKeyInput.value.trim() && !secretKeyInput.reportValidity())) {\n return;\n }\n const accessKey = accessKeyInput.value.trim();\n const secretKey = secretKeyInput.value.trim();\n\n const body = {};\n if (accessKey) body.access_key = accessKey;\n if (secretKey) body.secret_key = secretKey;\n\n isCreatingKey = true;\n const createBtn = document.querySelector('#createKeyForm .btn-primary');\n const cancelBtn = document.querySelector('#createKeyForm .btn-secondary');\n if (createBtn) createBtn.disabled = true;\n if (cancelBtn) cancelBtn.disabled = true;\n\n try {\n const encodedUsername = encodeURIComponent(username);\n const response = await fetch(basePath(`/api/users/${encodedUsername}/access-keys`), {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify(body)\n });\n\n if (response.ok) {\n const result = await response.json();\n\n // Show the new access key details\n if (result.access_key) {\n showNewAccessKeyModal(result.access_key);\n }\n\n showSuccessMessage('Access key created successfully');\n resetCreateKeyForm();\n\n // Refresh access keys display\n refreshAccessKeysList(username);\n } else {\n const error = await response.json();\n showAlert('Failed to create access key: ' + (error.error || 'Unknown error'), 'error');\n }\n } catch (error) {\n console.error('Error creating access key:', error);\n showAlert('Failed to create access key: ' + error.message, 'error');\n } finally {\n isCreatingKey = false;\n if (createBtn) createBtn.disabled = false;\n if (cancelBtn) cancelBtn.disabled = false;\n }\n }\n\n // Delete access key\n async function deleteAccessKey(username, accessKey) {\n showDeleteConfirm(accessKey, async function() {\n try {\n const encodedUsername = encodeURIComponent(username);\n const encodedAccessKey = encodeURIComponent(accessKey);\n const response = await fetch(basePath(`/api/users/${encodedUsername}/access-keys/${encodedAccessKey}`), {\n method: 'DELETE'\n });\n\n if (response.ok) {\n showSuccessMessage('Access key deleted successfully');\n\n // Refresh access keys display\n refreshAccessKeysList(username);\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 }, 'Are you sure you want to delete this access key?');\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 showAlert(message, 'error');\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}diff --git a/weed/admin/view/app/policies.templ b/weed/admin/view/app/policies.templindex 8dbc282460..6d7ade5dab 100644--- a/weed/admin/view/app/policies.templ+++ b/weed/admin/view/app/policies.templ@@ -368,7 +368,7 @@ templ Policies(data dash.PoliciesData) {document: policyDocument};- fetch('/api/object-store/policies', {+ fetch(basePath('/api/object-store/policies'), {method: 'POST',headers: {'Content-Type': 'application/json',@@ -408,7 +408,7 @@ templ Policies(data dash.PoliciesData) {`;// Fetch policy data- fetch('/api/object-store/policies/' + encodeURIComponent(policyName))+ fetch(basePath('/api/object-store/policies/' + encodeURIComponent(policyName))).then(response => {if (!response.ok) {throw new Error('Policy not found');@@ -494,7 +494,7 @@ templ Policies(data dash.PoliciesData) {document.getElementById('editPolicyDocument').value = 'Loading...';// Fetch policy data- fetch('/api/object-store/policies/' + encodeURIComponent(policyName))+ fetch(basePath('/api/object-store/policies/' + encodeURIComponent(policyName))).then(response => {if (!response.ok) {throw new Error('Policy not found');@@ -534,7 +534,7 @@ templ Policies(data dash.PoliciesData) {document: policyDocument};- fetch('/api/object-store/policies/' + encodeURIComponent(policyName), {+ fetch(basePath('/api/object-store/policies/' + encodeURIComponent(policyName)), {method: 'PUT',headers: {'Content-Type': 'application/json',@@ -636,7 +636,7 @@ templ Policies(data dash.PoliciesData) {function deletePolicy(policyName) {showDeleteConfirm(policyName, function() {- fetch('/api/object-store/policies/' + encodeURIComponent(policyName), {+ fetch(basePath('/api/object-store/policies/' + encodeURIComponent(policyName)), {method: 'DELETE'}).then(response => response.json())diff --git a/weed/admin/view/app/policies_templ.go b/weed/admin/view/app/policies_templ.goindex 5f016e7468..abee882abb 100644--- a/weed/admin/view/app/policies_templ.go+++ b/weed/admin/view/app/policies_templ.go@@ -1,6 +1,6 @@// Code generated by templ - DO NOT EDIT.-// templ: version: v0.3.977+// templ: version: v0.3.1001package app//lint:file-ignore SA4006 This context is only used if a nested component is present.@@ -41,7 +41,7 @@ func Policies(data dash.PoliciesData) templ.Component {var templ_7745c5c3_Var2 stringtempl_7745c5c3_Var2, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%d", data.TotalPolicies))if templ_7745c5c3_Err != nil {- return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/policies.templ`, Line: 34, Col: 74}+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/policies.templ`, Line: 34, Col: 74}}_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var2))if templ_7745c5c3_Err != nil {@@ -54,7 +54,7 @@ func Policies(data dash.PoliciesData) templ.Component {var templ_7745c5c3_Var3 stringtempl_7745c5c3_Var3, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%d", data.TotalPolicies))if templ_7745c5c3_Err != nil {- return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/policies.templ`, Line: 54, Col: 74}+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/policies.templ`, Line: 54, Col: 74}}_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var3))if templ_7745c5c3_Err != nil {@@ -67,7 +67,7 @@ func Policies(data dash.PoliciesData) templ.Component {var templ_7745c5c3_Var4 stringtempl_7745c5c3_Var4, templ_7745c5c3_Err = templ.JoinStringErrs(data.LastUpdated.Format("15:04"))if templ_7745c5c3_Err != nil {- return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/policies.templ`, Line: 74, Col: 69}+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/policies.templ`, Line: 74, Col: 69}}_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var4))if templ_7745c5c3_Err != nil {@@ -85,7 +85,7 @@ func Policies(data dash.PoliciesData) templ.Component {var templ_7745c5c3_Var5 stringtempl_7745c5c3_Var5, templ_7745c5c3_Err = templ.JoinStringErrs(policy.Name)if templ_7745c5c3_Err != nil {- return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/policies.templ`, Line: 123, Col: 68}+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/policies.templ`, Line: 123, Col: 68}}_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var5))if templ_7745c5c3_Err != nil {@@ -98,7 +98,7 @@ func Policies(data dash.PoliciesData) templ.Component {var templ_7745c5c3_Var6 stringtempl_7745c5c3_Var6, templ_7745c5c3_Err = templ.JoinStringErrs(policy.Document.Version)if templ_7745c5c3_Err != nil {- return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/policies.templ`, Line: 126, Col: 100}+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/policies.templ`, Line: 126, Col: 100}}_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var6))if templ_7745c5c3_Err != nil {@@ -111,7 +111,7 @@ func Policies(data dash.PoliciesData) templ.Component {var templ_7745c5c3_Var7 stringtempl_7745c5c3_Var7, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%d statements", len(policy.Document.Statement)))if templ_7745c5c3_Err != nil {- return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/policies.templ`, Line: 129, Col: 142}+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/policies.templ`, Line: 129, Col: 142}}_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var7))if templ_7745c5c3_Err != nil {@@ -124,7 +124,7 @@ func Policies(data dash.PoliciesData) templ.Component {var templ_7745c5c3_Var8 stringtempl_7745c5c3_Var8, templ_7745c5c3_Err = templ.JoinStringErrs(policy.CreatedAt.Format("2006-01-02 15:04"))if templ_7745c5c3_Err != nil {- return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/policies.templ`, Line: 132, Col: 118}+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/policies.templ`, Line: 132, Col: 118}}_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var8))if templ_7745c5c3_Err != nil {@@ -137,7 +137,7 @@ func Policies(data dash.PoliciesData) templ.Component {var templ_7745c5c3_Var9 stringtempl_7745c5c3_Var9, templ_7745c5c3_Err = templ.JoinStringErrs(policy.UpdatedAt.Format("2006-01-02 15:04"))if templ_7745c5c3_Err != nil {- return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/policies.templ`, Line: 135, Col: 118}+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/policies.templ`, Line: 135, Col: 118}}_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var9))if templ_7745c5c3_Err != nil {@@ -150,7 +150,7 @@ func Policies(data dash.PoliciesData) templ.Component {var templ_7745c5c3_Var10 stringtempl_7745c5c3_Var10, templ_7745c5c3_Err = templ.JoinStringErrs(policy.Name)if templ_7745c5c3_Err != nil {- return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/policies.templ`, Line: 139, Col: 168}+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/policies.templ`, Line: 139, Col: 168}}_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var10))if templ_7745c5c3_Err != nil {@@ -163,7 +163,7 @@ func Policies(data dash.PoliciesData) templ.Component {var templ_7745c5c3_Var11 stringtempl_7745c5c3_Var11, templ_7745c5c3_Err = templ.JoinStringErrs(policy.Name)if templ_7745c5c3_Err != nil {- return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/policies.templ`, Line: 142, Col: 171}+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/policies.templ`, Line: 142, Col: 171}}_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var11))if templ_7745c5c3_Err != nil {@@ -176,7 +176,7 @@ func Policies(data dash.PoliciesData) templ.Component {var templ_7745c5c3_Var12 stringtempl_7745c5c3_Var12, templ_7745c5c3_Err = templ.JoinStringErrs(policy.Name)if templ_7745c5c3_Err != nil {- return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/policies.templ`, Line: 145, Col: 174}+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/policies.templ`, Line: 145, Col: 174}}_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var12))if templ_7745c5c3_Err != nil {@@ -193,7 +193,7 @@ func Policies(data dash.PoliciesData) templ.Component {return templ_7745c5c3_Err}}- templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 15, "</tbody></table></div></div></div></div></div></div><!-- Create Policy Modal --><div class=\"modal fade\" id=\"createPolicyModal\" tabindex=\"-1\" aria-labelledby=\"createPolicyModalLabel\" aria-hidden=\"true\"><div class=\"modal-dialog modal-lg\"><div class=\"modal-content\"><div class=\"modal-header\"><h5 class=\"modal-title\" id=\"createPolicyModalLabel\"><i class=\"fas fa-shield-alt me-2\"></i>Create IAM Policy</h5><button type=\"button\" class=\"btn-close\" data-bs-dismiss=\"modal\" aria-label=\"Close\"></button></div><div class=\"modal-body\"><form id=\"createPolicyForm\"><div class=\"mb-3\"><label for=\"policyName\" class=\"form-label\">Policy Name</label> <input type=\"text\" class=\"form-control\" id=\"policyName\" name=\"name\" required placeholder=\"e.g., S3ReadOnlyPolicy\"><div class=\"form-text\">Enter a unique name for this policy (alphanumeric and underscores only)</div></div><div class=\"mb-3\"><label for=\"policyDocument\" class=\"form-label\">Policy Document</label> <textarea class=\"form-control\" id=\"policyDocument\" name=\"document\" rows=\"15\" required placeholder=\"Enter IAM policy JSON document...\"></textarea><div class=\"form-text\">Enter the policy document in AWS IAM JSON format</div></div><div class=\"mb-3\"><div class=\"row\"><div class=\"col-md-6\"><button type=\"button\" class=\"btn btn-outline-info btn-sm\" onclick=\"insertSamplePolicy()\"><i class=\"fas fa-file-alt me-1\"></i>Use Sample Policy</button></div><div class=\"col-md-6 text-end\"><button type=\"button\" class=\"btn btn-outline-secondary btn-sm\" onclick=\"validatePolicyDocument()\"><i class=\"fas fa-check me-1\"></i>Validate JSON</button></div></div></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=\"createPolicy()\"><i class=\"fas fa-plus me-1\"></i>Create Policy</button></div></div></div></div><!-- View Policy Modal --><div class=\"modal fade\" id=\"viewPolicyModal\" tabindex=\"-1\" aria-labelledby=\"viewPolicyModalLabel\" aria-hidden=\"true\"><div class=\"modal-dialog modal-lg\"><div class=\"modal-content\"><div class=\"modal-header\"><h5 class=\"modal-title\" id=\"viewPolicyModalLabel\"><i class=\"fas fa-eye me-2\"></i>View IAM Policy</h5><button type=\"button\" class=\"btn-close\" data-bs-dismiss=\"modal\" aria-label=\"Close\"></button></div><div class=\"modal-body\"><div id=\"viewPolicyContent\"><div class=\"text-center\"><div class=\"spinner-border\" role=\"status\"><span class=\"visually-hidden\">Loading...</span></div><p class=\"mt-2\">Loading policy...</p></div></div></div><div class=\"modal-footer\"><button type=\"button\" class=\"btn btn-secondary\" data-bs-dismiss=\"modal\">Close</button> <button type=\"button\" class=\"btn btn-primary\" id=\"editFromViewBtn\"><i class=\"fas fa-edit me-1\"></i>Edit Policy</button></div></div></div></div><!-- Edit Policy Modal --><div class=\"modal fade\" id=\"editPolicyModal\" tabindex=\"-1\" aria-labelledby=\"editPolicyModalLabel\" aria-hidden=\"true\"><div class=\"modal-dialog modal-lg\"><div class=\"modal-content\"><div class=\"modal-header\"><h5 class=\"modal-title\" id=\"editPolicyModalLabel\"><i class=\"fas fa-edit me-2\"></i>Edit IAM Policy</h5><button type=\"button\" class=\"btn-close\" data-bs-dismiss=\"modal\" aria-label=\"Close\"></button></div><div class=\"modal-body\"><form id=\"editPolicyForm\"><div class=\"mb-3\"><label for=\"editPolicyName\" class=\"form-label\">Policy Name</label> <input type=\"text\" class=\"form-control\" id=\"editPolicyName\" name=\"name\" readonly><div class=\"form-text\">Policy name cannot be changed</div></div><div class=\"mb-3\"><label for=\"editPolicyDocument\" class=\"form-label\">Policy Document</label> <textarea class=\"form-control\" id=\"editPolicyDocument\" name=\"document\" rows=\"15\" required></textarea><div class=\"form-text\">Edit the policy document in AWS IAM JSON format</div></div><div class=\"mb-3\"><div class=\"row\"><div class=\"col-md-6\"><button type=\"button\" class=\"btn btn-outline-info btn-sm\" onclick=\"insertSamplePolicyEdit()\"><i class=\"fas fa-file-alt me-1\"></i>Reset to Sample</button></div><div class=\"col-md-6 text-end\"><button type=\"button\" class=\"btn btn-outline-secondary btn-sm\" onclick=\"validateEditPolicyDocument()\"><i class=\"fas fa-check me-1\"></i>Validate JSON</button></div></div></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=\"updatePolicy()\"><i class=\"fas fa-save me-1\"></i>Save Changes</button></div></div></div></div><!-- JavaScript for Policy Management --><script>\n // Current policy being viewed/edited\n let currentPolicy = null;\n \n // Event listeners for policy actions\n document.addEventListener('DOMContentLoaded', function() {\n // View policy buttons\n document.querySelectorAll('.view-policy-btn').forEach(button => {\n button.addEventListener('click', function() {\n const policyName = this.getAttribute('data-policy-name');\n viewPolicy(policyName);\n });\n });\n \n // Edit policy buttons\n document.querySelectorAll('.edit-policy-btn').forEach(button => {\n button.addEventListener('click', function() {\n const policyName = this.getAttribute('data-policy-name');\n editPolicy(policyName);\n });\n });\n \n // Delete policy buttons\n document.querySelectorAll('.delete-policy-btn').forEach(button => {\n button.addEventListener('click', function() {\n const policyName = this.getAttribute('data-policy-name');\n deletePolicy(policyName);\n });\n });\n \n // Edit from view button\n document.getElementById('editFromViewBtn').addEventListener('click', function() {\n if (currentPolicy) {\n const viewModal = bootstrap.Modal.getInstance(document.getElementById('viewPolicyModal'));\n if (viewModal) viewModal.hide();\n editPolicy(currentPolicy.name);\n }\n });\n });\n \n function createPolicy() {\n const form = document.getElementById('createPolicyForm');\n const formData = new FormData(form);\n \n const policyName = formData.get('name');\n const policyDocumentText = formData.get('document');\n \n if (!policyName || !policyDocumentText) {\n showAlert('Please fill in all required fields', 'warning');\n return;\n }\n \n let policyDocument;\n try {\n policyDocument = JSON.parse(policyDocumentText);\n } catch (e) {\n showAlert('Invalid JSON in policy document: ' + e.message, 'error');\n return;\n }\n \n const requestData = {\n name: policyName,\n document: policyDocument\n };\n \n fetch('/api/object-store/policies', {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify(requestData)\n })\n .then(response => response.json())\n .then(data => {\n if (data.success) {\n showAlert('Policy created successfully!', 'success');\n const modal = bootstrap.Modal.getInstance(document.getElementById('createPolicyModal'));\n if (modal) modal.hide();\n location.reload(); // Refresh the page to show the new policy\n } else {\n showAlert('Error creating policy: ' + (data.error || 'Unknown error'), 'error');\n }\n })\n .catch(error => {\n console.error('Error:', error);\n showAlert('Error creating policy: ' + error.message, 'error');\n });\n }\n \n function viewPolicy(policyName) {\n // Show the modal first\n const modal = new bootstrap.Modal(document.getElementById('viewPolicyModal'));\n modal.show();\n \n // Reset content to loading state\n document.getElementById('viewPolicyContent').innerHTML = `\n <div class=\"text-center\">\n <div class=\"spinner-border\" role=\"status\">\n <span class=\"visually-hidden\">Loading...</span>\n </div>\n <p class=\"mt-2\">Loading policy...</p>\n </div>\n `;\n \n // Fetch policy data\n fetch('/api/object-store/policies/' + encodeURIComponent(policyName))\n .then(response => {\n if (!response.ok) {\n throw new Error('Policy not found');\n }\n return response.json();\n })\n .then(policy => {\n currentPolicy = policy;\n displayPolicyDetails(policy);\n })\n .catch(error => {\n console.error('Error:', error);\n document.getElementById('viewPolicyContent').innerHTML = `\n <div class=\"alert alert-danger\" role=\"alert\">\n <i class=\"fas fa-exclamation-triangle me-2\"></i>\n Error loading policy: ${error.message}\n </div>\n `;\n });\n }\n \n function displayPolicyDetails(policy) {\n const content = document.getElementById('viewPolicyContent');\n \n let statementsHtml = '';\n if (policy.document && policy.document.Statement) {\n statementsHtml = policy.document.Statement.map((stmt, index) => `\n <div class=\"card mb-2\">\n <div class=\"card-header py-2\">\n <h6 class=\"mb-0\">Statement ${index + 1}</h6>\n </div>\n <div class=\"card-body py-2\">\n <div class=\"row\">\n <div class=\"col-md-6\">\n <strong>Effect:</strong> \n <span class=\"badge ${stmt.Effect === 'Allow' ? 'bg-success' : 'bg-danger'}\">${stmt.Effect}</span>\n </div>\n <div class=\"col-md-6\">\n <strong>Actions:</strong> ${Array.isArray(stmt.Action) ? stmt.Action.join(', ') : stmt.Action}\n </div>\n </div>\n <div class=\"row mt-2\">\n <div class=\"col-12\">\n <strong>Resources:</strong> ${Array.isArray(stmt.Resource) ? stmt.Resource.join(', ') : stmt.Resource}\n </div>\n </div>\n </div>\n </div>\n `).join('');\n }\n \n content.innerHTML = `\n <div class=\"row mb-3\">\n <div class=\"col-md-6\">\n <strong>Policy Name:</strong> ${policy.name || 'Unknown'}\n </div>\n <div class=\"col-md-6\">\n <strong>Version:</strong> <span class=\"badge bg-info\">${policy.document?.Version || 'Unknown'}</span>\n </div>\n </div>\n \n <div class=\"mb-3\">\n <strong>Statements:</strong>\n <div class=\"mt-2\">\n ${statementsHtml || '<p class=\"text-muted\">No statements found</p>'}\n </div>\n </div>\n \n <div class=\"mb-3\">\n <strong>Raw Policy Document:</strong>\n <pre class=\"bg-light p-3 border rounded mt-2\"><code>${JSON.stringify(policy.document, null, 2)}</code></pre>\n </div>\n `;\n }\n \n function editPolicy(policyName) {\n // Show the modal first\n const modal = new bootstrap.Modal(document.getElementById('editPolicyModal'));\n modal.show();\n \n // Set policy name\n document.getElementById('editPolicyName').value = policyName;\n document.getElementById('editPolicyDocument').value = 'Loading...';\n \n // Fetch policy data\n fetch('/api/object-store/policies/' + encodeURIComponent(policyName))\n .then(response => {\n if (!response.ok) {\n throw new Error('Policy not found');\n }\n return response.json();\n })\n .then(policy => {\n currentPolicy = policy;\n document.getElementById('editPolicyDocument').value = JSON.stringify(policy.document, null, 2);\n })\n .catch(error => {\n console.error('Error:', error);\n showAlert('Error loading policy for editing: ' + error.message, 'error');\n const editModal = bootstrap.Modal.getInstance(document.getElementById('editPolicyModal'));\n if (editModal) editModal.hide();\n });\n }\n \n function updatePolicy() {\n const policyName = document.getElementById('editPolicyName').value;\n const policyDocumentText = document.getElementById('editPolicyDocument').value;\n \n if (!policyName || !policyDocumentText) {\n showAlert('Please fill in all required fields', 'warning');\n return;\n }\n \n let policyDocument;\n try {\n policyDocument = JSON.parse(policyDocumentText);\n } catch (e) {\n showAlert('Invalid JSON in policy document: ' + e.message, 'error');\n return;\n }\n \n const requestData = {\n document: policyDocument\n };\n \n fetch('/api/object-store/policies/' + encodeURIComponent(policyName), {\n method: 'PUT',\n headers: {\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify(requestData)\n })\n .then(response => response.json())\n .then(data => {\n if (data.success) {\n showAlert('Policy updated successfully!', 'success');\n const modal = bootstrap.Modal.getInstance(document.getElementById('editPolicyModal'));\n if (modal) modal.hide();\n location.reload(); // Refresh the page to show the updated policy\n } else {\n showAlert('Error updating policy: ' + (data.error || 'Unknown error'), 'error');\n }\n })\n .catch(error => {\n console.error('Error:', error);\n showAlert('Error updating policy: ' + error.message, 'error');\n });\n }\n \n function insertSamplePolicy() {\n const samplePolicy = {\n \"Version\": \"2012-10-17\",\n \"Statement\": [\n {\n \"Effect\": \"Allow\",\n \"Action\": [\n \"s3:GetObject\",\n \"s3:PutObject\"\n ],\n \"Resource\": [\n \"arn:aws:s3:::my-bucket/*\"\n ]\n }\n ]\n };\n \n document.getElementById('policyDocument').value = JSON.stringify(samplePolicy, null, 2);\n }\n \n function insertSamplePolicyEdit() {\n const samplePolicy = {\n \"Version\": \"2012-10-17\",\n \"Statement\": [\n {\n \"Effect\": \"Allow\",\n \"Action\": [\n \"s3:GetObject\",\n \"s3:PutObject\"\n ],\n \"Resource\": [\n \"arn:aws:s3:::my-bucket/*\"\n ]\n }\n ]\n };\n \n document.getElementById('editPolicyDocument').value = JSON.stringify(samplePolicy, null, 2);\n }\n \n function validatePolicyDocument() {\n const policyText = document.getElementById('policyDocument').value;\n validatePolicyJSON(policyText);\n }\n \n function validateEditPolicyDocument() {\n const policyText = document.getElementById('editPolicyDocument').value;\n validatePolicyJSON(policyText);\n }\n \n function validatePolicyJSON(policyText) {\n if (!policyText) {\n showAlert('Please enter a policy document first', 'warning');\n return;\n }\n \n try {\n const policy = JSON.parse(policyText);\n \n // Basic validation\n if (!policy.Version) {\n showAlert('Policy must have a Version field', 'error');\n return;\n }\n \n if (!policy.Statement || !Array.isArray(policy.Statement)) {\n showAlert('Policy must have a Statement array', 'error');\n return;\n }\n \n showAlert('Policy document is valid JSON!', 'success');\n } catch (e) {\n showAlert('Invalid JSON: ' + e.message, 'error');\n }\n }\n \n function deletePolicy(policyName) {\n showDeleteConfirm(policyName, function() {\n fetch('/api/object-store/policies/' + encodeURIComponent(policyName), {\n method: 'DELETE'\n })\n .then(response => response.json())\n .then(data => {\n if (data.success) {\n showAlert('Policy deleted successfully!', 'success');\n location.reload();\n } else {\n showAlert('Error deleting policy: ' + (data.error || 'Unknown error'), 'error');\n }\n })\n .catch(error => {\n console.error('Error:', error);\n showAlert('Error deleting policy: ' + error.message, 'error');\n });\n });\n }\n </script>")+ templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 15, "</tbody></table></div></div></div></div></div></div><!-- Create Policy Modal --><div class=\"modal fade\" id=\"createPolicyModal\" tabindex=\"-1\" aria-labelledby=\"createPolicyModalLabel\" aria-hidden=\"true\"><div class=\"modal-dialog modal-lg\"><div class=\"modal-content\"><div class=\"modal-header\"><h5 class=\"modal-title\" id=\"createPolicyModalLabel\"><i class=\"fas fa-shield-alt me-2\"></i>Create IAM Policy</h5><button type=\"button\" class=\"btn-close\" data-bs-dismiss=\"modal\" aria-label=\"Close\"></button></div><div class=\"modal-body\"><form id=\"createPolicyForm\"><div class=\"mb-3\"><label for=\"policyName\" class=\"form-label\">Policy Name</label> <input type=\"text\" class=\"form-control\" id=\"policyName\" name=\"name\" required placeholder=\"e.g., S3ReadOnlyPolicy\"><div class=\"form-text\">Enter a unique name for this policy (alphanumeric and underscores only)</div></div><div class=\"mb-3\"><label for=\"policyDocument\" class=\"form-label\">Policy Document</label> <textarea class=\"form-control\" id=\"policyDocument\" name=\"document\" rows=\"15\" required placeholder=\"Enter IAM policy JSON document...\"></textarea><div class=\"form-text\">Enter the policy document in AWS IAM JSON format</div></div><div class=\"mb-3\"><div class=\"row\"><div class=\"col-md-6\"><button type=\"button\" class=\"btn btn-outline-info btn-sm\" onclick=\"insertSamplePolicy()\"><i class=\"fas fa-file-alt me-1\"></i>Use Sample Policy</button></div><div class=\"col-md-6 text-end\"><button type=\"button\" class=\"btn btn-outline-secondary btn-sm\" onclick=\"validatePolicyDocument()\"><i class=\"fas fa-check me-1\"></i>Validate JSON</button></div></div></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=\"createPolicy()\"><i class=\"fas fa-plus me-1\"></i>Create Policy</button></div></div></div></div><!-- View Policy Modal --><div class=\"modal fade\" id=\"viewPolicyModal\" tabindex=\"-1\" aria-labelledby=\"viewPolicyModalLabel\" aria-hidden=\"true\"><div class=\"modal-dialog modal-lg\"><div class=\"modal-content\"><div class=\"modal-header\"><h5 class=\"modal-title\" id=\"viewPolicyModalLabel\"><i class=\"fas fa-eye me-2\"></i>View IAM Policy</h5><button type=\"button\" class=\"btn-close\" data-bs-dismiss=\"modal\" aria-label=\"Close\"></button></div><div class=\"modal-body\"><div id=\"viewPolicyContent\"><div class=\"text-center\"><div class=\"spinner-border\" role=\"status\"><span class=\"visually-hidden\">Loading...</span></div><p class=\"mt-2\">Loading policy...</p></div></div></div><div class=\"modal-footer\"><button type=\"button\" class=\"btn btn-secondary\" data-bs-dismiss=\"modal\">Close</button> <button type=\"button\" class=\"btn btn-primary\" id=\"editFromViewBtn\"><i class=\"fas fa-edit me-1\"></i>Edit Policy</button></div></div></div></div><!-- Edit Policy Modal --><div class=\"modal fade\" id=\"editPolicyModal\" tabindex=\"-1\" aria-labelledby=\"editPolicyModalLabel\" aria-hidden=\"true\"><div class=\"modal-dialog modal-lg\"><div class=\"modal-content\"><div class=\"modal-header\"><h5 class=\"modal-title\" id=\"editPolicyModalLabel\"><i class=\"fas fa-edit me-2\"></i>Edit IAM Policy</h5><button type=\"button\" class=\"btn-close\" data-bs-dismiss=\"modal\" aria-label=\"Close\"></button></div><div class=\"modal-body\"><form id=\"editPolicyForm\"><div class=\"mb-3\"><label for=\"editPolicyName\" class=\"form-label\">Policy Name</label> <input type=\"text\" class=\"form-control\" id=\"editPolicyName\" name=\"name\" readonly><div class=\"form-text\">Policy name cannot be changed</div></div><div class=\"mb-3\"><label for=\"editPolicyDocument\" class=\"form-label\">Policy Document</label> <textarea class=\"form-control\" id=\"editPolicyDocument\" name=\"document\" rows=\"15\" required></textarea><div class=\"form-text\">Edit the policy document in AWS IAM JSON format</div></div><div class=\"mb-3\"><div class=\"row\"><div class=\"col-md-6\"><button type=\"button\" class=\"btn btn-outline-info btn-sm\" onclick=\"insertSamplePolicyEdit()\"><i class=\"fas fa-file-alt me-1\"></i>Reset to Sample</button></div><div class=\"col-md-6 text-end\"><button type=\"button\" class=\"btn btn-outline-secondary btn-sm\" onclick=\"validateEditPolicyDocument()\"><i class=\"fas fa-check me-1\"></i>Validate JSON</button></div></div></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=\"updatePolicy()\"><i class=\"fas fa-save me-1\"></i>Save Changes</button></div></div></div></div><!-- JavaScript for Policy Management --><script>\n // Current policy being viewed/edited\n let currentPolicy = null;\n \n // Event listeners for policy actions\n document.addEventListener('DOMContentLoaded', function() {\n // View policy buttons\n document.querySelectorAll('.view-policy-btn').forEach(button => {\n button.addEventListener('click', function() {\n const policyName = this.getAttribute('data-policy-name');\n viewPolicy(policyName);\n });\n });\n \n // Edit policy buttons\n document.querySelectorAll('.edit-policy-btn').forEach(button => {\n button.addEventListener('click', function() {\n const policyName = this.getAttribute('data-policy-name');\n editPolicy(policyName);\n });\n });\n \n // Delete policy buttons\n document.querySelectorAll('.delete-policy-btn').forEach(button => {\n button.addEventListener('click', function() {\n const policyName = this.getAttribute('data-policy-name');\n deletePolicy(policyName);\n });\n });\n \n // Edit from view button\n document.getElementById('editFromViewBtn').addEventListener('click', function() {\n if (currentPolicy) {\n const viewModal = bootstrap.Modal.getInstance(document.getElementById('viewPolicyModal'));\n if (viewModal) viewModal.hide();\n editPolicy(currentPolicy.name);\n }\n });\n });\n \n function createPolicy() {\n const form = document.getElementById('createPolicyForm');\n const formData = new FormData(form);\n \n const policyName = formData.get('name');\n const policyDocumentText = formData.get('document');\n \n if (!policyName || !policyDocumentText) {\n showAlert('Please fill in all required fields', 'warning');\n return;\n }\n \n let policyDocument;\n try {\n policyDocument = JSON.parse(policyDocumentText);\n } catch (e) {\n showAlert('Invalid JSON in policy document: ' + e.message, 'error');\n return;\n }\n \n const requestData = {\n name: policyName,\n document: policyDocument\n };\n \n fetch(basePath('/api/object-store/policies'), {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify(requestData)\n })\n .then(response => response.json())\n .then(data => {\n if (data.success) {\n showAlert('Policy created successfully!', 'success');\n const modal = bootstrap.Modal.getInstance(document.getElementById('createPolicyModal'));\n if (modal) modal.hide();\n location.reload(); // Refresh the page to show the new policy\n } else {\n showAlert('Error creating policy: ' + (data.error || 'Unknown error'), 'error');\n }\n })\n .catch(error => {\n console.error('Error:', error);\n showAlert('Error creating policy: ' + error.message, 'error');\n });\n }\n \n function viewPolicy(policyName) {\n // Show the modal first\n const modal = new bootstrap.Modal(document.getElementById('viewPolicyModal'));\n modal.show();\n \n // Reset content to loading state\n document.getElementById('viewPolicyContent').innerHTML = `\n <div class=\"text-center\">\n <div class=\"spinner-border\" role=\"status\">\n <span class=\"visually-hidden\">Loading...</span>\n </div>\n <p class=\"mt-2\">Loading policy...</p>\n </div>\n `;\n \n // Fetch policy data\n fetch(basePath('/api/object-store/policies/' + encodeURIComponent(policyName)))\n .then(response => {\n if (!response.ok) {\n throw new Error('Policy not found');\n }\n return response.json();\n })\n .then(policy => {\n currentPolicy = policy;\n displayPolicyDetails(policy);\n })\n .catch(error => {\n console.error('Error:', error);\n document.getElementById('viewPolicyContent').innerHTML = `\n <div class=\"alert alert-danger\" role=\"alert\">\n <i class=\"fas fa-exclamation-triangle me-2\"></i>\n Error loading policy: ${error.message}\n </div>\n `;\n });\n }\n \n function displayPolicyDetails(policy) {\n const content = document.getElementById('viewPolicyContent');\n \n let statementsHtml = '';\n if (policy.document && policy.document.Statement) {\n statementsHtml = policy.document.Statement.map((stmt, index) => `\n <div class=\"card mb-2\">\n <div class=\"card-header py-2\">\n <h6 class=\"mb-0\">Statement ${index + 1}</h6>\n </div>\n <div class=\"card-body py-2\">\n <div class=\"row\">\n <div class=\"col-md-6\">\n <strong>Effect:</strong> \n <span class=\"badge ${stmt.Effect === 'Allow' ? 'bg-success' : 'bg-danger'}\">${stmt.Effect}</span>\n </div>\n <div class=\"col-md-6\">\n <strong>Actions:</strong> ${Array.isArray(stmt.Action) ? stmt.Action.join(', ') : stmt.Action}\n </div>\n </div>\n <div class=\"row mt-2\">\n <div class=\"col-12\">\n <strong>Resources:</strong> ${Array.isArray(stmt.Resource) ? stmt.Resource.join(', ') : stmt.Resource}\n </div>\n </div>\n </div>\n </div>\n `).join('');\n }\n \n content.innerHTML = `\n <div class=\"row mb-3\">\n <div class=\"col-md-6\">\n <strong>Policy Name:</strong> ${policy.name || 'Unknown'}\n </div>\n <div class=\"col-md-6\">\n <strong>Version:</strong> <span class=\"badge bg-info\">${policy.document?.Version || 'Unknown'}</span>\n </div>\n </div>\n \n <div class=\"mb-3\">\n <strong>Statements:</strong>\n <div class=\"mt-2\">\n ${statementsHtml || '<p class=\"text-muted\">No statements found</p>'}\n </div>\n </div>\n \n <div class=\"mb-3\">\n <strong>Raw Policy Document:</strong>\n <pre class=\"bg-light p-3 border rounded mt-2\"><code>${JSON.stringify(policy.document, null, 2)}</code></pre>\n </div>\n `;\n }\n \n function editPolicy(policyName) {\n // Show the modal first\n const modal = new bootstrap.Modal(document.getElementById('editPolicyModal'));\n modal.show();\n \n // Set policy name\n document.getElementById('editPolicyName').value = policyName;\n document.getElementById('editPolicyDocument').value = 'Loading...';\n \n // Fetch policy data\n fetch(basePath('/api/object-store/policies/' + encodeURIComponent(policyName)))\n .then(response => {\n if (!response.ok) {\n throw new Error('Policy not found');\n }\n return response.json();\n })\n .then(policy => {\n currentPolicy = policy;\n document.getElementById('editPolicyDocument').value = JSON.stringify(policy.document, null, 2);\n })\n .catch(error => {\n console.error('Error:', error);\n showAlert('Error loading policy for editing: ' + error.message, 'error');\n const editModal = bootstrap.Modal.getInstance(document.getElementById('editPolicyModal'));\n if (editModal) editModal.hide();\n });\n }\n \n function updatePolicy() {\n const policyName = document.getElementById('editPolicyName').value;\n const policyDocumentText = document.getElementById('editPolicyDocument').value;\n \n if (!policyName || !policyDocumentText) {\n showAlert('Please fill in all required fields', 'warning');\n return;\n }\n \n let policyDocument;\n try {\n policyDocument = JSON.parse(policyDocumentText);\n } catch (e) {\n showAlert('Invalid JSON in policy document: ' + e.message, 'error');\n return;\n }\n \n const requestData = {\n document: policyDocument\n };\n \n fetch(basePath('/api/object-store/policies/' + encodeURIComponent(policyName)), {\n method: 'PUT',\n headers: {\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify(requestData)\n })\n .then(response => response.json())\n .then(data => {\n if (data.success) {\n showAlert('Policy updated successfully!', 'success');\n const modal = bootstrap.Modal.getInstance(document.getElementById('editPolicyModal'));\n if (modal) modal.hide();\n location.reload(); // Refresh the page to show the updated policy\n } else {\n showAlert('Error updating policy: ' + (data.error || 'Unknown error'), 'error');\n }\n })\n .catch(error => {\n console.error('Error:', error);\n showAlert('Error updating policy: ' + error.message, 'error');\n });\n }\n \n function insertSamplePolicy() {\n const samplePolicy = {\n \"Version\": \"2012-10-17\",\n \"Statement\": [\n {\n \"Effect\": \"Allow\",\n \"Action\": [\n \"s3:GetObject\",\n \"s3:PutObject\"\n ],\n \"Resource\": [\n \"arn:aws:s3:::my-bucket/*\"\n ]\n }\n ]\n };\n \n document.getElementById('policyDocument').value = JSON.stringify(samplePolicy, null, 2);\n }\n \n function insertSamplePolicyEdit() {\n const samplePolicy = {\n \"Version\": \"2012-10-17\",\n \"Statement\": [\n {\n \"Effect\": \"Allow\",\n \"Action\": [\n \"s3:GetObject\",\n \"s3:PutObject\"\n ],\n \"Resource\": [\n \"arn:aws:s3:::my-bucket/*\"\n ]\n }\n ]\n };\n \n document.getElementById('editPolicyDocument').value = JSON.stringify(samplePolicy, null, 2);\n }\n \n function validatePolicyDocument() {\n const policyText = document.getElementById('policyDocument').value;\n validatePolicyJSON(policyText);\n }\n \n function validateEditPolicyDocument() {\n const policyText = document.getElementById('editPolicyDocument').value;\n validatePolicyJSON(policyText);\n }\n \n function validatePolicyJSON(policyText) {\n if (!policyText) {\n showAlert('Please enter a policy document first', 'warning');\n return;\n }\n \n try {\n const policy = JSON.parse(policyText);\n \n // Basic validation\n if (!policy.Version) {\n showAlert('Policy must have a Version field', 'error');\n return;\n }\n \n if (!policy.Statement || !Array.isArray(policy.Statement)) {\n showAlert('Policy must have a Statement array', 'error');\n return;\n }\n \n showAlert('Policy document is valid JSON!', 'success');\n } catch (e) {\n showAlert('Invalid JSON: ' + e.message, 'error');\n }\n }\n \n function deletePolicy(policyName) {\n showDeleteConfirm(policyName, function() {\n fetch(basePath('/api/object-store/policies/' + encodeURIComponent(policyName)), {\n method: 'DELETE'\n })\n .then(response => response.json())\n .then(data => {\n if (data.success) {\n showAlert('Policy deleted successfully!', 'success');\n location.reload();\n } else {\n showAlert('Error deleting policy: ' + (data.error || 'Unknown error'), 'error');\n }\n })\n .catch(error => {\n console.error('Error:', error);\n showAlert('Error deleting policy: ' + error.message, 'error');\n });\n });\n }\n </script>")if templ_7745c5c3_Err != nil {return templ_7745c5c3_Err}diff --git a/weed/admin/view/app/s3_buckets.templ b/weed/admin/view/app/s3_buckets.templindex b1e86572b1..e268f3be63 100644--- a/weed/admin/view/app/s3_buckets.templ+++ b/weed/admin/view/app/s3_buckets.templ@@ -712,7 +712,7 @@ templ S3Buckets(data dash.S3BucketsData) {// Only fetch if not already populatedif (ownerSelect.options.length <= 1) {try {- const response = await fetch('/api/users');+ const response = await fetch(basePath('/api/users'));const data = await response.json();const users = data.users || [];@@ -756,7 +756,7 @@ templ S3Buckets(data dash.S3BucketsData) {return;}- fetch('/api/s3/buckets', {+ fetch(basePath('/api/s3/buckets'), {method: 'POST',headers: {'Content-Type': 'application/json',@@ -846,7 +846,7 @@ templ S3Buckets(data dash.S3BucketsData) {quota_enabled: enabled};- fetch(`/api/s3/buckets/${bucketName}/quota`, {+ fetch(basePath(`/api/s3/buckets/${bucketName}/quota`), {method: 'PUT',headers: {'Content-Type': 'application/json',@@ -897,7 +897,7 @@ templ S3Buckets(data dash.S3BucketsData) {// Fetch users if not cachedtry {if (!cachedUsers) {- const response = await fetch('/api/users');+ const response = await fetch(basePath('/api/users'));const data = await response.json();cachedUsers = data.users || [];}@@ -941,7 +941,7 @@ templ S3Buckets(data dash.S3BucketsData) {const owner = document.getElementById('bucketOwnerSelect').value;const data = { owner: owner };- fetch(`/api/s3/buckets/${bucketName}/owner`, {+ fetch(basePath(`/api/s3/buckets/${bucketName}/owner`), {method: 'PUT',headers: {'Content-Type': 'application/json',@@ -988,7 +988,7 @@ templ S3Buckets(data dash.S3BucketsData) {detailsModalInstance.show();// Fetch bucket details- fetch('/api/s3/buckets/' + bucketName)+ fetch(basePath('/api/s3/buckets/' + bucketName)).then(response => response.json()).then(data => {if (data.error) {@@ -1017,7 +1017,7 @@ templ S3Buckets(data dash.S3BucketsData) {const bucketName = document.getElementById('deleteBucketModal').dataset.bucketName;if (!bucketName) return;- fetch(`/api/s3/buckets/${bucketName}`, {+ fetch(basePath(`/api/s3/buckets/${bucketName}`), {method: 'DELETE'}).then(response => response.json())@@ -1172,7 +1172,7 @@ function displayBucketDetails(data) {}// Fetch all buckets from the API (not just the current page)- fetch('/api/s3/buckets')+ fetch(basePath('/api/s3/buckets')).then(response => response.json()).then(data => {if (data.error) {diff --git a/weed/admin/view/app/s3_buckets_templ.go b/weed/admin/view/app/s3_buckets_templ.goindex ec739c9871..08b94e859e 100644--- a/weed/admin/view/app/s3_buckets_templ.go+++ b/weed/admin/view/app/s3_buckets_templ.go@@ -1,6 +1,6 @@// Code generated by templ - DO NOT EDIT.-// templ: version: v0.3.977+// templ: version: v0.3.1001package app//lint:file-ignore SA4006 This context is only used if a nested component is present.@@ -81,7 +81,7 @@ func S3Buckets(data dash.S3BucketsData) templ.Component {var templ_7745c5c3_Var2 stringtempl_7745c5c3_Var2, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%d", data.TotalBuckets))if templ_7745c5c3_Err != nil {- return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/s3_buckets.templ`, Line: 42, Col: 73}+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/s3_buckets.templ`, Line: 42, Col: 73}}_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var2))if templ_7745c5c3_Err != nil {@@ -94,7 +94,7 @@ func S3Buckets(data dash.S3BucketsData) templ.Component {var templ_7745c5c3_Var3 stringtempl_7745c5c3_Var3, templ_7745c5c3_Err = templ.JoinStringErrs(formatBytes(data.TotalSize))if templ_7745c5c3_Err != nil {- return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/s3_buckets.templ`, Line: 62, Col: 64}+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/s3_buckets.templ`, Line: 62, Col: 64}}_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var3))if templ_7745c5c3_Err != nil {@@ -107,7 +107,7 @@ func S3Buckets(data dash.S3BucketsData) templ.Component {var templ_7745c5c3_Var4 stringtempl_7745c5c3_Var4, templ_7745c5c3_Err = templ.JoinStringErrs(data.LastUpdated.Format("15:04:05"))if templ_7745c5c3_Err != nil {- return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/s3_buckets.templ`, Line: 83, Col: 72}+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/s3_buckets.templ`, Line: 83, Col: 72}}_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var4))if templ_7745c5c3_Err != nil {@@ -165,7 +165,7 @@ func S3Buckets(data dash.S3BucketsData) templ.Component {var templ_7745c5c3_Var5 templ.SafeURLtempl_7745c5c3_Var5, templ_7745c5c3_Err = templ.JoinURLErrs(dash.PUrl(ctx, fmt.Sprintf("/files?path=/buckets/%s", bucket.Name)))if templ_7745c5c3_Err != nil {- return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/s3_buckets.templ`, Line: 160, Col: 124}+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/s3_buckets.templ`, Line: 160, Col: 124}}_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var5))if templ_7745c5c3_Err != nil {@@ -178,7 +178,7 @@ func S3Buckets(data dash.S3BucketsData) templ.Component {var templ_7745c5c3_Var6 stringtempl_7745c5c3_Var6, templ_7745c5c3_Err = templ.JoinStringErrs(bucket.Name)if templ_7745c5c3_Err != nil {- return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/s3_buckets.templ`, Line: 163, Col: 64}+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/s3_buckets.templ`, Line: 163, Col: 64}}_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var6))if templ_7745c5c3_Err != nil {@@ -196,7 +196,7 @@ func S3Buckets(data dash.S3BucketsData) templ.Component {var templ_7745c5c3_Var7 stringtempl_7745c5c3_Var7, templ_7745c5c3_Err = templ.JoinStringErrs(bucket.Owner)if templ_7745c5c3_Err != nil {- return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/s3_buckets.templ`, Line: 169, Col: 101}+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/s3_buckets.templ`, Line: 169, Col: 101}}_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var7))if templ_7745c5c3_Err != nil {@@ -219,7 +219,7 @@ func S3Buckets(data dash.S3BucketsData) templ.Component {var templ_7745c5c3_Var8 stringtempl_7745c5c3_Var8, templ_7745c5c3_Err = templ.JoinStringErrs(bucket.CreatedAt.Format("2006-01-02 15:04"))if templ_7745c5c3_Err != nil {- return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/s3_buckets.templ`, Line: 175, Col: 92}+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/s3_buckets.templ`, Line: 175, Col: 92}}_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var8))if templ_7745c5c3_Err != nil {@@ -232,7 +232,7 @@ func S3Buckets(data dash.S3BucketsData) templ.Component {var templ_7745c5c3_Var9 stringtempl_7745c5c3_Var9, templ_7745c5c3_Err = templ.JoinStringErrs(formatBytes(bucket.LogicalSize))if templ_7745c5c3_Err != nil {- return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/s3_buckets.templ`, Line: 177, Col: 85}+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/s3_buckets.templ`, Line: 177, Col: 85}}_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var9))if templ_7745c5c3_Err != nil {@@ -250,7 +250,7 @@ func S3Buckets(data dash.S3BucketsData) templ.Component {var templ_7745c5c3_Var10 stringtempl_7745c5c3_Var10, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%.1fx overhead", float64(bucket.PhysicalSize)/float64(bucket.LogicalSize)))if templ_7745c5c3_Err != nil {- return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/s3_buckets.templ`, Line: 180, Col: 144}+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/s3_buckets.templ`, Line: 180, Col: 144}}_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var10))if templ_7745c5c3_Err != nil {@@ -268,7 +268,7 @@ func S3Buckets(data dash.S3BucketsData) templ.Component {var templ_7745c5c3_Var11 stringtempl_7745c5c3_Var11, templ_7745c5c3_Err = templ.JoinStringErrs(formatBytes(bucket.PhysicalSize))if templ_7745c5c3_Err != nil {- return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/s3_buckets.templ`, Line: 184, Col: 81}+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/s3_buckets.templ`, Line: 184, Col: 81}}_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var11))if templ_7745c5c3_Err != nil {@@ -295,7 +295,7 @@ func S3Buckets(data dash.S3BucketsData) templ.Component {var templ_7745c5c3_Var13 stringtempl_7745c5c3_Var13, templ_7745c5c3_Err = templ.JoinStringErrs(templ.CSSClasses(templ_7745c5c3_Var12).String())if templ_7745c5c3_Err != nil {- return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/s3_buckets.templ`, Line: 1, Col: 0}+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/s3_buckets.templ`, Line: 1, Col: 0}}_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var13))if templ_7745c5c3_Err != nil {@@ -308,7 +308,7 @@ func S3Buckets(data dash.S3BucketsData) templ.Component {var templ_7745c5c3_Var14 stringtempl_7745c5c3_Var14, templ_7745c5c3_Err = templ.JoinStringErrs(formatBytes(bucket.Quota))if templ_7745c5c3_Err != nil {- return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/s3_buckets.templ`, Line: 189, Col: 86}+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/s3_buckets.templ`, Line: 189, Col: 86}}_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var14))if templ_7745c5c3_Err != nil {@@ -326,7 +326,7 @@ func S3Buckets(data dash.S3BucketsData) templ.Component {var templ_7745c5c3_Var15 stringtempl_7745c5c3_Var15, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%.1f%% used", float64(bucket.LogicalSize)/float64(bucket.Quota)*100))if templ_7745c5c3_Err != nil {- return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/s3_buckets.templ`, Line: 193, Col: 146}+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/s3_buckets.templ`, Line: 193, Col: 146}}_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var15))if templ_7745c5c3_Err != nil {@@ -384,7 +384,7 @@ func S3Buckets(data dash.S3BucketsData) templ.Component {var templ_7745c5c3_Var16 stringtempl_7745c5c3_Var16, templ_7745c5c3_Err = templ.JoinStringErrs(bucket.ObjectLockMode)if templ_7745c5c3_Err != nil {- return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/s3_buckets.templ`, Line: 223, Col: 82}+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/s3_buckets.templ`, Line: 223, Col: 82}}_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var16))if templ_7745c5c3_Err != nil {@@ -397,7 +397,7 @@ func S3Buckets(data dash.S3BucketsData) templ.Component {var templ_7745c5c3_Var17 stringtempl_7745c5c3_Var17, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%d days", bucket.ObjectLockDuration))if templ_7745c5c3_Err != nil {- return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/s3_buckets.templ`, Line: 223, Col: 138}+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/s3_buckets.templ`, Line: 223, Col: 138}}_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var17))if templ_7745c5c3_Err != nil {@@ -420,7 +420,7 @@ func S3Buckets(data dash.S3BucketsData) templ.Component {var templ_7745c5c3_Var18 templ.SafeURLtempl_7745c5c3_Var18, templ_7745c5c3_Err = templ.JoinURLErrs(dash.PUrl(ctx, fmt.Sprintf("/files?path=/buckets/%s", bucket.Name)))if templ_7745c5c3_Err != nil {- return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/s3_buckets.templ`, Line: 232, Col: 128}+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/s3_buckets.templ`, Line: 232, Col: 128}}_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var18))if templ_7745c5c3_Err != nil {@@ -433,7 +433,7 @@ func S3Buckets(data dash.S3BucketsData) templ.Component {var templ_7745c5c3_Var19 stringtempl_7745c5c3_Var19, templ_7745c5c3_Err = templ.JoinStringErrs(bucket.Name)if templ_7745c5c3_Err != nil {- return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/s3_buckets.templ`, Line: 239, Col: 89}+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/s3_buckets.templ`, Line: 239, Col: 89}}_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var19))if templ_7745c5c3_Err != nil {@@ -446,7 +446,7 @@ func S3Buckets(data dash.S3BucketsData) templ.Component {var templ_7745c5c3_Var20 stringtempl_7745c5c3_Var20, templ_7745c5c3_Err = templ.JoinStringErrs(bucket.Name)if templ_7745c5c3_Err != nil {- return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/s3_buckets.templ`, Line: 245, Col: 89}+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/s3_buckets.templ`, Line: 245, Col: 89}}_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var20))if templ_7745c5c3_Err != nil {@@ -459,7 +459,7 @@ func S3Buckets(data dash.S3BucketsData) templ.Component {var templ_7745c5c3_Var21 stringtempl_7745c5c3_Var21, templ_7745c5c3_Err = templ.JoinStringErrs(bucket.Owner)if templ_7745c5c3_Err != nil {- return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/s3_buckets.templ`, Line: 246, Col: 92}+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/s3_buckets.templ`, Line: 246, Col: 92}}_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var21))if templ_7745c5c3_Err != nil {@@ -472,7 +472,7 @@ func S3Buckets(data dash.S3BucketsData) templ.Component {var templ_7745c5c3_Var22 stringtempl_7745c5c3_Var22, templ_7745c5c3_Err = templ.JoinStringErrs(bucket.Name)if templ_7745c5c3_Err != nil {- return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/s3_buckets.templ`, Line: 252, Col: 89}+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/s3_buckets.templ`, Line: 252, Col: 89}}_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var22))if templ_7745c5c3_Err != nil {@@ -485,7 +485,7 @@ func S3Buckets(data dash.S3BucketsData) templ.Component {var templ_7745c5c3_Var23 stringtempl_7745c5c3_Var23, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%d", getQuotaInMB(bucket.Quota)))if templ_7745c5c3_Err != nil {- return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/s3_buckets.templ`, Line: 253, Col: 125}+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/s3_buckets.templ`, Line: 253, Col: 125}}_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var23))if templ_7745c5c3_Err != nil {@@ -498,7 +498,7 @@ func S3Buckets(data dash.S3BucketsData) templ.Component {var templ_7745c5c3_Var24 stringtempl_7745c5c3_Var24, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%t", bucket.QuotaEnabled))if templ_7745c5c3_Err != nil {- return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/s3_buckets.templ`, Line: 254, Col: 118}+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/s3_buckets.templ`, Line: 254, Col: 118}}_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var24))if templ_7745c5c3_Err != nil {@@ -511,7 +511,7 @@ func S3Buckets(data dash.S3BucketsData) templ.Component {var templ_7745c5c3_Var25 stringtempl_7745c5c3_Var25, templ_7745c5c3_Err = templ.JoinStringErrs(bucket.Name)if templ_7745c5c3_Err != nil {- return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/s3_buckets.templ`, Line: 260, Col: 89}+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/s3_buckets.templ`, Line: 260, Col: 89}}_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var25))if templ_7745c5c3_Err != nil {@@ -540,7 +540,7 @@ func S3Buckets(data dash.S3BucketsData) templ.Component {var templ_7745c5c3_Var26 stringtempl_7745c5c3_Var26, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%d", (data.CurrentPage-1)*data.PageSize+1))if templ_7745c5c3_Err != nil {- return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/s3_buckets.templ`, Line: 292, Col: 101}+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/s3_buckets.templ`, Line: 292, Col: 101}}_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var26))if templ_7745c5c3_Err != nil {@@ -553,7 +553,7 @@ func S3Buckets(data dash.S3BucketsData) templ.Component {var templ_7745c5c3_Var27 stringtempl_7745c5c3_Var27, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%d", minInt(data.CurrentPage*data.PageSize, data.TotalBuckets)))if templ_7745c5c3_Err != nil {- return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/s3_buckets.templ`, Line: 292, Col: 185}+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/s3_buckets.templ`, Line: 292, Col: 185}}_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var27))if templ_7745c5c3_Err != nil {@@ -566,7 +566,7 @@ func S3Buckets(data dash.S3BucketsData) templ.Component {var templ_7745c5c3_Var28 stringtempl_7745c5c3_Var28, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%d", data.TotalBuckets))if templ_7745c5c3_Err != nil {- return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/s3_buckets.templ`, Line: 292, Col: 229}+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/s3_buckets.templ`, Line: 292, Col: 229}}_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var28))if templ_7745c5c3_Err != nil {@@ -584,7 +584,7 @@ func S3Buckets(data dash.S3BucketsData) templ.Component {var templ_7745c5c3_Var29 stringtempl_7745c5c3_Var29, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%d", data.CurrentPage-1))if templ_7745c5c3_Err != nil {- return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/s3_buckets.templ`, Line: 299, Col: 142}+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/s3_buckets.templ`, Line: 299, Col: 142}}_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var29))if templ_7745c5c3_Err != nil {@@ -613,7 +613,7 @@ func S3Buckets(data dash.S3BucketsData) templ.Component {var templ_7745c5c3_Var30 stringtempl_7745c5c3_Var30, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%d", i))if templ_7745c5c3_Err != nil {- return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/s3_buckets.templ`, Line: 315, Col: 97}+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/s3_buckets.templ`, Line: 315, Col: 97}}_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var30))if templ_7745c5c3_Err != nil {@@ -631,7 +631,7 @@ func S3Buckets(data dash.S3BucketsData) templ.Component {var templ_7745c5c3_Var31 stringtempl_7745c5c3_Var31, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%d", i))if templ_7745c5c3_Err != nil {- return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/s3_buckets.templ`, Line: 319, Col: 129}+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/s3_buckets.templ`, Line: 319, Col: 129}}_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var31))if templ_7745c5c3_Err != nil {@@ -644,7 +644,7 @@ func S3Buckets(data dash.S3BucketsData) templ.Component {var templ_7745c5c3_Var32 stringtempl_7745c5c3_Var32, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%d", i))if templ_7745c5c3_Err != nil {- return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/s3_buckets.templ`, Line: 319, Col: 152}+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/s3_buckets.templ`, Line: 319, Col: 152}}_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var32))if templ_7745c5c3_Err != nil {@@ -668,7 +668,7 @@ func S3Buckets(data dash.S3BucketsData) templ.Component {var templ_7745c5c3_Var33 stringtempl_7745c5c3_Var33, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%d", data.CurrentPage+1))if templ_7745c5c3_Err != nil {- return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/s3_buckets.templ`, Line: 327, Col: 142}+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/s3_buckets.templ`, Line: 327, Col: 142}}_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var33))if templ_7745c5c3_Err != nil {@@ -696,13 +696,13 @@ func S3Buckets(data dash.S3BucketsData) templ.Component {var templ_7745c5c3_Var34 stringtempl_7745c5c3_Var34, templ_7745c5c3_Err = templ.JoinStringErrs(data.LastUpdated.Format("2006-01-02 15:04:05"))if templ_7745c5c3_Err != nil {- return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/s3_buckets.templ`, Line: 352, Col: 81}+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/s3_buckets.templ`, Line: 352, Col: 81}}_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var34))if templ_7745c5c3_Err != nil {return templ_7745c5c3_Err}- templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 79, "</small></div></div></div><!-- Create Bucket Modal --><div class=\"modal fade\" id=\"createBucketModal\" tabindex=\"-1\" aria-labelledby=\"createBucketModalLabel\" aria-hidden=\"true\"><div class=\"modal-dialog\"><div class=\"modal-content\"><div class=\"modal-header\"><h5 class=\"modal-title\" id=\"createBucketModalLabel\"><i class=\"fas fa-plus me-2\"></i>Create New S3 Bucket</h5><button type=\"button\" class=\"btn-close\" data-bs-dismiss=\"modal\" aria-label=\"Close\"></button></div><form id=\"createBucketForm\"><div class=\"modal-body\"><div class=\"mb-3\"><label for=\"bucketName\" class=\"form-label\">Bucket Name</label> <input type=\"text\" class=\"form-control\" id=\"bucketName\" name=\"name\" placeholder=\"my-bucket-name\" required pattern=\"[a-z0-9.-]+\" title=\"Bucket name must contain only lowercase letters, numbers, dots, and hyphens\"><div class=\"form-text\">Bucket names must be between 3 and 63 characters, contain only lowercase letters, numbers, dots, and hyphens.</div></div><div class=\"mb-3\"><label for=\"bucketOwner\" class=\"form-label\">Owner (Optional)</label> <select class=\"form-select\" id=\"bucketOwner\" name=\"owner\"><option value=\"\">No owner (admin-only access)</option><!-- Options will be populated dynamically when modal opens --></select><div class=\"form-text\">The S3 identity that owns this bucket. Non-admin users can only access buckets they own.</div></div><div class=\"mb-3\"><div class=\"form-check\"><input class=\"form-check-input\" type=\"checkbox\" id=\"enableQuota\" name=\"quota_enabled\"> <label class=\"form-check-label\" for=\"enableQuota\">Enable Storage Quota</label></div></div><div class=\"mb-3\" id=\"quotaSettings\" style=\"display: none;\"><div class=\"row\"><div class=\"col-md-8\"><label for=\"quotaSize\" class=\"form-label\">Quota Size</label> <input type=\"number\" class=\"form-control\" id=\"quotaSize\" name=\"quota_size\" placeholder=\"1024\" min=\"1\" step=\"1\"></div><div class=\"col-md-4\"><label for=\"quotaUnit\" class=\"form-label\">Unit</label> <select class=\"form-select\" id=\"quotaUnit\" name=\"quota_unit\"><option value=\"MB\" selected>MB</option> <option value=\"GB\">GB</option> <option value=\"TB\">TB</option></select></div></div><div class=\"form-text\">Set the maximum storage size for this bucket.</div></div><div class=\"mb-3\"><div class=\"form-check\"><input class=\"form-check-input\" type=\"checkbox\" id=\"enableVersioning\" name=\"versioning_enabled\"> <label class=\"form-check-label\" for=\"enableVersioning\">Enable Object Versioning</label></div><div class=\"form-text\">Keep multiple versions of objects in this bucket.</div></div><div class=\"mb-3\"><div class=\"form-check\"><input class=\"form-check-input\" type=\"checkbox\" id=\"enableObjectLock\" name=\"object_lock_enabled\"> <label class=\"form-check-label\" for=\"enableObjectLock\">Enable Object Lock</label></div><div class=\"form-text\">Prevent objects from being deleted or overwritten for a specified period. Automatically enables versioning.</div></div><div class=\"mb-3\" id=\"objectLockSettings\" style=\"display: none;\"><div class=\"row\"><div class=\"col-md-6\"><label for=\"objectLockMode\" class=\"form-label\">Object Lock Mode</label> <select class=\"form-select\" id=\"objectLockMode\" name=\"object_lock_mode\"><option value=\"GOVERNANCE\" selected>Governance</option> <option value=\"COMPLIANCE\">Compliance</option></select><div class=\"form-text\">Governance allows override with special permissions, Compliance is immutable.</div></div><div class=\"col-md-6\"><div class=\"form-check mb-3\"><input class=\"form-check-input\" type=\"checkbox\" id=\"setDefaultRetention\" name=\"set_default_retention\"> <label class=\"form-check-label\" for=\"setDefaultRetention\">Set Default Retention</label><div class=\"form-text\">Apply default retention to all new objects in this bucket.</div></div><div id=\"defaultRetentionSettings\" style=\"display: none;\"><label for=\"objectLockDuration\" class=\"form-label\">Default Retention (days)</label> <input type=\"number\" class=\"form-control\" id=\"objectLockDuration\" name=\"object_lock_duration\" placeholder=\"30\" min=\"1\" max=\"36500\" step=\"1\"><div class=\"form-text\">Default retention period for new objects (1-36500 days).</div></div></div></div></div></div><div class=\"modal-footer\"><button type=\"button\" class=\"btn btn-secondary\" data-bs-dismiss=\"modal\">Cancel</button> <button type=\"submit\" class=\"btn btn-primary\"><i class=\"fas fa-plus me-1\"></i>Create Bucket</button></div></form></div></div></div><!-- Delete Confirmation Modal --><div class=\"modal fade\" id=\"deleteBucketModal\" tabindex=\"-1\" aria-labelledby=\"deleteBucketModalLabel\" aria-hidden=\"true\"><div class=\"modal-dialog\"><div class=\"modal-content\"><div class=\"modal-header\"><h5 class=\"modal-title\" id=\"deleteBucketModalLabel\"><i class=\"fas fa-exclamation-triangle me-2 text-warning\"></i>Delete Bucket</h5><button type=\"button\" class=\"btn-close\" data-bs-dismiss=\"modal\" aria-label=\"Close\"></button></div><div class=\"modal-body\"><p>Are you sure you want to delete the bucket <strong id=\"deleteBucketName\"></strong>?</p><div class=\"alert alert-warning\"><i class=\"fas fa-exclamation-triangle me-2\"></i> <strong>Warning:</strong> This action cannot be undone. All objects in the bucket will be permanently deleted.</div></div><div class=\"modal-footer\"><button type=\"button\" class=\"btn btn-secondary\" data-bs-dismiss=\"modal\">Cancel</button> <button type=\"button\" class=\"btn btn-danger\" onclick=\"deleteBucket()\"><i class=\"fas fa-trash me-1\"></i>Delete Bucket</button></div></div></div></div><!-- Manage Quota Modal --><div class=\"modal fade\" id=\"manageQuotaModal\" tabindex=\"-1\" aria-labelledby=\"manageQuotaModalLabel\" aria-hidden=\"true\"><div class=\"modal-dialog\"><div class=\"modal-content\"><div class=\"modal-header\"><h5 class=\"modal-title\" id=\"manageQuotaModalLabel\"><i class=\"fas fa-tachometer-alt me-2\"></i>Manage Bucket Quota</h5><button type=\"button\" class=\"btn-close\" data-bs-dismiss=\"modal\" aria-label=\"Close\"></button></div><form id=\"quotaForm\"><div class=\"modal-body\"><div class=\"mb-3\"><label class=\"form-label\">Bucket Name</label> <input type=\"text\" class=\"form-control\" id=\"quotaBucketName\" readonly></div><div class=\"mb-3\"><div class=\"form-check\"><input class=\"form-check-input\" type=\"checkbox\" id=\"quotaEnabled\" name=\"quota_enabled\"> <label class=\"form-check-label\" for=\"quotaEnabled\">Enable Storage Quota</label></div></div><div class=\"mb-3\" id=\"quotaSizeSettings\"><div class=\"row\"><div class=\"col-md-8\"><label for=\"quotaSizeMB\" class=\"form-label\">Quota Size</label> <input type=\"number\" class=\"form-control\" id=\"quotaSizeMB\" name=\"quota_size\" placeholder=\"1024\" min=\"0\" step=\"1\"></div><div class=\"col-md-4\"><label for=\"quotaUnitMB\" class=\"form-label\">Unit</label> <select class=\"form-select\" id=\"quotaUnitMB\" name=\"quota_unit\"><option value=\"MB\" selected>MB</option> <option value=\"GB\">GB</option> <option value=\"TB\">TB</option></select></div></div><div class=\"form-text\">Set the maximum storage size for this bucket. Set to 0 to remove quota.</div></div></div><div class=\"modal-footer\"><button type=\"button\" class=\"btn btn-secondary\" data-bs-dismiss=\"modal\">Cancel</button> <button type=\"submit\" class=\"btn btn-warning\"><i class=\"fas fa-save me-1\"></i>Update Quota</button></div></form></div></div></div><!-- Bucket Details Modal --><div class=\"modal fade\" id=\"bucketDetailsModal\" tabindex=\"-1\" aria-labelledby=\"bucketDetailsModalLabel\" aria-hidden=\"true\"><div class=\"modal-dialog modal-lg\"><div class=\"modal-content\"><div class=\"modal-header\"><h5 class=\"modal-title\" id=\"bucketDetailsModalLabel\"><i class=\"fas fa-cube me-2\"></i>Bucket Details</h5><button type=\"button\" class=\"btn-close\" data-bs-dismiss=\"modal\" aria-label=\"Close\"></button></div><div class=\"modal-body\"><div id=\"bucketDetailsContent\"><div class=\"text-center py-4\"><div class=\"spinner-border text-primary\" role=\"status\"><span class=\"visually-hidden\">Loading...</span></div><div class=\"mt-2\">Loading bucket details...</div></div></div></div><div class=\"modal-footer\"><button type=\"button\" class=\"btn btn-secondary\" data-bs-dismiss=\"modal\">Close</button></div></div></div></div><!-- Manage Owner Modal --><div class=\"modal fade\" id=\"manageOwnerModal\" tabindex=\"-1\" aria-labelledby=\"manageOwnerModalLabel\" aria-hidden=\"true\"><div class=\"modal-dialog\"><div class=\"modal-content\"><div class=\"modal-header\"><h5 class=\"modal-title\" id=\"manageOwnerModalLabel\"><i class=\"fas fa-user-edit me-2\"></i>Manage Bucket Owner</h5><button type=\"button\" class=\"btn-close\" data-bs-dismiss=\"modal\" aria-label=\"Close\"></button></div><form id=\"ownerForm\"><div class=\"modal-body\"><div class=\"mb-3\"><label class=\"form-label\">Bucket Name</label> <input type=\"text\" class=\"form-control\" id=\"ownerBucketName\" readonly></div><div class=\"mb-3\"><label for=\"bucketOwnerSelect\" class=\"form-label\">Owner</label> <select class=\"form-select\" id=\"bucketOwnerSelect\" name=\"owner\"><option value=\"\">No owner (admin-only access)</option><!-- Options will be populated dynamically --></select><div class=\"form-text\">Select the S3 identity that owns this bucket. Non-admin users can only access buckets they own.</div></div><div id=\"ownerLoadingSpinner\" class=\"text-center py-2\" style=\"display: none;\"><div class=\"spinner-border spinner-border-sm text-primary\" role=\"status\"><span class=\"visually-hidden\">Loading users...</span></div><span class=\"ms-2\">Loading users...</span></div></div><div class=\"modal-footer\"><button type=\"button\" class=\"btn btn-secondary\" data-bs-dismiss=\"modal\">Cancel</button> <button type=\"submit\" class=\"btn btn-info\"><i class=\"fas fa-save me-1\"></i>Update Owner</button></div></form></div></div></div><!-- JavaScript for bucket management --><script>\n // Global state (shared between DOMContentLoaded handlers and global functions)\n let deleteModalInstance = null;\n let quotaModalInstance = null;\n let ownerModalInstance = null;\n let detailsModalInstance = null;\n let cachedUsers = null;\n\n document.addEventListener('DOMContentLoaded', function() {\n // Add click handlers to pagination links\n document.querySelectorAll('.pagination-link').forEach(link => {\n link.addEventListener('click', function(e) {\n e.preventDefault();\n const page = this.getAttribute('data-page');\n goToPage(page);\n });\n });\n\n // Initialize modal instances once (reuse with show/hide)\n deleteModalInstance = new bootstrap.Modal(document.getElementById('deleteBucketModal'));\n quotaModalInstance = new bootstrap.Modal(document.getElementById('manageQuotaModal'));\n ownerModalInstance = new bootstrap.Modal(document.getElementById('manageOwnerModal'));\n detailsModalInstance = new bootstrap.Modal(document.getElementById('bucketDetailsModal'));\n\n const quotaCheckbox = document.getElementById('enableQuota');\n const quotaSettings = document.getElementById('quotaSettings');\n const versioningCheckbox = document.getElementById('enableVersioning');\n const objectLockCheckbox = document.getElementById('enableObjectLock');\n const objectLockSettings = document.getElementById('objectLockSettings');\n const setDefaultRetentionCheckbox = document.getElementById('setDefaultRetention');\n const defaultRetentionSettings = document.getElementById('defaultRetentionSettings');\n const createBucketForm = document.getElementById('createBucketForm');\n\n // Toggle quota settings\n quotaCheckbox.addEventListener('change', function() {\n quotaSettings.style.display = this.checked ? 'block' : 'none';\n });\n\n // Toggle object lock settings and automatically enable versioning\n objectLockCheckbox.addEventListener('change', function() {\n objectLockSettings.style.display = this.checked ? 'block' : 'none';\n if (this.checked) {\n versioningCheckbox.checked = true;\n versioningCheckbox.disabled = true;\n } else {\n versioningCheckbox.disabled = false;\n // Reset default retention settings when object lock is disabled\n setDefaultRetentionCheckbox.checked = false;\n defaultRetentionSettings.style.display = 'none';\n }\n });\n\n // Toggle default retention settings\n setDefaultRetentionCheckbox.addEventListener('change', function() {\n defaultRetentionSettings.style.display = this.checked ? 'block' : 'none';\n });\n\n // Populate owner dropdown when create bucket modal opens\n document.getElementById('createBucketModal').addEventListener('show.bs.modal', async function() {\n const ownerSelect = document.getElementById('bucketOwner');\n \n // Only fetch if not already populated\n if (ownerSelect.options.length <= 1) {\n try {\n const response = await fetch('/api/users');\n const data = await response.json();\n const users = data.users || [];\n \n users.forEach(user => {\n const option = document.createElement('option');\n option.value = user.username;\n option.textContent = user.username;\n ownerSelect.appendChild(option);\n });\n } catch (error) {\n console.error('Error fetching users for owner dropdown:', error);\n // Reset to default state on error - user can still create bucket without owner\n ownerSelect.innerHTML = '<option value=\"\">No owner (admin-only access)</option>';\n ownerSelect.selectedIndex = 0;\n }\n }\n });\n\n // Handle form submission\n createBucketForm.addEventListener('submit', function(e) {\n e.preventDefault();\n \n const formData = new FormData(this);\n const data = {\n name: formData.get('name'),\n owner: formData.get('owner') || '',\n region: formData.get('region') || '',\n quota_size: quotaCheckbox.checked ? parseInt(formData.get('quota_size')) || 0 : 0,\n quota_unit: formData.get('quota_unit') || 'MB',\n quota_enabled: quotaCheckbox.checked,\n versioning_enabled: versioningCheckbox.checked,\n object_lock_enabled: objectLockCheckbox.checked,\n object_lock_mode: formData.get('object_lock_mode') || 'GOVERNANCE',\n set_default_retention: setDefaultRetentionCheckbox.checked,\n object_lock_duration: setDefaultRetentionCheckbox.checked ? parseInt(formData.get('object_lock_duration')) || 30 : 0\n };\n\n // Validate object lock settings\n if (data.object_lock_enabled && data.set_default_retention && data.object_lock_duration <= 0) {\n alert('Please enter a valid retention duration for object lock.');\n return;\n }\n\n fetch('/api/s3/buckets', {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify(data)\n })\n .then(response => response.json())\n .then(data => {\n if (data.error) {\n alert('Error creating bucket: ' + data.error);\n } else {\n alert('Bucket created successfully!');\n // Properly close the modal before reloading\n const createModal = bootstrap.Modal.getInstance(document.getElementById('createBucketModal'));\n if (createModal) {\n createModal.hide();\n }\n setTimeout(() => location.reload(), 500);\n }\n })\n .catch(error => {\n console.error('Error:', error);\n alert('Error creating bucket: ' + error.message);\n });\n });\n\n // Handle delete bucket\n const deleteForm = document.getElementById('deleteBucketModal');\n document.querySelectorAll('.delete-bucket-btn').forEach(button => {\n button.addEventListener('click', function() {\n const bucketName = this.dataset.bucketName;\n document.getElementById('deleteBucketName').textContent = bucketName;\n // Store bucket name on modal element instead of global window property\n deleteForm.dataset.bucketName = bucketName;\n deleteModalInstance.show();\n });\n });\n\n // Handle quota management\n const quotaForm = document.getElementById('quotaForm');\n document.querySelectorAll('.quota-btn').forEach(button => {\n button.addEventListener('click', function() {\n const bucketName = this.dataset.bucketName;\n const currentQuota = parseInt(this.dataset.currentQuota);\n const quotaEnabled = this.dataset.quotaEnabled === 'true';\n \n document.getElementById('quotaBucketName').value = bucketName;\n document.getElementById('quotaEnabled').checked = quotaEnabled;\n document.getElementById('quotaSizeMB').value = currentQuota;\n \n // Toggle quota size settings\n document.getElementById('quotaSizeSettings').style.display = quotaEnabled ? 'block' : 'none';\n \n // Store bucket name on form element instead of global window property\n quotaForm.dataset.bucketName = bucketName;\n quotaModalInstance.show();\n });\n });\n\n // Add event listener to properly dispose of quota modal when hidden\n document.getElementById('manageQuotaModal').addEventListener('hidden.bs.modal', function() {\n if (quotaModalInstance) {\n quotaModalInstance.dispose();\n quotaModalInstance = null;\n }\n // Force remove any remaining backdrops\n document.querySelectorAll('.modal-backdrop').forEach(backdrop => {\n backdrop.remove();\n });\n // Ensure body classes are removed\n document.body.classList.remove('modal-open');\n document.body.style.removeProperty('padding-right');\n });\n\n // Handle quota form submission\n document.getElementById('quotaForm').addEventListener('submit', function(e) {\n e.preventDefault();\n \n const bucketName = this.dataset.bucketName;\n if (!bucketName) return;\n\n const formData = new FormData(this);\n const enabled = document.getElementById('quotaEnabled').checked;\n const data = {\n quota_size: enabled ? parseInt(formData.get('quota_size')) || 0 : 0,\n quota_unit: formData.get('quota_unit') || 'MB',\n quota_enabled: enabled\n };\n\n fetch(`/api/s3/buckets/${bucketName}/quota`, {\n method: 'PUT',\n headers: {\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify(data)\n })\n .then(response => response.json())\n .then(data => {\n if (data.error) {\n alert('Error updating quota: ' + data.error);\n } else {\n alert('Quota updated successfully!');\n // Properly close the modal before reloading\n if (quotaModalInstance) {\n quotaModalInstance.hide();\n }\n setTimeout(() => location.reload(), 500);\n }\n })\n .catch(error => {\n console.error('Error:', error);\n alert('Error updating quota: ' + error.message);\n });\n });\n\n // Handle quota enabled checkbox\n document.getElementById('quotaEnabled').addEventListener('change', function() {\n document.getElementById('quotaSizeSettings').style.display = this.checked ? 'block' : 'none';\n });\n\n // Handle owner management\n const ownerForm = document.getElementById('ownerForm');\n document.querySelectorAll('.owner-btn').forEach(button => {\n button.addEventListener('click', async function() {\n const bucketName = this.dataset.bucketName;\n const currentOwner = this.dataset.currentOwner || '';\n \n document.getElementById('ownerBucketName').value = bucketName;\n // Store bucket name on form element instead of global window property\n ownerForm.dataset.bucketName = bucketName;\n \n // Show loading spinner\n document.getElementById('ownerLoadingSpinner').style.display = 'block';\n document.getElementById('bucketOwnerSelect').disabled = true;\n \n ownerModalInstance.show();\n \n // Fetch users if not cached\n try {\n if (!cachedUsers) {\n const response = await fetch('/api/users');\n const data = await response.json();\n cachedUsers = data.users || [];\n }\n \n // Populate the select dropdown\n const select = document.getElementById('bucketOwnerSelect');\n select.innerHTML = '<option value=\"\">No owner (admin-only access)</option>';\n \n cachedUsers.forEach(user => {\n const option = document.createElement('option');\n option.value = user.username;\n option.textContent = user.username;\n if (user.username === currentOwner) {\n option.selected = true;\n }\n select.appendChild(option);\n });\n \n select.disabled = false;\n } catch (error) {\n console.error('Error fetching users:', error);\n alert('Error loading users: ' + error.message);\n // Re-enable select and reset to default on error\n const select = document.getElementById('bucketOwnerSelect');\n select.innerHTML = '<option value=\"\">No owner (admin-only access)</option>';\n select.selectedIndex = 0;\n select.disabled = false;\n } finally {\n document.getElementById('ownerLoadingSpinner').style.display = 'none';\n }\n });\n });\n\n // Handle owner form submission\n document.getElementById('ownerForm').addEventListener('submit', function(e) {\n e.preventDefault();\n \n const bucketName = this.dataset.bucketName;\n if (!bucketName) return;\n\n const owner = document.getElementById('bucketOwnerSelect').value;\n const data = { owner: owner };\n\n fetch(`/api/s3/buckets/${bucketName}/owner`, {\n method: 'PUT',\n headers: {\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify(data)\n })\n .then(response => response.json())\n .then(data => {\n if (data.error) {\n alert('Error updating owner: ' + data.error);\n } else {\n alert('Bucket owner updated successfully!');\n // Properly close the modal before reloading\n if (ownerModalInstance) {\n ownerModalInstance.hide();\n }\n setTimeout(() => location.reload(), 500);\n }\n })\n .catch(error => {\n console.error('Error:', error);\n alert('Error updating owner: ' + error.message);\n });\n });\n\n // Handle view details button\n document.querySelectorAll('.view-details-btn').forEach(button => {\n button.addEventListener('click', function() {\n const bucketName = this.dataset.bucketName;\n \n // Update modal title\n document.getElementById('bucketDetailsModalLabel').innerHTML = \n '<i class=\"fas fa-cube me-2\"></i>Bucket Details - ' + bucketName;\n \n // Show loading spinner\n document.getElementById('bucketDetailsContent').innerHTML = \n '<div class=\"text-center py-4\">' +\n '<div class=\"spinner-border text-primary\" role=\"status\">' +\n '<span class=\"visually-hidden\">Loading...</span>' +\n '<\\\\/div>' +\n '<div class=\"mt-2\">Loading bucket details...</div>' +\n '<\\\\/div>';\n \n detailsModalInstance.show();\n \n // Fetch bucket details\n fetch('/api/s3/buckets/' + bucketName)\n .then(response => response.json())\n .then(data => {\n if (data.error) {\n document.getElementById('bucketDetailsContent').innerHTML = \n '<div class=\"alert alert-danger\">' +\n '<i class=\"fas fa-exclamation-triangle me-2\"></i>' +\n 'Error loading bucket details: ' + data.error +\n '<\\\\/div>';\n } else {\n displayBucketDetails(data);\n }\n })\n .catch(error => {\n console.error('Error fetching bucket details:', error);\n document.getElementById('bucketDetailsContent').innerHTML = \n '<div class=\"alert alert-danger\">' +\n '<i class=\"fas fa-exclamation-triangle me-2\"></i>' +\n 'Error loading bucket details: ' + error.message +\n '<\\\\/div>';\n });\n });\n });\n });\n\n function deleteBucket() {\n const bucketName = document.getElementById('deleteBucketModal').dataset.bucketName;\n if (!bucketName) return;\n\n fetch(`/api/s3/buckets/${bucketName}`, {\n method: 'DELETE'\n })\n .then(response => response.json())\n .then(data => {\n if (data.error) {\n alert('Error deleting bucket: ' + data.error);\n } else {\n alert('Bucket deleted successfully!');\n // Properly close the modal before reloading\n if (deleteModalInstance) {\n deleteModalInstance.hide();\n }\n setTimeout(() => location.reload(), 500);\n }\n })\n .catch(error => {\n console.error('Error:', error);\n alert('Error deleting bucket: ' + error.message);\n });\n }\n\nfunction displayBucketDetails(data) {\n const bucket = data.bucket;\n\n function escapeHtml(v) {\n return String(v ?? '')\n .replace(/&/g, '&')\n .replace(/</g, '<')\n .replace(/>/g, '>')\n .replace(/\"/g, '"')\n .replace(/'/g, ''');\n }\n\n function formatBytes(bytes) {\n if (bytes === 0) return '0 Bytes';\n const k = 1024;\n const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB'];\n const i = Math.floor(Math.log(bytes) / Math.log(k));\n return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];\n }\n\n function formatDate(dateString) {\n const date = new Date(dateString);\n return date.toLocaleString();\n }\n\n let ownerHtml = '<span class=\"text-muted\">No owner (admin-only)</span>';\n if (bucket.owner) {\n ownerHtml = '<span class=\"badge bg-info\"><i class=\"fas fa-user me-1\"></i>' + escapeHtml(bucket.owner) + '</span>';\n }\n\n let usageHtml = '';\n if (bucket.physical_size > 0 && bucket.logical_size > 0 && bucket.physical_size > bucket.logical_size) {\n const overhead = (bucket.physical_size / bucket.logical_size).toFixed(1);\n usageHtml = '<br><small class=\"text-muted\">' + overhead + 'x overhead<\\/small>';\n }\n\n let quotaHtml = '<span class=\"badge bg-secondary\">Disabled</span>';\n if (bucket.quota_enabled) {\n quotaHtml = '<span class=\"badge bg-success\">' + formatBytes(bucket.quota) + '</span>';\n }\n\n let versioningHtml = '<span class=\"text-muted\">Not configured</span>';\n if (bucket.versioning_status === 'Enabled') {\n versioningHtml = '<span class=\"badge bg-success\"><i class=\"fas fa-check me-1\"></i>Enabled</span>';\n } else if (bucket.versioning_status === 'Suspended') {\n versioningHtml = '<span class=\"badge bg-warning\"><i class=\"fas fa-pause me-1\"></i>Suspended</span>';\n }\n\n let objectLockHtml = '<span class=\"text-muted\">Not configured</span>';\n if (bucket.object_lock_enabled) {\n let details = '';\n if (bucket.object_lock_mode && bucket.object_lock_duration > 0) {\n details = '<br><small class=\"text-muted\">' + escapeHtml(bucket.object_lock_mode) + ' • ' + bucket.object_lock_duration + ' days<\\/small>';\n }\n objectLockHtml = '<span class=\"badge bg-warning\"><i class=\"fas fa-lock me-1\"></i>Enabled</span>' + details;\n }\n\n const rows = [\n '<div class=\"row\">',\n '<div class=\"col-md-6\">',\n '<h6><i class=\"fas fa-info-circle me-2\"></i>Bucket Information</h6>',\n '<table class=\"table table-sm\">',\n '<tr><td><strong>Name:</strong></td><td>' + escapeHtml(bucket.name) + '<\\/td><\\/tr>',\n '<tr><td><strong>Owner:</strong></td><td>' + ownerHtml + '<\\/td><\\/tr>',\n '<tr><td><strong>Created:</strong></td><td>' + formatDate(bucket.created_at) + '<\\/td><\\/tr>',\n '<tr><td><strong>Last Modified:</strong></td><td>' + formatDate(bucket.last_modified) + '<\\/td><\\/tr>',\n '<tr><td><strong>Logical Size:</strong></td><td>' + formatBytes(bucket.logical_size) + '<\\/td><\\/tr>',\n '<tr><td><strong>Physical Size:</strong></td><td>' + formatBytes(bucket.physical_size) + usageHtml + '<\\/td><\\/tr>',\n '<\\/table>',\n '<\\/div>',\n '<div class=\"col-md-6\">',\n '<h6><i class=\"fas fa-cogs me-2\"></i>Configuration</h6>',\n '<table class=\"table table-sm\">',\n '<tr><td><strong>Quota:</strong></td><td>' + quotaHtml + '<\\/td><\\/tr>',\n '<tr><td><strong>Versioning:</strong></td><td>' + versioningHtml + '<\\/td><\\/tr>',\n '<tr><td><strong>Object Lock:</strong></td><td>' + objectLockHtml + '<\\/td><\\/tr>',\n '<\\/table>',\n '<\\/div>',\n '<\\/div>'\n ];\n\n document.getElementById('bucketDetailsContent').innerHTML = rows.join('');\n}\n\n function goToPage(page) {\n const url = new URL(window.location);\n url.searchParams.set('page', page);\n window.location.href = url.toString();\n }\n\n function changePageSize() {\n const pageSize = document.getElementById('pageSizeSelect').value;\n const url = new URL(window.location);\n url.searchParams.set('pageSize', pageSize);\n url.searchParams.set('page', '1');\n window.location.href = url.toString();\n }\n\n function sortTable(column) {\n const url = new URL(window.location);\n const currentSort = url.searchParams.get('sortBy');\n const currentOrder = url.searchParams.get('sortOrder') || 'asc';\n\n let newOrder = 'asc';\n if (currentSort === column && currentOrder === 'asc') {\n newOrder = 'desc';\n }\n\n url.searchParams.set('sortBy', column);\n url.searchParams.set('sortOrder', newOrder);\n url.searchParams.set('page', '1');\n window.location.href = url.toString();\n }\n\n function exportBucketList() {\n // RFC 4180 compliant CSV escaping: escape double quotes by doubling them\n function escapeCsvField(value) {\n const str = String(value ?? '');\n if (str.includes(',') || str.includes('\"') || str.includes('\\n') || str.includes('\\r')) {\n return '\"' + str.replace(/\"/g, '\"\"') + '\"';\n }\n return '\"' + str + '\"';\n }\n\n function formatBytes(bytes) {\n if (bytes === 0) return '0 Bytes';\n const k = 1024;\n const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB'];\n const i = Math.floor(Math.log(bytes) / Math.log(k));\n return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];\n }\n\n // Fetch all buckets from the API (not just the current page)\n fetch('/api/s3/buckets')\n .then(response => response.json())\n .then(data => {\n if (data.error) {\n alert('Error exporting buckets: ' + data.error);\n return;\n }\n\n const buckets = data.buckets || [];\n const csvContent = \"data:text/csv;charset=utf-8,\" +\n \"Name,Owner,Logical Size,Physical Size,Created,Quota,Versioning,Object Lock\\n\" +\n buckets.map(b => [\n escapeCsvField(b.name),\n escapeCsvField(b.owner),\n escapeCsvField(formatBytes(b.logical_size)),\n escapeCsvField(formatBytes(b.physical_size)),\n escapeCsvField(b.created_at),\n escapeCsvField(b.quota_enabled ? formatBytes(b.quota) : 'No quota'),\n escapeCsvField(b.versioning_status || 'Not configured'),\n escapeCsvField(b.object_lock_enabled ? 'Enabled' : 'Not configured')\n ].join(',')).join(\"\\n\");\n\n const encodedUri = encodeURI(csvContent);\n const link = document.createElement(\"a\");\n link.setAttribute(\"href\", encodedUri);\n link.setAttribute(\"download\", \"buckets.csv\");\n document.body.appendChild(link);\n link.click();\n document.body.removeChild(link);\n })\n .catch(error => {\n console.error('Error:', error);\n alert('Error exporting buckets: ' + error.message);\n });\n }\n </script>")+ templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 79, "</small></div></div></div><!-- Create Bucket Modal --><div class=\"modal fade\" id=\"createBucketModal\" tabindex=\"-1\" aria-labelledby=\"createBucketModalLabel\" aria-hidden=\"true\"><div class=\"modal-dialog\"><div class=\"modal-content\"><div class=\"modal-header\"><h5 class=\"modal-title\" id=\"createBucketModalLabel\"><i class=\"fas fa-plus me-2\"></i>Create New S3 Bucket</h5><button type=\"button\" class=\"btn-close\" data-bs-dismiss=\"modal\" aria-label=\"Close\"></button></div><form id=\"createBucketForm\"><div class=\"modal-body\"><div class=\"mb-3\"><label for=\"bucketName\" class=\"form-label\">Bucket Name</label> <input type=\"text\" class=\"form-control\" id=\"bucketName\" name=\"name\" placeholder=\"my-bucket-name\" required pattern=\"[a-z0-9.-]+\" title=\"Bucket name must contain only lowercase letters, numbers, dots, and hyphens\"><div class=\"form-text\">Bucket names must be between 3 and 63 characters, contain only lowercase letters, numbers, dots, and hyphens.</div></div><div class=\"mb-3\"><label for=\"bucketOwner\" class=\"form-label\">Owner (Optional)</label> <select class=\"form-select\" id=\"bucketOwner\" name=\"owner\"><option value=\"\">No owner (admin-only access)</option><!-- Options will be populated dynamically when modal opens --></select><div class=\"form-text\">The S3 identity that owns this bucket. Non-admin users can only access buckets they own.</div></div><div class=\"mb-3\"><div class=\"form-check\"><input class=\"form-check-input\" type=\"checkbox\" id=\"enableQuota\" name=\"quota_enabled\"> <label class=\"form-check-label\" for=\"enableQuota\">Enable Storage Quota</label></div></div><div class=\"mb-3\" id=\"quotaSettings\" style=\"display: none;\"><div class=\"row\"><div class=\"col-md-8\"><label for=\"quotaSize\" class=\"form-label\">Quota Size</label> <input type=\"number\" class=\"form-control\" id=\"quotaSize\" name=\"quota_size\" placeholder=\"1024\" min=\"1\" step=\"1\"></div><div class=\"col-md-4\"><label for=\"quotaUnit\" class=\"form-label\">Unit</label> <select class=\"form-select\" id=\"quotaUnit\" name=\"quota_unit\"><option value=\"MB\" selected>MB</option> <option value=\"GB\">GB</option> <option value=\"TB\">TB</option></select></div></div><div class=\"form-text\">Set the maximum storage size for this bucket.</div></div><div class=\"mb-3\"><div class=\"form-check\"><input class=\"form-check-input\" type=\"checkbox\" id=\"enableVersioning\" name=\"versioning_enabled\"> <label class=\"form-check-label\" for=\"enableVersioning\">Enable Object Versioning</label></div><div class=\"form-text\">Keep multiple versions of objects in this bucket.</div></div><div class=\"mb-3\"><div class=\"form-check\"><input class=\"form-check-input\" type=\"checkbox\" id=\"enableObjectLock\" name=\"object_lock_enabled\"> <label class=\"form-check-label\" for=\"enableObjectLock\">Enable Object Lock</label></div><div class=\"form-text\">Prevent objects from being deleted or overwritten for a specified period. Automatically enables versioning.</div></div><div class=\"mb-3\" id=\"objectLockSettings\" style=\"display: none;\"><div class=\"row\"><div class=\"col-md-6\"><label for=\"objectLockMode\" class=\"form-label\">Object Lock Mode</label> <select class=\"form-select\" id=\"objectLockMode\" name=\"object_lock_mode\"><option value=\"GOVERNANCE\" selected>Governance</option> <option value=\"COMPLIANCE\">Compliance</option></select><div class=\"form-text\">Governance allows override with special permissions, Compliance is immutable.</div></div><div class=\"col-md-6\"><div class=\"form-check mb-3\"><input class=\"form-check-input\" type=\"checkbox\" id=\"setDefaultRetention\" name=\"set_default_retention\"> <label class=\"form-check-label\" for=\"setDefaultRetention\">Set Default Retention</label><div class=\"form-text\">Apply default retention to all new objects in this bucket.</div></div><div id=\"defaultRetentionSettings\" style=\"display: none;\"><label for=\"objectLockDuration\" class=\"form-label\">Default Retention (days)</label> <input type=\"number\" class=\"form-control\" id=\"objectLockDuration\" name=\"object_lock_duration\" placeholder=\"30\" min=\"1\" max=\"36500\" step=\"1\"><div class=\"form-text\">Default retention period for new objects (1-36500 days).</div></div></div></div></div></div><div class=\"modal-footer\"><button type=\"button\" class=\"btn btn-secondary\" data-bs-dismiss=\"modal\">Cancel</button> <button type=\"submit\" class=\"btn btn-primary\"><i class=\"fas fa-plus me-1\"></i>Create Bucket</button></div></form></div></div></div><!-- Delete Confirmation Modal --><div class=\"modal fade\" id=\"deleteBucketModal\" tabindex=\"-1\" aria-labelledby=\"deleteBucketModalLabel\" aria-hidden=\"true\"><div class=\"modal-dialog\"><div class=\"modal-content\"><div class=\"modal-header\"><h5 class=\"modal-title\" id=\"deleteBucketModalLabel\"><i class=\"fas fa-exclamation-triangle me-2 text-warning\"></i>Delete Bucket</h5><button type=\"button\" class=\"btn-close\" data-bs-dismiss=\"modal\" aria-label=\"Close\"></button></div><div class=\"modal-body\"><p>Are you sure you want to delete the bucket <strong id=\"deleteBucketName\"></strong>?</p><div class=\"alert alert-warning\"><i class=\"fas fa-exclamation-triangle me-2\"></i> <strong>Warning:</strong> This action cannot be undone. All objects in the bucket will be permanently deleted.</div></div><div class=\"modal-footer\"><button type=\"button\" class=\"btn btn-secondary\" data-bs-dismiss=\"modal\">Cancel</button> <button type=\"button\" class=\"btn btn-danger\" onclick=\"deleteBucket()\"><i class=\"fas fa-trash me-1\"></i>Delete Bucket</button></div></div></div></div><!-- Manage Quota Modal --><div class=\"modal fade\" id=\"manageQuotaModal\" tabindex=\"-1\" aria-labelledby=\"manageQuotaModalLabel\" aria-hidden=\"true\"><div class=\"modal-dialog\"><div class=\"modal-content\"><div class=\"modal-header\"><h5 class=\"modal-title\" id=\"manageQuotaModalLabel\"><i class=\"fas fa-tachometer-alt me-2\"></i>Manage Bucket Quota</h5><button type=\"button\" class=\"btn-close\" data-bs-dismiss=\"modal\" aria-label=\"Close\"></button></div><form id=\"quotaForm\"><div class=\"modal-body\"><div class=\"mb-3\"><label class=\"form-label\">Bucket Name</label> <input type=\"text\" class=\"form-control\" id=\"quotaBucketName\" readonly></div><div class=\"mb-3\"><div class=\"form-check\"><input class=\"form-check-input\" type=\"checkbox\" id=\"quotaEnabled\" name=\"quota_enabled\"> <label class=\"form-check-label\" for=\"quotaEnabled\">Enable Storage Quota</label></div></div><div class=\"mb-3\" id=\"quotaSizeSettings\"><div class=\"row\"><div class=\"col-md-8\"><label for=\"quotaSizeMB\" class=\"form-label\">Quota Size</label> <input type=\"number\" class=\"form-control\" id=\"quotaSizeMB\" name=\"quota_size\" placeholder=\"1024\" min=\"0\" step=\"1\"></div><div class=\"col-md-4\"><label for=\"quotaUnitMB\" class=\"form-label\">Unit</label> <select class=\"form-select\" id=\"quotaUnitMB\" name=\"quota_unit\"><option value=\"MB\" selected>MB</option> <option value=\"GB\">GB</option> <option value=\"TB\">TB</option></select></div></div><div class=\"form-text\">Set the maximum storage size for this bucket. Set to 0 to remove quota.</div></div></div><div class=\"modal-footer\"><button type=\"button\" class=\"btn btn-secondary\" data-bs-dismiss=\"modal\">Cancel</button> <button type=\"submit\" class=\"btn btn-warning\"><i class=\"fas fa-save me-1\"></i>Update Quota</button></div></form></div></div></div><!-- Bucket Details Modal --><div class=\"modal fade\" id=\"bucketDetailsModal\" tabindex=\"-1\" aria-labelledby=\"bucketDetailsModalLabel\" aria-hidden=\"true\"><div class=\"modal-dialog modal-lg\"><div class=\"modal-content\"><div class=\"modal-header\"><h5 class=\"modal-title\" id=\"bucketDetailsModalLabel\"><i class=\"fas fa-cube me-2\"></i>Bucket Details</h5><button type=\"button\" class=\"btn-close\" data-bs-dismiss=\"modal\" aria-label=\"Close\"></button></div><div class=\"modal-body\"><div id=\"bucketDetailsContent\"><div class=\"text-center py-4\"><div class=\"spinner-border text-primary\" role=\"status\"><span class=\"visually-hidden\">Loading...</span></div><div class=\"mt-2\">Loading bucket details...</div></div></div></div><div class=\"modal-footer\"><button type=\"button\" class=\"btn btn-secondary\" data-bs-dismiss=\"modal\">Close</button></div></div></div></div><!-- Manage Owner Modal --><div class=\"modal fade\" id=\"manageOwnerModal\" tabindex=\"-1\" aria-labelledby=\"manageOwnerModalLabel\" aria-hidden=\"true\"><div class=\"modal-dialog\"><div class=\"modal-content\"><div class=\"modal-header\"><h5 class=\"modal-title\" id=\"manageOwnerModalLabel\"><i class=\"fas fa-user-edit me-2\"></i>Manage Bucket Owner</h5><button type=\"button\" class=\"btn-close\" data-bs-dismiss=\"modal\" aria-label=\"Close\"></button></div><form id=\"ownerForm\"><div class=\"modal-body\"><div class=\"mb-3\"><label class=\"form-label\">Bucket Name</label> <input type=\"text\" class=\"form-control\" id=\"ownerBucketName\" readonly></div><div class=\"mb-3\"><label for=\"bucketOwnerSelect\" class=\"form-label\">Owner</label> <select class=\"form-select\" id=\"bucketOwnerSelect\" name=\"owner\"><option value=\"\">No owner (admin-only access)</option><!-- Options will be populated dynamically --></select><div class=\"form-text\">Select the S3 identity that owns this bucket. Non-admin users can only access buckets they own.</div></div><div id=\"ownerLoadingSpinner\" class=\"text-center py-2\" style=\"display: none;\"><div class=\"spinner-border spinner-border-sm text-primary\" role=\"status\"><span class=\"visually-hidden\">Loading users...</span></div><span class=\"ms-2\">Loading users...</span></div></div><div class=\"modal-footer\"><button type=\"button\" class=\"btn btn-secondary\" data-bs-dismiss=\"modal\">Cancel</button> <button type=\"submit\" class=\"btn btn-info\"><i class=\"fas fa-save me-1\"></i>Update Owner</button></div></form></div></div></div><!-- JavaScript for bucket management --><script>\n // Global state (shared between DOMContentLoaded handlers and global functions)\n let deleteModalInstance = null;\n let quotaModalInstance = null;\n let ownerModalInstance = null;\n let detailsModalInstance = null;\n let cachedUsers = null;\n\n document.addEventListener('DOMContentLoaded', function() {\n // Add click handlers to pagination links\n document.querySelectorAll('.pagination-link').forEach(link => {\n link.addEventListener('click', function(e) {\n e.preventDefault();\n const page = this.getAttribute('data-page');\n goToPage(page);\n });\n });\n\n // Initialize modal instances once (reuse with show/hide)\n deleteModalInstance = new bootstrap.Modal(document.getElementById('deleteBucketModal'));\n quotaModalInstance = new bootstrap.Modal(document.getElementById('manageQuotaModal'));\n ownerModalInstance = new bootstrap.Modal(document.getElementById('manageOwnerModal'));\n detailsModalInstance = new bootstrap.Modal(document.getElementById('bucketDetailsModal'));\n\n const quotaCheckbox = document.getElementById('enableQuota');\n const quotaSettings = document.getElementById('quotaSettings');\n const versioningCheckbox = document.getElementById('enableVersioning');\n const objectLockCheckbox = document.getElementById('enableObjectLock');\n const objectLockSettings = document.getElementById('objectLockSettings');\n const setDefaultRetentionCheckbox = document.getElementById('setDefaultRetention');\n const defaultRetentionSettings = document.getElementById('defaultRetentionSettings');\n const createBucketForm = document.getElementById('createBucketForm');\n\n // Toggle quota settings\n quotaCheckbox.addEventListener('change', function() {\n quotaSettings.style.display = this.checked ? 'block' : 'none';\n });\n\n // Toggle object lock settings and automatically enable versioning\n objectLockCheckbox.addEventListener('change', function() {\n objectLockSettings.style.display = this.checked ? 'block' : 'none';\n if (this.checked) {\n versioningCheckbox.checked = true;\n versioningCheckbox.disabled = true;\n } else {\n versioningCheckbox.disabled = false;\n // Reset default retention settings when object lock is disabled\n setDefaultRetentionCheckbox.checked = false;\n defaultRetentionSettings.style.display = 'none';\n }\n });\n\n // Toggle default retention settings\n setDefaultRetentionCheckbox.addEventListener('change', function() {\n defaultRetentionSettings.style.display = this.checked ? 'block' : 'none';\n });\n\n // Populate owner dropdown when create bucket modal opens\n document.getElementById('createBucketModal').addEventListener('show.bs.modal', async function() {\n const ownerSelect = document.getElementById('bucketOwner');\n \n // Only fetch if not already populated\n if (ownerSelect.options.length <= 1) {\n try {\n const response = await fetch(basePath('/api/users'));\n const data = await response.json();\n const users = data.users || [];\n \n users.forEach(user => {\n const option = document.createElement('option');\n option.value = user.username;\n option.textContent = user.username;\n ownerSelect.appendChild(option);\n });\n } catch (error) {\n console.error('Error fetching users for owner dropdown:', error);\n // Reset to default state on error - user can still create bucket without owner\n ownerSelect.innerHTML = '<option value=\"\">No owner (admin-only access)</option>';\n ownerSelect.selectedIndex = 0;\n }\n }\n });\n\n // Handle form submission\n createBucketForm.addEventListener('submit', function(e) {\n e.preventDefault();\n \n const formData = new FormData(this);\n const data = {\n name: formData.get('name'),\n owner: formData.get('owner') || '',\n region: formData.get('region') || '',\n quota_size: quotaCheckbox.checked ? parseInt(formData.get('quota_size')) || 0 : 0,\n quota_unit: formData.get('quota_unit') || 'MB',\n quota_enabled: quotaCheckbox.checked,\n versioning_enabled: versioningCheckbox.checked,\n object_lock_enabled: objectLockCheckbox.checked,\n object_lock_mode: formData.get('object_lock_mode') || 'GOVERNANCE',\n set_default_retention: setDefaultRetentionCheckbox.checked,\n object_lock_duration: setDefaultRetentionCheckbox.checked ? parseInt(formData.get('object_lock_duration')) || 30 : 0\n };\n\n // Validate object lock settings\n if (data.object_lock_enabled && data.set_default_retention && data.object_lock_duration <= 0) {\n alert('Please enter a valid retention duration for object lock.');\n return;\n }\n\n fetch(basePath('/api/s3/buckets'), {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify(data)\n })\n .then(response => response.json())\n .then(data => {\n if (data.error) {\n alert('Error creating bucket: ' + data.error);\n } else {\n alert('Bucket created successfully!');\n // Properly close the modal before reloading\n const createModal = bootstrap.Modal.getInstance(document.getElementById('createBucketModal'));\n if (createModal) {\n createModal.hide();\n }\n setTimeout(() => location.reload(), 500);\n }\n })\n .catch(error => {\n console.error('Error:', error);\n alert('Error creating bucket: ' + error.message);\n });\n });\n\n // Handle delete bucket\n const deleteForm = document.getElementById('deleteBucketModal');\n document.querySelectorAll('.delete-bucket-btn').forEach(button => {\n button.addEventListener('click', function() {\n const bucketName = this.dataset.bucketName;\n document.getElementById('deleteBucketName').textContent = bucketName;\n // Store bucket name on modal element instead of global window property\n deleteForm.dataset.bucketName = bucketName;\n deleteModalInstance.show();\n });\n });\n\n // Handle quota management\n const quotaForm = document.getElementById('quotaForm');\n document.querySelectorAll('.quota-btn').forEach(button => {\n button.addEventListener('click', function() {\n const bucketName = this.dataset.bucketName;\n const currentQuota = parseInt(this.dataset.currentQuota);\n const quotaEnabled = this.dataset.quotaEnabled === 'true';\n \n document.getElementById('quotaBucketName').value = bucketName;\n document.getElementById('quotaEnabled').checked = quotaEnabled;\n document.getElementById('quotaSizeMB').value = currentQuota;\n \n // Toggle quota size settings\n document.getElementById('quotaSizeSettings').style.display = quotaEnabled ? 'block' : 'none';\n \n // Store bucket name on form element instead of global window property\n quotaForm.dataset.bucketName = bucketName;\n quotaModalInstance.show();\n });\n });\n\n // Add event listener to properly dispose of quota modal when hidden\n document.getElementById('manageQuotaModal').addEventListener('hidden.bs.modal', function() {\n if (quotaModalInstance) {\n quotaModalInstance.dispose();\n quotaModalInstance = null;\n }\n // Force remove any remaining backdrops\n document.querySelectorAll('.modal-backdrop').forEach(backdrop => {\n backdrop.remove();\n });\n // Ensure body classes are removed\n document.body.classList.remove('modal-open');\n document.body.style.removeProperty('padding-right');\n });\n\n // Handle quota form submission\n document.getElementById('quotaForm').addEventListener('submit', function(e) {\n e.preventDefault();\n \n const bucketName = this.dataset.bucketName;\n if (!bucketName) return;\n\n const formData = new FormData(this);\n const enabled = document.getElementById('quotaEnabled').checked;\n const data = {\n quota_size: enabled ? parseInt(formData.get('quota_size')) || 0 : 0,\n quota_unit: formData.get('quota_unit') || 'MB',\n quota_enabled: enabled\n };\n\n fetch(basePath(`/api/s3/buckets/${bucketName}/quota`), {\n method: 'PUT',\n headers: {\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify(data)\n })\n .then(response => response.json())\n .then(data => {\n if (data.error) {\n alert('Error updating quota: ' + data.error);\n } else {\n alert('Quota updated successfully!');\n // Properly close the modal before reloading\n if (quotaModalInstance) {\n quotaModalInstance.hide();\n }\n setTimeout(() => location.reload(), 500);\n }\n })\n .catch(error => {\n console.error('Error:', error);\n alert('Error updating quota: ' + error.message);\n });\n });\n\n // Handle quota enabled checkbox\n document.getElementById('quotaEnabled').addEventListener('change', function() {\n document.getElementById('quotaSizeSettings').style.display = this.checked ? 'block' : 'none';\n });\n\n // Handle owner management\n const ownerForm = document.getElementById('ownerForm');\n document.querySelectorAll('.owner-btn').forEach(button => {\n button.addEventListener('click', async function() {\n const bucketName = this.dataset.bucketName;\n const currentOwner = this.dataset.currentOwner || '';\n \n document.getElementById('ownerBucketName').value = bucketName;\n // Store bucket name on form element instead of global window property\n ownerForm.dataset.bucketName = bucketName;\n \n // Show loading spinner\n document.getElementById('ownerLoadingSpinner').style.display = 'block';\n document.getElementById('bucketOwnerSelect').disabled = true;\n \n ownerModalInstance.show();\n \n // Fetch users if not cached\n try {\n if (!cachedUsers) {\n const response = await fetch(basePath('/api/users'));\n const data = await response.json();\n cachedUsers = data.users || [];\n }\n \n // Populate the select dropdown\n const select = document.getElementById('bucketOwnerSelect');\n select.innerHTML = '<option value=\"\">No owner (admin-only access)</option>';\n \n cachedUsers.forEach(user => {\n const option = document.createElement('option');\n option.value = user.username;\n option.textContent = user.username;\n if (user.username === currentOwner) {\n option.selected = true;\n }\n select.appendChild(option);\n });\n \n select.disabled = false;\n } catch (error) {\n console.error('Error fetching users:', error);\n alert('Error loading users: ' + error.message);\n // Re-enable select and reset to default on error\n const select = document.getElementById('bucketOwnerSelect');\n select.innerHTML = '<option value=\"\">No owner (admin-only access)</option>';\n select.selectedIndex = 0;\n select.disabled = false;\n } finally {\n document.getElementById('ownerLoadingSpinner').style.display = 'none';\n }\n });\n });\n\n // Handle owner form submission\n document.getElementById('ownerForm').addEventListener('submit', function(e) {\n e.preventDefault();\n \n const bucketName = this.dataset.bucketName;\n if (!bucketName) return;\n\n const owner = document.getElementById('bucketOwnerSelect').value;\n const data = { owner: owner };\n\n fetch(basePath(`/api/s3/buckets/${bucketName}/owner`), {\n method: 'PUT',\n headers: {\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify(data)\n })\n .then(response => response.json())\n .then(data => {\n if (data.error) {\n alert('Error updating owner: ' + data.error);\n } else {\n alert('Bucket owner updated successfully!');\n // Properly close the modal before reloading\n if (ownerModalInstance) {\n ownerModalInstance.hide();\n }\n setTimeout(() => location.reload(), 500);\n }\n })\n .catch(error => {\n console.error('Error:', error);\n alert('Error updating owner: ' + error.message);\n });\n });\n\n // Handle view details button\n document.querySelectorAll('.view-details-btn').forEach(button => {\n button.addEventListener('click', function() {\n const bucketName = this.dataset.bucketName;\n \n // Update modal title\n document.getElementById('bucketDetailsModalLabel').innerHTML = \n '<i class=\"fas fa-cube me-2\"></i>Bucket Details - ' + bucketName;\n \n // Show loading spinner\n document.getElementById('bucketDetailsContent').innerHTML = \n '<div class=\"text-center py-4\">' +\n '<div class=\"spinner-border text-primary\" role=\"status\">' +\n '<span class=\"visually-hidden\">Loading...</span>' +\n '<\\\\/div>' +\n '<div class=\"mt-2\">Loading bucket details...</div>' +\n '<\\\\/div>';\n \n detailsModalInstance.show();\n \n // Fetch bucket details\n fetch(basePath('/api/s3/buckets/' + bucketName))\n .then(response => response.json())\n .then(data => {\n if (data.error) {\n document.getElementById('bucketDetailsContent').innerHTML = \n '<div class=\"alert alert-danger\">' +\n '<i class=\"fas fa-exclamation-triangle me-2\"></i>' +\n 'Error loading bucket details: ' + data.error +\n '<\\\\/div>';\n } else {\n displayBucketDetails(data);\n }\n })\n .catch(error => {\n console.error('Error fetching bucket details:', error);\n document.getElementById('bucketDetailsContent').innerHTML = \n '<div class=\"alert alert-danger\">' +\n '<i class=\"fas fa-exclamation-triangle me-2\"></i>' +\n 'Error loading bucket details: ' + error.message +\n '<\\\\/div>';\n });\n });\n });\n });\n\n function deleteBucket() {\n const bucketName = document.getElementById('deleteBucketModal').dataset.bucketName;\n if (!bucketName) return;\n\n fetch(basePath(`/api/s3/buckets/${bucketName}`), {\n method: 'DELETE'\n })\n .then(response => response.json())\n .then(data => {\n if (data.error) {\n alert('Error deleting bucket: ' + data.error);\n } else {\n alert('Bucket deleted successfully!');\n // Properly close the modal before reloading\n if (deleteModalInstance) {\n deleteModalInstance.hide();\n }\n setTimeout(() => location.reload(), 500);\n }\n })\n .catch(error => {\n console.error('Error:', error);\n alert('Error deleting bucket: ' + error.message);\n });\n }\n\nfunction displayBucketDetails(data) {\n const bucket = data.bucket;\n\n function escapeHtml(v) {\n return String(v ?? '')\n .replace(/&/g, '&')\n .replace(/</g, '<')\n .replace(/>/g, '>')\n .replace(/\"/g, '"')\n .replace(/'/g, ''');\n }\n\n function formatBytes(bytes) {\n if (bytes === 0) return '0 Bytes';\n const k = 1024;\n const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB'];\n const i = Math.floor(Math.log(bytes) / Math.log(k));\n return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];\n }\n\n function formatDate(dateString) {\n const date = new Date(dateString);\n return date.toLocaleString();\n }\n\n let ownerHtml = '<span class=\"text-muted\">No owner (admin-only)</span>';\n if (bucket.owner) {\n ownerHtml = '<span class=\"badge bg-info\"><i class=\"fas fa-user me-1\"></i>' + escapeHtml(bucket.owner) + '</span>';\n }\n\n let usageHtml = '';\n if (bucket.physical_size > 0 && bucket.logical_size > 0 && bucket.physical_size > bucket.logical_size) {\n const overhead = (bucket.physical_size / bucket.logical_size).toFixed(1);\n usageHtml = '<br><small class=\"text-muted\">' + overhead + 'x overhead<\\/small>';\n }\n\n let quotaHtml = '<span class=\"badge bg-secondary\">Disabled</span>';\n if (bucket.quota_enabled) {\n quotaHtml = '<span class=\"badge bg-success\">' + formatBytes(bucket.quota) + '</span>';\n }\n\n let versioningHtml = '<span class=\"text-muted\">Not configured</span>';\n if (bucket.versioning_status === 'Enabled') {\n versioningHtml = '<span class=\"badge bg-success\"><i class=\"fas fa-check me-1\"></i>Enabled</span>';\n } else if (bucket.versioning_status === 'Suspended') {\n versioningHtml = '<span class=\"badge bg-warning\"><i class=\"fas fa-pause me-1\"></i>Suspended</span>';\n }\n\n let objectLockHtml = '<span class=\"text-muted\">Not configured</span>';\n if (bucket.object_lock_enabled) {\n let details = '';\n if (bucket.object_lock_mode && bucket.object_lock_duration > 0) {\n details = '<br><small class=\"text-muted\">' + escapeHtml(bucket.object_lock_mode) + ' • ' + bucket.object_lock_duration + ' days<\\/small>';\n }\n objectLockHtml = '<span class=\"badge bg-warning\"><i class=\"fas fa-lock me-1\"></i>Enabled</span>' + details;\n }\n\n const rows = [\n '<div class=\"row\">',\n '<div class=\"col-md-6\">',\n '<h6><i class=\"fas fa-info-circle me-2\"></i>Bucket Information</h6>',\n '<table class=\"table table-sm\">',\n '<tr><td><strong>Name:</strong></td><td>' + escapeHtml(bucket.name) + '<\\/td><\\/tr>',\n '<tr><td><strong>Owner:</strong></td><td>' + ownerHtml + '<\\/td><\\/tr>',\n '<tr><td><strong>Created:</strong></td><td>' + formatDate(bucket.created_at) + '<\\/td><\\/tr>',\n '<tr><td><strong>Last Modified:</strong></td><td>' + formatDate(bucket.last_modified) + '<\\/td><\\/tr>',\n '<tr><td><strong>Logical Size:</strong></td><td>' + formatBytes(bucket.logical_size) + '<\\/td><\\/tr>',\n '<tr><td><strong>Physical Size:</strong></td><td>' + formatBytes(bucket.physical_size) + usageHtml + '<\\/td><\\/tr>',\n '<\\/table>',\n '<\\/div>',\n '<div class=\"col-md-6\">',\n '<h6><i class=\"fas fa-cogs me-2\"></i>Configuration</h6>',\n '<table class=\"table table-sm\">',\n '<tr><td><strong>Quota:</strong></td><td>' + quotaHtml + '<\\/td><\\/tr>',\n '<tr><td><strong>Versioning:</strong></td><td>' + versioningHtml + '<\\/td><\\/tr>',\n '<tr><td><strong>Object Lock:</strong></td><td>' + objectLockHtml + '<\\/td><\\/tr>',\n '<\\/table>',\n '<\\/div>',\n '<\\/div>'\n ];\n\n document.getElementById('bucketDetailsContent').innerHTML = rows.join('');\n}\n\n function goToPage(page) {\n const url = new URL(window.location);\n url.searchParams.set('page', page);\n window.location.href = url.toString();\n }\n\n function changePageSize() {\n const pageSize = document.getElementById('pageSizeSelect').value;\n const url = new URL(window.location);\n url.searchParams.set('pageSize', pageSize);\n url.searchParams.set('page', '1');\n window.location.href = url.toString();\n }\n\n function sortTable(column) {\n const url = new URL(window.location);\n const currentSort = url.searchParams.get('sortBy');\n const currentOrder = url.searchParams.get('sortOrder') || 'asc';\n\n let newOrder = 'asc';\n if (currentSort === column && currentOrder === 'asc') {\n newOrder = 'desc';\n }\n\n url.searchParams.set('sortBy', column);\n url.searchParams.set('sortOrder', newOrder);\n url.searchParams.set('page', '1');\n window.location.href = url.toString();\n }\n\n function exportBucketList() {\n // RFC 4180 compliant CSV escaping: escape double quotes by doubling them\n function escapeCsvField(value) {\n const str = String(value ?? '');\n if (str.includes(',') || str.includes('\"') || str.includes('\\n') || str.includes('\\r')) {\n return '\"' + str.replace(/\"/g, '\"\"') + '\"';\n }\n return '\"' + str + '\"';\n }\n\n function formatBytes(bytes) {\n if (bytes === 0) return '0 Bytes';\n const k = 1024;\n const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB'];\n const i = Math.floor(Math.log(bytes) / Math.log(k));\n return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];\n }\n\n // Fetch all buckets from the API (not just the current page)\n fetch(basePath('/api/s3/buckets'))\n .then(response => response.json())\n .then(data => {\n if (data.error) {\n alert('Error exporting buckets: ' + data.error);\n return;\n }\n\n const buckets = data.buckets || [];\n const csvContent = \"data:text/csv;charset=utf-8,\" +\n \"Name,Owner,Logical Size,Physical Size,Created,Quota,Versioning,Object Lock\\n\" +\n buckets.map(b => [\n escapeCsvField(b.name),\n escapeCsvField(b.owner),\n escapeCsvField(formatBytes(b.logical_size)),\n escapeCsvField(formatBytes(b.physical_size)),\n escapeCsvField(b.created_at),\n escapeCsvField(b.quota_enabled ? formatBytes(b.quota) : 'No quota'),\n escapeCsvField(b.versioning_status || 'Not configured'),\n escapeCsvField(b.object_lock_enabled ? 'Enabled' : 'Not configured')\n ].join(',')).join(\"\\n\");\n\n const encodedUri = encodeURI(csvContent);\n const link = document.createElement(\"a\");\n link.setAttribute(\"href\", encodedUri);\n link.setAttribute(\"download\", \"buckets.csv\");\n document.body.appendChild(link);\n link.click();\n document.body.removeChild(link);\n })\n .catch(error => {\n console.error('Error:', error);\n alert('Error exporting buckets: ' + error.message);\n });\n }\n </script>")if templ_7745c5c3_Err != nil {return templ_7745c5c3_Err}diff --git a/weed/admin/view/app/service_accounts.templ b/weed/admin/view/app/service_accounts.templindex 4696c63b97..2fb18e187b 100644--- a/weed/admin/view/app/service_accounts.templ+++ b/weed/admin/view/app/service_accounts.templ@@ -336,7 +336,7 @@ templ ServiceAccounts(data dash.ServiceAccountsData) {async function showSADetails(id) {try {const encodedId = encodeURIComponent(id);- const response = await fetch(`/api/service-accounts/${encodedId}`);+ const response = await fetch(basePath(`/api/service-accounts/${encodedId}`));if (response.ok) {const sa = await response.json();document.getElementById('saDetailsContent').innerHTML = createSADetailsContent(sa);@@ -355,7 +355,7 @@ templ ServiceAccounts(data dash.ServiceAccountsData) {const newStatus = currentStatus === 'Active' ? 'Inactive' : 'Active';try {const encodedId = encodeURIComponent(id);- const response = await fetch(`/api/service-accounts/${encodedId}`, {+ const response = await fetch(basePath(`/api/service-accounts/${encodedId}`), {method: 'PUT',headers: { 'Content-Type': 'application/json' },body: JSON.stringify({ status: newStatus })@@ -378,7 +378,7 @@ templ ServiceAccounts(data dash.ServiceAccountsData) {showDeleteConfirm(id, async function() {try {const encodedId = encodeURIComponent(id);- const response = await fetch(`/api/service-accounts/${encodedId}`, {+ const response = await fetch(basePath(`/api/service-accounts/${encodedId}`), {method: 'DELETE'});@@ -427,7 +427,7 @@ templ ServiceAccounts(data dash.ServiceAccountsData) {}try {- const response = await fetch('/api/service-accounts', {+ const response = await fetch(basePath('/api/service-accounts'), {method: 'POST',headers: { 'Content-Type': 'application/json' },body: JSON.stringify(saData)diff --git a/weed/admin/view/app/service_accounts_templ.go b/weed/admin/view/app/service_accounts_templ.goindex 68eda9fc5c..323102d858 100644--- a/weed/admin/view/app/service_accounts_templ.go+++ b/weed/admin/view/app/service_accounts_templ.go@@ -1,6 +1,6 @@// Code generated by templ - DO NOT EDIT.-// templ: version: v0.3.977+// templ: version: v0.3.1001package app//lint:file-ignore SA4006 This context is only used if a nested component is present.@@ -41,7 +41,7 @@ func ServiceAccounts(data dash.ServiceAccountsData) templ.Component {var templ_7745c5c3_Var2 stringtempl_7745c5c3_Var2, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%d", data.TotalAccounts))if templ_7745c5c3_Err != nil {- return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/service_accounts.templ`, Line: 38, Col: 74}+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/service_accounts.templ`, Line: 38, Col: 74}}_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var2))if templ_7745c5c3_Err != nil {@@ -54,7 +54,7 @@ func ServiceAccounts(data dash.ServiceAccountsData) templ.Component {var templ_7745c5c3_Var3 stringtempl_7745c5c3_Var3, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%d", data.ActiveAccounts))if templ_7745c5c3_Err != nil {- return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/service_accounts.templ`, Line: 58, Col: 75}+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/service_accounts.templ`, Line: 58, Col: 75}}_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var3))if templ_7745c5c3_Err != nil {@@ -67,7 +67,7 @@ func ServiceAccounts(data dash.ServiceAccountsData) templ.Component {var templ_7745c5c3_Var4 stringtempl_7745c5c3_Var4, templ_7745c5c3_Err = templ.JoinStringErrs(data.LastUpdated.Format("15:04"))if templ_7745c5c3_Err != nil {- return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/service_accounts.templ`, Line: 78, Col: 69}+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/service_accounts.templ`, Line: 78, Col: 69}}_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var4))if templ_7745c5c3_Err != nil {@@ -85,7 +85,7 @@ func ServiceAccounts(data dash.ServiceAccountsData) templ.Component {var templ_7745c5c3_Var5 stringtempl_7745c5c3_Var5, templ_7745c5c3_Err = templ.JoinStringErrs(sa.ID)if templ_7745c5c3_Err != nil {- return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/service_accounts.templ`, Line: 118, Col: 64}+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/service_accounts.templ`, Line: 118, Col: 64}}_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var5))if templ_7745c5c3_Err != nil {@@ -98,7 +98,7 @@ func ServiceAccounts(data dash.ServiceAccountsData) templ.Component {var templ_7745c5c3_Var6 stringtempl_7745c5c3_Var6, templ_7745c5c3_Err = templ.JoinStringErrs(sa.ParentUser)if templ_7745c5c3_Err != nil {- return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/service_accounts.templ`, Line: 123, Col: 62}+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/service_accounts.templ`, Line: 123, Col: 62}}_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var6))if templ_7745c5c3_Err != nil {@@ -111,7 +111,7 @@ func ServiceAccounts(data dash.ServiceAccountsData) templ.Component {var templ_7745c5c3_Var7 stringtempl_7745c5c3_Var7, templ_7745c5c3_Err = templ.JoinStringErrs(sa.AccessKeyId)if templ_7745c5c3_Err != nil {- return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/service_accounts.templ`, Line: 126, Col: 88}+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/service_accounts.templ`, Line: 126, Col: 88}}_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var7))if templ_7745c5c3_Err != nil {@@ -139,7 +139,7 @@ func ServiceAccounts(data dash.ServiceAccountsData) templ.Component {var templ_7745c5c3_Var8 stringtempl_7745c5c3_Var8, templ_7745c5c3_Err = templ.JoinStringErrs(sa.CreateDate.Format("2006-01-02"))if templ_7745c5c3_Err != nil {- return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/service_accounts.templ`, Line: 135, Col: 83}+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/service_accounts.templ`, Line: 135, Col: 83}}_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var8))if templ_7745c5c3_Err != nil {@@ -152,7 +152,7 @@ func ServiceAccounts(data dash.ServiceAccountsData) templ.Component {var templ_7745c5c3_Var9 stringtempl_7745c5c3_Var9, templ_7745c5c3_Err = templ.JoinStringErrs(sa.ID)if templ_7745c5c3_Err != nil {- return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/service_accounts.templ`, Line: 139, Col: 108}+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/service_accounts.templ`, Line: 139, Col: 108}}_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var9))if templ_7745c5c3_Err != nil {@@ -165,7 +165,7 @@ func ServiceAccounts(data dash.ServiceAccountsData) templ.Component {var templ_7745c5c3_Var10 stringtempl_7745c5c3_Var10, templ_7745c5c3_Err = templ.JoinStringErrs(sa.ID)if templ_7745c5c3_Err != nil {- return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/service_accounts.templ`, Line: 143, Col: 109}+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/service_accounts.templ`, Line: 143, Col: 109}}_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var10))if templ_7745c5c3_Err != nil {@@ -178,7 +178,7 @@ func ServiceAccounts(data dash.ServiceAccountsData) templ.Component {var templ_7745c5c3_Var11 stringtempl_7745c5c3_Var11, templ_7745c5c3_Err = templ.JoinStringErrs(sa.Status)if templ_7745c5c3_Err != nil {- return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/service_accounts.templ`, Line: 143, Col: 143}+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/service_accounts.templ`, Line: 143, Col: 143}}_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var11))if templ_7745c5c3_Err != nil {@@ -206,7 +206,7 @@ func ServiceAccounts(data dash.ServiceAccountsData) templ.Component {var templ_7745c5c3_Var12 stringtempl_7745c5c3_Var12, templ_7745c5c3_Err = templ.JoinStringErrs(sa.ID)if templ_7745c5c3_Err != nil {- return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/service_accounts.templ`, Line: 151, Col: 102}+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/service_accounts.templ`, Line: 151, Col: 102}}_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var12))if templ_7745c5c3_Err != nil {@@ -230,7 +230,7 @@ func ServiceAccounts(data dash.ServiceAccountsData) templ.Component {var templ_7745c5c3_Var13 stringtempl_7745c5c3_Var13, templ_7745c5c3_Err = templ.JoinStringErrs(data.LastUpdated.Format("2006-01-02 15:04:05"))if templ_7745c5c3_Err != nil {- return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/service_accounts.templ`, Line: 182, Col: 81}+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/service_accounts.templ`, Line: 182, Col: 81}}_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var13))if templ_7745c5c3_Err != nil {@@ -248,7 +248,7 @@ func ServiceAccounts(data dash.ServiceAccountsData) templ.Component {var templ_7745c5c3_Var14 stringtempl_7745c5c3_Var14, templ_7745c5c3_Err = templ.JoinStringErrs(user)if templ_7745c5c3_Err != nil {- return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/service_accounts.templ`, Line: 205, Col: 56}+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/service_accounts.templ`, Line: 205, Col: 56}}_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var14))if templ_7745c5c3_Err != nil {@@ -261,7 +261,7 @@ func ServiceAccounts(data dash.ServiceAccountsData) templ.Component {var templ_7745c5c3_Var15 stringtempl_7745c5c3_Var15, templ_7745c5c3_Err = templ.JoinStringErrs(user)if templ_7745c5c3_Err != nil {- return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/service_accounts.templ`, Line: 205, Col: 65}+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/service_accounts.templ`, Line: 205, Col: 65}}_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var15))if templ_7745c5c3_Err != nil {@@ -272,7 +272,7 @@ func ServiceAccounts(data dash.ServiceAccountsData) templ.Component {return templ_7745c5c3_Err}}- templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 26, "</select> <small class=\"form-text text-muted\">The service account will inherit permissions from this user</small></div><div class=\"mb-3\"><label for=\"description\" class=\"form-label\">Description</label> <textarea class=\"form-control\" id=\"description\" name=\"description\" rows=\"2\" placeholder=\"What is this service account used for?\"></textarea></div><div class=\"mb-3\"><label for=\"expiration\" class=\"form-label\">Expiration (optional)</label> <input type=\"datetime-local\" class=\"form-control\" id=\"expiration\" name=\"expiration\"> <small class=\"form-text text-muted\">Leave empty for no expiration</small></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=\"handleCreateServiceAccount()\">Create</button></div></div></div></div><!-- Service Account Details Modal --><div class=\"modal fade\" id=\"saDetailsModal\" 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-robot me-2\"></i>Service Account Details</h5><button type=\"button\" class=\"btn-close\" data-bs-dismiss=\"modal\"></button></div><div class=\"modal-body\" id=\"saDetailsContent\"><!-- 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><!-- Credentials Display Modal --><div class=\"modal fade\" id=\"credentialsModal\" tabindex=\"-1\" role=\"dialog\" data-bs-backdrop=\"static\" data-bs-keyboard=\"false\"><div class=\"modal-dialog modal-lg\" role=\"document\"><div class=\"modal-content\"><div class=\"modal-header bg-success text-white\"><h5 class=\"modal-title\"><i class=\"fas fa-check-circle me-2\"></i>Service Account Created Successfully</h5></div><div class=\"modal-body\"><div class=\"alert alert-warning\"><i class=\"fas fa-exclamation-triangle me-2\"></i> <strong>Important:</strong> This is the only time you will see the secret access key. Please save it securely.</div><div class=\"mb-4\"><h6 class=\"text-muted mb-3\">AWS CLI Configuration</h6><p class=\"text-muted small\">Use these credentials to configure AWS CLI or SDKs:</p><div class=\"mb-3\"><label class=\"form-label fw-bold\">AWS_ACCESS_KEY_ID</label><div class=\"input-group\"><input type=\"text\" class=\"form-control font-monospace\" id=\"displayAccessKey\" readonly> <button class=\"btn btn-outline-secondary\" type=\"button\" onclick=\"copyCredentialToClipboard(this, 'displayAccessKey')\"><i class=\"fas fa-copy\"></i> Copy</button></div></div><div class=\"mb-3\"><label class=\"form-label fw-bold\">AWS_SECRET_ACCESS_KEY</label><div class=\"input-group\"><input type=\"text\" class=\"form-control font-monospace\" id=\"displaySecretKey\" readonly> <button class=\"btn btn-outline-secondary\" type=\"button\" onclick=\"copyCredentialToClipboard(this, 'displaySecretKey')\"><i class=\"fas fa-copy\"></i> Copy</button></div></div></div><div class=\"bg-light p-3 rounded\"><h6 class=\"text-muted mb-2\">Example AWS CLI Usage:</h6><div class=\"font-monospace small\"><div>export AWS_ACCESS_KEY_ID=<span id=\"exampleAccessKey\"></span></div><div>export AWS_SECRET_ACCESS_KEY=<span id=\"exampleSecretKey\"></span></div><div>export AWS_ENDPOINT_URL=http://localhost:8333</div><div class=\"mt-2\"># List buckets</div><div>aws s3 ls</div><div class=\"mt-2\"># Upload a file</div><div>aws s3 cp myfile.txt s3://mybucket/</div></div></div></div><div class=\"modal-footer\"><button type=\"button\" class=\"btn btn-primary\" onclick=\"closeCredentialsModal()\"><i class=\"fas fa-check me-1\"></i>I have saved the credentials</button></div></div></div></div><!-- JavaScript for service account management --><script>\n document.addEventListener('DOMContentLoaded', function() {\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 saId = button.getAttribute('data-sa-id');\n \n switch (action) {\n case 'show-sa-details':\n showSADetails(saId);\n break;\n case 'toggle-sa-status':\n toggleSAStatus(saId, button.getAttribute('data-current-status'));\n break;\n case 'delete-sa':\n deleteSA(saId);\n break;\n }\n });\n });\n\n async function showSADetails(id) {\n try {\n const encodedId = encodeURIComponent(id);\n const response = await fetch(`/api/service-accounts/${encodedId}`);\n if (response.ok) {\n const sa = await response.json();\n document.getElementById('saDetailsContent').innerHTML = createSADetailsContent(sa);\n const modal = new bootstrap.Modal(document.getElementById('saDetailsModal'));\n modal.show();\n } else {\n showErrorMessage('Failed to load service account details');\n }\n } catch (error) {\n console.error('Error loading service account details:', error);\n showErrorMessage('Failed to load service account details');\n }\n }\n\n async function toggleSAStatus(id, currentStatus) {\n const newStatus = currentStatus === 'Active' ? 'Inactive' : 'Active';\n try {\n const encodedId = encodeURIComponent(id);\n const response = await fetch(`/api/service-accounts/${encodedId}`, {\n method: 'PUT',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ status: newStatus })\n });\n \n if (response.ok) {\n showSuccessMessage(`Service account ${newStatus === 'Active' ? 'activated' : 'deactivated'}`);\n setTimeout(() => window.location.reload(), 1000);\n } else {\n const error = await response.json();\n showErrorMessage('Failed to update status: ' + (error.error || 'Unknown error'));\n }\n } catch (error) {\n console.error('Error updating status:', error);\n showErrorMessage('Failed to update status: ' + error.message);\n }\n }\n\n async function deleteSA(id) {\n showDeleteConfirm(id, async function() {\n try {\n const encodedId = encodeURIComponent(id);\n const response = await fetch(`/api/service-accounts/${encodedId}`, {\n method: 'DELETE'\n });\n \n if (response.ok) {\n showSuccessMessage('Service account deleted successfully');\n setTimeout(() => window.location.reload(), 1000);\n } else {\n const error = await response.json();\n showErrorMessage('Failed to delete: ' + (error.error || 'Unknown error'));\n }\n } catch (error) {\n console.error('Error deleting service account:', error);\n showErrorMessage('Failed to delete: ' + error.message);\n }\n }, 'Are you sure you want to delete this service account? This action cannot be undone.');\n }\n\n async function handleCreateServiceAccount() {\n const form = document.getElementById('createSAForm');\n const formData = new FormData(form);\n \n const saData = {\n parent_user: formData.get('parent_user'),\n description: formData.get('description')\n };\n \n // Handle expiration if set\n const expiration = formData.get('expiration');\n if (expiration) {\n // Validate the date before using it\n const date = new Date(expiration);\n const now = new Date();\n \n if (isNaN(date.getTime())) {\n showErrorMessage('Invalid expiration date format');\n return;\n }\n \n // Ensure expiration is in the future\n if (date <= now) {\n showErrorMessage('Expiration date must be in the future');\n return;\n }\n \n saData.expiration = date.toISOString();\n }\n \n try {\n const response = await fetch('/api/service-accounts', {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify(saData)\n });\n \n if (response.ok) {\n const result = await response.json();\n \n // Hide create modal\n const createModal = bootstrap.Modal.getInstance(document.getElementById('createServiceAccountModal'));\n createModal.hide();\n form.reset();\n \n // Show credentials if returned\n if (result.service_account && result.service_account.secret_access_key) {\n showCredentials(result.service_account);\n } else {\n showSuccessMessage('Service account created successfully');\n setTimeout(() => window.location.reload(), 1000);\n }\n } else {\n const error = await response.json();\n showErrorMessage('Failed to create service account: ' + (error.error || 'Unknown error'));\n }\n } catch (error) {\n console.error('Error creating service account:', error);\n showErrorMessage('Failed to create service account: ' + error.message);\n }\n }\n\n function showCredentials(serviceAccount) {\n // Populate the credentials modal\n document.getElementById('displayAccessKey').value = serviceAccount.access_key_id;\n document.getElementById('displaySecretKey').value = serviceAccount.secret_access_key;\n document.getElementById('exampleAccessKey').textContent = serviceAccount.access_key_id;\n document.getElementById('exampleSecretKey').textContent = serviceAccount.secret_access_key;\n \n // Show the modal\n const credentialsModal = new bootstrap.Modal(document.getElementById('credentialsModal'));\n credentialsModal.show();\n }\n\n function closeCredentialsModal() {\n const modal = bootstrap.Modal.getInstance(document.getElementById('credentialsModal'));\n modal.hide();\n // Reload to show the new service account in the list\n setTimeout(() => window.location.reload(), 500);\n }\n\n function copyCredentialToClipboard(button, elementId) {\n const element = document.getElementById(elementId);\n const textToCopy = element.value;\n \n // Use modern Clipboard API if available\n if (navigator.clipboard && navigator.clipboard.writeText) {\n navigator.clipboard.writeText(textToCopy).then(() => {\n showSuccessMessage('Copied to clipboard!');\n }).catch(err => {\n console.warn('Clipboard API failed:', err);\n // Fallback\n fallbackCopyTextToClipboard(element);\n });\n } else {\n // Fallback for older browsers or non-secure contexts\n fallbackCopyTextToClipboard(element);\n }\n \n // Visual feedback\n const originalHTML = button.innerHTML;\n \n button.innerHTML = '<i class=\"fas fa-check\"></i>';\n button.classList.remove('btn-outline-secondary');\n button.classList.add('btn-success');\n \n setTimeout(() => {\n button.innerHTML = originalHTML;\n button.classList.remove('btn-success');\n button.classList.add('btn-outline-secondary');\n }, 1000);\n }\n\n function fallbackCopyTextToClipboard(element) {\n element.select();\n element.setSelectionRange(0, 99999); // For mobile devices\n \n try {\n const successful = document.execCommand('copy');\n if (successful) {\n showSuccessMessage('Copied to clipboard!');\n } else {\n showErrorMessage('Failed to copy to clipboard');\n }\n } catch (err) {\n console.error('Fallback copy failed:', err);\n showErrorMessage('Failed to copy to clipboard');\n }\n \n // Clear selection\n window.getSelection().removeAllRanges();\n }\n\n\n function createSADetailsContent(sa) {\n // Create DOM elements safely to prevent XSS\n const container = document.createElement('div');\n container.className = 'row';\n \n // Basic Information column\n const col1 = document.createElement('div');\n col1.className = 'col-md-6';\n \n const h6_1 = document.createElement('h6');\n h6_1.className = 'text-muted';\n h6_1.textContent = 'Basic Information';\n col1.appendChild(h6_1);\n \n const table1 = document.createElement('table');\n table1.className = 'table table-sm';\n \n // ID row\n const idRow = document.createElement('tr');\n idRow.innerHTML = '<td><strong>ID:</strong></td><td><code></code></td>';\n idRow.querySelector('code').textContent = sa.id || '';\n table1.appendChild(idRow);\n \n // Parent User row\n const parentRow = document.createElement('tr');\n parentRow.innerHTML = '<td><strong>Parent User:</strong></td><td></td>';\n parentRow.querySelectorAll('td')[1].textContent = sa.parent_user || '';\n table1.appendChild(parentRow);\n \n // Access Key row\n const keyRow = document.createElement('tr');\n keyRow.innerHTML = '<td><strong>Access Key:</strong></td><td><code></code></td>';\n keyRow.querySelector('code').textContent = sa.access_key_id || '';\n table1.appendChild(keyRow);\n \n // Status row\n const statusRow = document.createElement('tr');\n const statusTd1 = document.createElement('td');\n statusTd1.innerHTML = '<strong>Status:</strong>';\n const statusTd2 = document.createElement('td');\n const statusBadge = document.createElement('span');\n statusBadge.className = sa.status === 'Active' ? 'badge bg-success' : 'badge bg-secondary';\n statusBadge.textContent = sa.status || 'Unknown';\n statusTd2.appendChild(statusBadge);\n statusRow.appendChild(statusTd1);\n statusRow.appendChild(statusTd2);\n table1.appendChild(statusRow);\n \n col1.appendChild(table1);\n container.appendChild(col1);\n \n // Details column\n const col2 = document.createElement('div');\n col2.className = 'col-md-6';\n \n const h6_2 = document.createElement('h6');\n h6_2.className = 'text-muted';\n h6_2.textContent = 'Details';\n col2.appendChild(h6_2);\n \n const table2 = document.createElement('table');\n table2.className = 'table table-sm';\n \n // Description row\n const descRow = document.createElement('tr');\n descRow.innerHTML = '<td><strong>Description:</strong></td><td></td>';\n descRow.querySelectorAll('td')[1].textContent = sa.description || 'Not set';\n table2.appendChild(descRow);\n \n // Created row\n const createdRow = document.createElement('tr');\n createdRow.innerHTML = '<td><strong>Created:</strong></td><td></td>';\n try {\n createdRow.querySelectorAll('td')[1].textContent = new Date(sa.create_date).toLocaleString();\n } catch (e) {\n createdRow.querySelectorAll('td')[1].textContent = 'Invalid date';\n }\n table2.appendChild(createdRow);\n \n // Expiration row\n const expRow = document.createElement('tr');\n expRow.innerHTML = '<td><strong>Expires:</strong></td><td></td>';\n expRow.querySelectorAll('td')[1].textContent = sa.expiration || 'Never';\n table2.appendChild(expRow);\n \n col2.appendChild(table2);\n container.appendChild(col2);\n \n return container.outerHTML;\n }\n\n\n function showSuccessMessage(message) {\n showToast(message, 'success');\n }\n\n function showErrorMessage(message) {\n showToast(message, 'danger');\n }\n\n function showToast(message, type) {\n // Create toast container if it doesn't exist\n let toastContainer = document.getElementById('toastContainer');\n if (!toastContainer) {\n toastContainer = document.createElement('div');\n toastContainer.id = 'toastContainer';\n toastContainer.className = 'toast-container position-fixed top-0 end-0 p-3';\n toastContainer.style.zIndex = '9999';\n document.body.appendChild(toastContainer);\n }\n\n // Create toast element\n const toastId = 'toast-' + Date.now();\n const toastHTML = `\n <div id=\"${toastId}\" class=\"toast align-items-center text-white bg-${type} border-0\" role=\"alert\" aria-live=\"assertive\" aria-atomic=\"true\">\n <div class=\"d-flex\">\n <div class=\"toast-body\">\n ${escapeHtml(message)}\n </div>\n <button type=\"button\" class=\"btn-close btn-close-white me-2 m-auto\" data-bs-dismiss=\"toast\" aria-label=\"Close\"></button>\n </div>\n </div>\n `;\n \n toastContainer.insertAdjacentHTML('beforeend', toastHTML);\n const toastElement = document.getElementById(toastId);\n const toast = new bootstrap.Toast(toastElement, { autohide: true, delay: 5000 });\n toast.show();\n \n // Remove toast element after it's hidden\n toastElement.addEventListener('hidden.bs.toast', () => {\n toastElement.remove();\n });\n }\n\n function escapeHtml(text) {\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, 26, "</select> <small class=\"form-text text-muted\">The service account will inherit permissions from this user</small></div><div class=\"mb-3\"><label for=\"description\" class=\"form-label\">Description</label> <textarea class=\"form-control\" id=\"description\" name=\"description\" rows=\"2\" placeholder=\"What is this service account used for?\"></textarea></div><div class=\"mb-3\"><label for=\"expiration\" class=\"form-label\">Expiration (optional)</label> <input type=\"datetime-local\" class=\"form-control\" id=\"expiration\" name=\"expiration\"> <small class=\"form-text text-muted\">Leave empty for no expiration</small></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=\"handleCreateServiceAccount()\">Create</button></div></div></div></div><!-- Service Account Details Modal --><div class=\"modal fade\" id=\"saDetailsModal\" 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-robot me-2\"></i>Service Account Details</h5><button type=\"button\" class=\"btn-close\" data-bs-dismiss=\"modal\"></button></div><div class=\"modal-body\" id=\"saDetailsContent\"><!-- 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><!-- Credentials Display Modal --><div class=\"modal fade\" id=\"credentialsModal\" tabindex=\"-1\" role=\"dialog\" data-bs-backdrop=\"static\" data-bs-keyboard=\"false\"><div class=\"modal-dialog modal-lg\" role=\"document\"><div class=\"modal-content\"><div class=\"modal-header bg-success text-white\"><h5 class=\"modal-title\"><i class=\"fas fa-check-circle me-2\"></i>Service Account Created Successfully</h5></div><div class=\"modal-body\"><div class=\"alert alert-warning\"><i class=\"fas fa-exclamation-triangle me-2\"></i> <strong>Important:</strong> This is the only time you will see the secret access key. Please save it securely.</div><div class=\"mb-4\"><h6 class=\"text-muted mb-3\">AWS CLI Configuration</h6><p class=\"text-muted small\">Use these credentials to configure AWS CLI or SDKs:</p><div class=\"mb-3\"><label class=\"form-label fw-bold\">AWS_ACCESS_KEY_ID</label><div class=\"input-group\"><input type=\"text\" class=\"form-control font-monospace\" id=\"displayAccessKey\" readonly> <button class=\"btn btn-outline-secondary\" type=\"button\" onclick=\"copyCredentialToClipboard(this, 'displayAccessKey')\"><i class=\"fas fa-copy\"></i> Copy</button></div></div><div class=\"mb-3\"><label class=\"form-label fw-bold\">AWS_SECRET_ACCESS_KEY</label><div class=\"input-group\"><input type=\"text\" class=\"form-control font-monospace\" id=\"displaySecretKey\" readonly> <button class=\"btn btn-outline-secondary\" type=\"button\" onclick=\"copyCredentialToClipboard(this, 'displaySecretKey')\"><i class=\"fas fa-copy\"></i> Copy</button></div></div></div><div class=\"bg-light p-3 rounded\"><h6 class=\"text-muted mb-2\">Example AWS CLI Usage:</h6><div class=\"font-monospace small\"><div>export AWS_ACCESS_KEY_ID=<span id=\"exampleAccessKey\"></span></div><div>export AWS_SECRET_ACCESS_KEY=<span id=\"exampleSecretKey\"></span></div><div>export AWS_ENDPOINT_URL=http://localhost:8333</div><div class=\"mt-2\"># List buckets</div><div>aws s3 ls</div><div class=\"mt-2\"># Upload a file</div><div>aws s3 cp myfile.txt s3://mybucket/</div></div></div></div><div class=\"modal-footer\"><button type=\"button\" class=\"btn btn-primary\" onclick=\"closeCredentialsModal()\"><i class=\"fas fa-check me-1\"></i>I have saved the credentials</button></div></div></div></div><!-- JavaScript for service account management --><script>\n document.addEventListener('DOMContentLoaded', function() {\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 saId = button.getAttribute('data-sa-id');\n \n switch (action) {\n case 'show-sa-details':\n showSADetails(saId);\n break;\n case 'toggle-sa-status':\n toggleSAStatus(saId, button.getAttribute('data-current-status'));\n break;\n case 'delete-sa':\n deleteSA(saId);\n break;\n }\n });\n });\n\n async function showSADetails(id) {\n try {\n const encodedId = encodeURIComponent(id);\n const response = await fetch(basePath(`/api/service-accounts/${encodedId}`));\n if (response.ok) {\n const sa = await response.json();\n document.getElementById('saDetailsContent').innerHTML = createSADetailsContent(sa);\n const modal = new bootstrap.Modal(document.getElementById('saDetailsModal'));\n modal.show();\n } else {\n showErrorMessage('Failed to load service account details');\n }\n } catch (error) {\n console.error('Error loading service account details:', error);\n showErrorMessage('Failed to load service account details');\n }\n }\n\n async function toggleSAStatus(id, currentStatus) {\n const newStatus = currentStatus === 'Active' ? 'Inactive' : 'Active';\n try {\n const encodedId = encodeURIComponent(id);\n const response = await fetch(basePath(`/api/service-accounts/${encodedId}`), {\n method: 'PUT',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ status: newStatus })\n });\n \n if (response.ok) {\n showSuccessMessage(`Service account ${newStatus === 'Active' ? 'activated' : 'deactivated'}`);\n setTimeout(() => window.location.reload(), 1000);\n } else {\n const error = await response.json();\n showErrorMessage('Failed to update status: ' + (error.error || 'Unknown error'));\n }\n } catch (error) {\n console.error('Error updating status:', error);\n showErrorMessage('Failed to update status: ' + error.message);\n }\n }\n\n async function deleteSA(id) {\n showDeleteConfirm(id, async function() {\n try {\n const encodedId = encodeURIComponent(id);\n const response = await fetch(basePath(`/api/service-accounts/${encodedId}`), {\n method: 'DELETE'\n });\n \n if (response.ok) {\n showSuccessMessage('Service account deleted successfully');\n setTimeout(() => window.location.reload(), 1000);\n } else {\n const error = await response.json();\n showErrorMessage('Failed to delete: ' + (error.error || 'Unknown error'));\n }\n } catch (error) {\n console.error('Error deleting service account:', error);\n showErrorMessage('Failed to delete: ' + error.message);\n }\n }, 'Are you sure you want to delete this service account? This action cannot be undone.');\n }\n\n async function handleCreateServiceAccount() {\n const form = document.getElementById('createSAForm');\n const formData = new FormData(form);\n \n const saData = {\n parent_user: formData.get('parent_user'),\n description: formData.get('description')\n };\n \n // Handle expiration if set\n const expiration = formData.get('expiration');\n if (expiration) {\n // Validate the date before using it\n const date = new Date(expiration);\n const now = new Date();\n \n if (isNaN(date.getTime())) {\n showErrorMessage('Invalid expiration date format');\n return;\n }\n \n // Ensure expiration is in the future\n if (date <= now) {\n showErrorMessage('Expiration date must be in the future');\n return;\n }\n \n saData.expiration = date.toISOString();\n }\n \n try {\n const response = await fetch(basePath('/api/service-accounts'), {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify(saData)\n });\n \n if (response.ok) {\n const result = await response.json();\n \n // Hide create modal\n const createModal = bootstrap.Modal.getInstance(document.getElementById('createServiceAccountModal'));\n createModal.hide();\n form.reset();\n \n // Show credentials if returned\n if (result.service_account && result.service_account.secret_access_key) {\n showCredentials(result.service_account);\n } else {\n showSuccessMessage('Service account created successfully');\n setTimeout(() => window.location.reload(), 1000);\n }\n } else {\n const error = await response.json();\n showErrorMessage('Failed to create service account: ' + (error.error || 'Unknown error'));\n }\n } catch (error) {\n console.error('Error creating service account:', error);\n showErrorMessage('Failed to create service account: ' + error.message);\n }\n }\n\n function showCredentials(serviceAccount) {\n // Populate the credentials modal\n document.getElementById('displayAccessKey').value = serviceAccount.access_key_id;\n document.getElementById('displaySecretKey').value = serviceAccount.secret_access_key;\n document.getElementById('exampleAccessKey').textContent = serviceAccount.access_key_id;\n document.getElementById('exampleSecretKey').textContent = serviceAccount.secret_access_key;\n \n // Show the modal\n const credentialsModal = new bootstrap.Modal(document.getElementById('credentialsModal'));\n credentialsModal.show();\n }\n\n function closeCredentialsModal() {\n const modal = bootstrap.Modal.getInstance(document.getElementById('credentialsModal'));\n modal.hide();\n // Reload to show the new service account in the list\n setTimeout(() => window.location.reload(), 500);\n }\n\n function copyCredentialToClipboard(button, elementId) {\n const element = document.getElementById(elementId);\n const textToCopy = element.value;\n \n // Use modern Clipboard API if available\n if (navigator.clipboard && navigator.clipboard.writeText) {\n navigator.clipboard.writeText(textToCopy).then(() => {\n showSuccessMessage('Copied to clipboard!');\n }).catch(err => {\n console.warn('Clipboard API failed:', err);\n // Fallback\n fallbackCopyTextToClipboard(element);\n });\n } else {\n // Fallback for older browsers or non-secure contexts\n fallbackCopyTextToClipboard(element);\n }\n \n // Visual feedback\n const originalHTML = button.innerHTML;\n \n button.innerHTML = '<i class=\"fas fa-check\"></i>';\n button.classList.remove('btn-outline-secondary');\n button.classList.add('btn-success');\n \n setTimeout(() => {\n button.innerHTML = originalHTML;\n button.classList.remove('btn-success');\n button.classList.add('btn-outline-secondary');\n }, 1000);\n }\n\n function fallbackCopyTextToClipboard(element) {\n element.select();\n element.setSelectionRange(0, 99999); // For mobile devices\n \n try {\n const successful = document.execCommand('copy');\n if (successful) {\n showSuccessMessage('Copied to clipboard!');\n } else {\n showErrorMessage('Failed to copy to clipboard');\n }\n } catch (err) {\n console.error('Fallback copy failed:', err);\n showErrorMessage('Failed to copy to clipboard');\n }\n \n // Clear selection\n window.getSelection().removeAllRanges();\n }\n\n\n function createSADetailsContent(sa) {\n // Create DOM elements safely to prevent XSS\n const container = document.createElement('div');\n container.className = 'row';\n \n // Basic Information column\n const col1 = document.createElement('div');\n col1.className = 'col-md-6';\n \n const h6_1 = document.createElement('h6');\n h6_1.className = 'text-muted';\n h6_1.textContent = 'Basic Information';\n col1.appendChild(h6_1);\n \n const table1 = document.createElement('table');\n table1.className = 'table table-sm';\n \n // ID row\n const idRow = document.createElement('tr');\n idRow.innerHTML = '<td><strong>ID:</strong></td><td><code></code></td>';\n idRow.querySelector('code').textContent = sa.id || '';\n table1.appendChild(idRow);\n \n // Parent User row\n const parentRow = document.createElement('tr');\n parentRow.innerHTML = '<td><strong>Parent User:</strong></td><td></td>';\n parentRow.querySelectorAll('td')[1].textContent = sa.parent_user || '';\n table1.appendChild(parentRow);\n \n // Access Key row\n const keyRow = document.createElement('tr');\n keyRow.innerHTML = '<td><strong>Access Key:</strong></td><td><code></code></td>';\n keyRow.querySelector('code').textContent = sa.access_key_id || '';\n table1.appendChild(keyRow);\n \n // Status row\n const statusRow = document.createElement('tr');\n const statusTd1 = document.createElement('td');\n statusTd1.innerHTML = '<strong>Status:</strong>';\n const statusTd2 = document.createElement('td');\n const statusBadge = document.createElement('span');\n statusBadge.className = sa.status === 'Active' ? 'badge bg-success' : 'badge bg-secondary';\n statusBadge.textContent = sa.status || 'Unknown';\n statusTd2.appendChild(statusBadge);\n statusRow.appendChild(statusTd1);\n statusRow.appendChild(statusTd2);\n table1.appendChild(statusRow);\n \n col1.appendChild(table1);\n container.appendChild(col1);\n \n // Details column\n const col2 = document.createElement('div');\n col2.className = 'col-md-6';\n \n const h6_2 = document.createElement('h6');\n h6_2.className = 'text-muted';\n h6_2.textContent = 'Details';\n col2.appendChild(h6_2);\n \n const table2 = document.createElement('table');\n table2.className = 'table table-sm';\n \n // Description row\n const descRow = document.createElement('tr');\n descRow.innerHTML = '<td><strong>Description:</strong></td><td></td>';\n descRow.querySelectorAll('td')[1].textContent = sa.description || 'Not set';\n table2.appendChild(descRow);\n \n // Created row\n const createdRow = document.createElement('tr');\n createdRow.innerHTML = '<td><strong>Created:</strong></td><td></td>';\n try {\n createdRow.querySelectorAll('td')[1].textContent = new Date(sa.create_date).toLocaleString();\n } catch (e) {\n createdRow.querySelectorAll('td')[1].textContent = 'Invalid date';\n }\n table2.appendChild(createdRow);\n \n // Expiration row\n const expRow = document.createElement('tr');\n expRow.innerHTML = '<td><strong>Expires:</strong></td><td></td>';\n expRow.querySelectorAll('td')[1].textContent = sa.expiration || 'Never';\n table2.appendChild(expRow);\n \n col2.appendChild(table2);\n container.appendChild(col2);\n \n return container.outerHTML;\n }\n\n\n function showSuccessMessage(message) {\n showToast(message, 'success');\n }\n\n function showErrorMessage(message) {\n showToast(message, 'danger');\n }\n\n function showToast(message, type) {\n // Create toast container if it doesn't exist\n let toastContainer = document.getElementById('toastContainer');\n if (!toastContainer) {\n toastContainer = document.createElement('div');\n toastContainer.id = 'toastContainer';\n toastContainer.className = 'toast-container position-fixed top-0 end-0 p-3';\n toastContainer.style.zIndex = '9999';\n document.body.appendChild(toastContainer);\n }\n\n // Create toast element\n const toastId = 'toast-' + Date.now();\n const toastHTML = `\n <div id=\"${toastId}\" class=\"toast align-items-center text-white bg-${type} border-0\" role=\"alert\" aria-live=\"assertive\" aria-atomic=\"true\">\n <div class=\"d-flex\">\n <div class=\"toast-body\">\n ${escapeHtml(message)}\n </div>\n <button type=\"button\" class=\"btn-close btn-close-white me-2 m-auto\" data-bs-dismiss=\"toast\" aria-label=\"Close\"></button>\n </div>\n </div>\n `;\n \n toastContainer.insertAdjacentHTML('beforeend', toastHTML);\n const toastElement = document.getElementById(toastId);\n const toast = new bootstrap.Toast(toastElement, { autohide: true, delay: 5000 });\n toast.show();\n \n // Remove toast element after it's hidden\n toastElement.addEventListener('hidden.bs.toast', () => {\n toastElement.remove();\n });\n }\n\n function escapeHtml(text) {\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}diff --git a/weed/admin/view/app/topics.templ b/weed/admin/view/app/topics.templindex 4a69b0c547..8c916a9728 100644--- a/weed/admin/view/app/topics.templ+++ b/weed/admin/view/app/topics.templ@@ -273,7 +273,7 @@ templ Topics(data dash.TopicsData) {};// Create the topic- fetch('/api/mq/topics/create', {+ fetch(basePath('/api/mq/topics/create'), {method: 'POST',headers: {'Content-Type': 'application/json'@@ -354,7 +354,7 @@ templ Topics(data dash.TopicsData) {var detailsRow = document.getElementById('details-' + topicName.replace(/\./g, '_'));var contentDiv = detailsRow.querySelector('.topic-details-content');- fetch('/admin/topics/' + encodeURIComponent(topicName) + '/details')+ fetch(basePath('/admin/topics/' + encodeURIComponent(topicName) + '/details')).then(response => response.json()).then(data => {var html = '<div class="row">';diff --git a/weed/admin/view/app/topics_templ.go b/weed/admin/view/app/topics_templ.goindex 86d208c35c..115fa1e008 100644--- a/weed/admin/view/app/topics_templ.go+++ b/weed/admin/view/app/topics_templ.go@@ -40,7 +40,7 @@ func Topics(data dash.TopicsData) templ.Component {var templ_7745c5c3_Var2 stringtempl_7745c5c3_Var2, templ_7745c5c3_Err = templ.JoinStringErrs(data.LastUpdated.Format("2006-01-02 15:04:05"))if templ_7745c5c3_Err != nil {- return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/topics.templ`, Line: 13, Col: 107}+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/topics.templ`, Line: 13, Col: 107}}_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var2))if templ_7745c5c3_Err != nil {@@ -53,7 +53,7 @@ func Topics(data dash.TopicsData) templ.Component {var templ_7745c5c3_Var3 stringtempl_7745c5c3_Var3, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%d", data.TotalTopics))if templ_7745c5c3_Err != nil {- return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/topics.templ`, Line: 22, Col: 93}+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/topics.templ`, Line: 22, Col: 93}}_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var3))if templ_7745c5c3_Err != nil {@@ -66,7 +66,7 @@ func Topics(data dash.TopicsData) templ.Component {var templ_7745c5c3_Var4 stringtempl_7745c5c3_Var4, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%d", len(data.Topics)))if templ_7745c5c3_Err != nil {- return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/topics.templ`, Line: 30, Col: 90}+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/topics.templ`, Line: 30, Col: 90}}_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var4))if templ_7745c5c3_Err != nil {@@ -94,7 +94,7 @@ func Topics(data dash.TopicsData) templ.Component {var templ_7745c5c3_Var5 stringtempl_7745c5c3_Var5, templ_7745c5c3_Err = templ.JoinStringErrs(topic.Name)if templ_7745c5c3_Err != nil {- return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/topics.templ`, Line: 70, Col: 93}+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/topics.templ`, Line: 70, Col: 93}}_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var5))if templ_7745c5c3_Err != nil {@@ -113,7 +113,7 @@ func Topics(data dash.TopicsData) templ.Component {return topic.Name[:idx]}())if templ_7745c5c3_Err != nil {- return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/topics.templ`, Line: 78, Col: 55}+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/topics.templ`, Line: 78, Col: 55}}_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var6))if templ_7745c5c3_Err != nil {@@ -132,7 +132,7 @@ func Topics(data dash.TopicsData) templ.Component {return topic.Name[idx+1:]}())if templ_7745c5c3_Err != nil {- return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/topics.templ`, Line: 87, Col: 55}+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/topics.templ`, Line: 87, Col: 55}}_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var7))if templ_7745c5c3_Err != nil {@@ -145,7 +145,7 @@ func Topics(data dash.TopicsData) templ.Component {var templ_7745c5c3_Var8 stringtempl_7745c5c3_Var8, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%d", topic.Partitions))if templ_7745c5c3_Err != nil {- return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/topics.templ`, Line: 90, Col: 116}+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/topics.templ`, Line: 90, Col: 116}}_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var8))if templ_7745c5c3_Err != nil {@@ -163,7 +163,7 @@ func Topics(data dash.TopicsData) templ.Component {var templ_7745c5c3_Var9 stringtempl_7745c5c3_Var9, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%d %s", topic.Retention.DisplayValue, topic.Retention.DisplayUnit))if templ_7745c5c3_Err != nil {- return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/topics.templ`, Line: 96, Col: 140}+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/topics.templ`, Line: 96, Col: 140}}_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var9))if templ_7745c5c3_Err != nil {@@ -186,7 +186,7 @@ func Topics(data dash.TopicsData) templ.Component {var templ_7745c5c3_Var10 stringtempl_7745c5c3_Var10, templ_7745c5c3_Err = templ.JoinStringErrs(topic.Name)if templ_7745c5c3_Err != nil {- return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/topics.templ`, Line: 105, Col: 160}+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/topics.templ`, Line: 105, Col: 160}}_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var10))if templ_7745c5c3_Err != nil {@@ -199,7 +199,7 @@ func Topics(data dash.TopicsData) templ.Component {var templ_7745c5c3_Var11 stringtempl_7745c5c3_Var11, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("details-%s", strings.ReplaceAll(topic.Name, ".", "_")))if templ_7745c5c3_Err != nil {- return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/topics.templ`, Line: 110, Col: 146}+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/topics.templ`, Line: 110, Col: 146}}_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var11))if templ_7745c5c3_Err != nil {@@ -215,7 +215,7 @@ func Topics(data dash.TopicsData) templ.Component {return templ_7745c5c3_Err}}- templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 19, "</div></div></div></div></div><!-- Create Topic Modal --><div class=\"modal fade\" id=\"createTopicModal\" 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-plus me-2\"></i>Create New Topic</h5><button type=\"button\" class=\"btn-close\" data-bs-dismiss=\"modal\"></button></div><div class=\"modal-body\"><form id=\"createTopicForm\"><div class=\"row\"><div class=\"col-md-6\"><div class=\"mb-3\"><label for=\"topicNamespace\" class=\"form-label\">Namespace *</label> <input type=\"text\" class=\"form-control\" id=\"topicNamespace\" name=\"namespace\" required placeholder=\"e.g., default\"></div></div><div class=\"col-md-6\"><div class=\"mb-3\"><label for=\"topicName\" class=\"form-label\">Topic Name *</label> <input type=\"text\" class=\"form-control\" id=\"topicName\" name=\"name\" required placeholder=\"e.g., user-events\"></div></div></div><div class=\"row\"><div class=\"col-md-6\"><div class=\"mb-3\"><label for=\"partitionCount\" class=\"form-label\">Partition Count *</label> <input type=\"number\" class=\"form-control\" id=\"partitionCount\" name=\"partitionCount\" required min=\"1\" max=\"100\" value=\"6\"></div></div></div><!-- Retention Configuration --><div class=\"card mt-3\"><div class=\"card-header\"><h6 class=\"mb-0\"><i class=\"fas fa-clock me-2\"></i>Retention Policy</h6></div><div class=\"card-body\"><div class=\"form-check mb-3\"><input class=\"form-check-input\" type=\"checkbox\" id=\"enableRetention\" name=\"enableRetention\" onchange=\"toggleRetentionFields()\"> <label class=\"form-check-label\" for=\"enableRetention\">Enable data retention</label></div><div id=\"retentionFields\" style=\"display: none;\"><div class=\"row\"><div class=\"col-md-6\"><div class=\"mb-3\"><label for=\"retentionValue\" class=\"form-label\">Retention Duration</label> <input type=\"number\" class=\"form-control\" id=\"retentionValue\" name=\"retentionValue\" min=\"1\" value=\"7\"></div></div><div class=\"col-md-6\"><div class=\"mb-3\"><label for=\"retentionUnit\" class=\"form-label\">Unit</label> <select class=\"form-control\" id=\"retentionUnit\" name=\"retentionUnit\"><option value=\"hours\">Hours</option> <option value=\"days\" selected>Days</option></select></div></div></div><div class=\"alert alert-info\"><i class=\"fas fa-info-circle me-2\"></i> Data older than this duration will be automatically purged to save storage space.</div></div></div></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=\"createTopic()\"><i class=\"fas fa-plus me-1\"></i>Create Topic</button></div></div></div></div><script type=\"text/javascript\">\n // Topic management functions\n function showCreateTopicModal() {\n var modal = new bootstrap.Modal(document.getElementById('createTopicModal'));\n modal.show();\n }\n\n function toggleRetentionFields() {\n var enableRetention = document.getElementById('enableRetention').checked;\n var retentionFields = document.getElementById('retentionFields');\n \n if (enableRetention) {\n retentionFields.style.display = 'block';\n } else {\n retentionFields.style.display = 'none';\n }\n }\n\n function createTopic() {\n var form = document.getElementById('createTopicForm');\n var formData = new FormData(form);\n \n if (!form.checkValidity()) {\n form.classList.add('was-validated');\n return;\n }\n \n var namespace = formData.get('namespace');\n var name = formData.get('name');\n var partitionCount = formData.get('partitionCount');\n var enableRetention = formData.get('enableRetention');\n var retentionValue = enableRetention === 'on' ? parseInt(formData.get('retentionValue')) : 0;\n var retentionUnit = enableRetention === 'on' ? formData.get('retentionUnit') : 'hours';\n \n // Convert retention to seconds\n var retentionSeconds = 0;\n if (enableRetention === 'on' && retentionValue > 0) {\n if (retentionUnit === 'hours') {\n retentionSeconds = retentionValue * 3600;\n } else if (retentionUnit === 'days') {\n retentionSeconds = retentionValue * 86400;\n }\n }\n \n var topicData = {\n namespace: namespace,\n name: name,\n partition_count: parseInt(partitionCount),\n retention: {\n enabled: enableRetention === 'on',\n retention_seconds: retentionSeconds\n }\n };\n \n // Create the topic\n fetch('/api/mq/topics/create', {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json'\n },\n body: JSON.stringify(topicData)\n })\n .then(response => {\n if (response.ok) {\n return response.json();\n }\n throw new Error('Failed to create topic');\n })\n .then(data => {\n // Hide modal and refresh page\n var modal = bootstrap.Modal.getInstance(document.getElementById('createTopicModal'));\n modal.hide();\n location.reload();\n })\n .catch(error => {\n console.error('Error:', error);\n alert('Error creating topic: ' + error.message);\n });\n }\n\n function exportTopicsCSV() {\n var csvContent = 'Namespace,Topic Name,Partitions,Retention Enabled,Retention Value,Retention Unit\\n';\n \n var rows = document.querySelectorAll('#topicsTable tbody tr.topic-row');\n rows.forEach(function(row) {\n var cells = row.querySelectorAll('td');\n var namespace = cells[0].textContent.trim();\n var topicName = cells[1].textContent.trim();\n var partitions = cells[2].textContent.trim();\n var retention = cells[3].textContent.trim();\n \n var retentionEnabled = retention !== 'Disabled';\n var retentionValue = retentionEnabled ? retention.split(' ')[0] : '';\n var retentionUnit = retentionEnabled ? retention.split(' ')[1] : '';\n \n csvContent += namespace + ',' + topicName + ',' + partitions + ',' + retentionEnabled + ',' + retentionValue + ',' + retentionUnit + '\\n';\n });\n \n var blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });\n var link = document.createElement('a');\n var url = URL.createObjectURL(blob);\n link.setAttribute('href', url);\n link.setAttribute('download', 'topics_export.csv');\n link.style.visibility = 'hidden';\n document.body.appendChild(link);\n link.click();\n document.body.removeChild(link);\n }\n\n // Topic details functionality\n document.addEventListener('DOMContentLoaded', function() {\n // Handle view topic details buttons\n document.querySelectorAll('[data-action=\"view-topic-details\"]').forEach(function(button) {\n button.addEventListener('click', function(e) {\n e.stopPropagation();\n var topicName = this.getAttribute('data-topic-name');\n var detailsRow = document.getElementById('details-' + topicName.replace(/\\./g, '_'));\n \n if (detailsRow.style.display === 'none') {\n detailsRow.style.display = 'table-row';\n this.innerHTML = '<i class=\"fas fa-eye-slash\"></i>';\n \n // Load topic details\n loadTopicDetails(topicName);\n } else {\n detailsRow.style.display = 'none';\n this.innerHTML = '<i class=\"fas fa-eye\"></i>';\n }\n });\n });\n });\n\n function loadTopicDetails(topicName) {\n var detailsRow = document.getElementById('details-' + topicName.replace(/\\./g, '_'));\n var contentDiv = detailsRow.querySelector('.topic-details-content');\n \n fetch('/admin/topics/' + encodeURIComponent(topicName) + '/details')\n .then(response => response.json())\n .then(data => {\n var html = '<div class=\"row\">';\n html += '<div class=\"col-md-6\">';\n html += '<h6>Topic Configuration</h6>';\n html += '<ul class=\"list-unstyled\">';\n html += '<li><strong>Full Name:</strong> ' + data.name + '</li>';\n html += '<li><strong>Partitions:</strong> ' + data.partitions + '</li>';\n html += '<li><strong>Created:</strong> ' + (data.created || 'N/A') + '</li>';\n html += '</ul>';\n html += '</div>';\n html += '<div class=\"col-md-6\">';\n html += '<h6>Retention Policy</h6>';\n if (data.retention && data.retention.enabled) {\n html += '<p><i class=\"fas fa-check-circle text-success\"></i> Enabled</p>';\n html += '<p><strong>Duration:</strong> ' + data.retention.value + ' ' + data.retention.unit + '</p>';\n } else {\n html += '<p><i class=\"fas fa-times-circle text-danger\"></i> Disabled</p>';\n }\n html += '</div>';\n html += '</div>';\n \n contentDiv.innerHTML = html;\n })\n .catch(error => {\n console.error('Error loading topic details:', error);\n contentDiv.innerHTML = '<div class=\"alert alert-danger\">Failed to load topic details</div>';\n });\n }\n </script>")+ templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 19, "</div></div></div></div></div><!-- Create Topic Modal --><div class=\"modal fade\" id=\"createTopicModal\" 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-plus me-2\"></i>Create New Topic</h5><button type=\"button\" class=\"btn-close\" data-bs-dismiss=\"modal\"></button></div><div class=\"modal-body\"><form id=\"createTopicForm\"><div class=\"row\"><div class=\"col-md-6\"><div class=\"mb-3\"><label for=\"topicNamespace\" class=\"form-label\">Namespace *</label> <input type=\"text\" class=\"form-control\" id=\"topicNamespace\" name=\"namespace\" required placeholder=\"e.g., default\"></div></div><div class=\"col-md-6\"><div class=\"mb-3\"><label for=\"topicName\" class=\"form-label\">Topic Name *</label> <input type=\"text\" class=\"form-control\" id=\"topicName\" name=\"name\" required placeholder=\"e.g., user-events\"></div></div></div><div class=\"row\"><div class=\"col-md-6\"><div class=\"mb-3\"><label for=\"partitionCount\" class=\"form-label\">Partition Count *</label> <input type=\"number\" class=\"form-control\" id=\"partitionCount\" name=\"partitionCount\" required min=\"1\" max=\"100\" value=\"6\"></div></div></div><!-- Retention Configuration --><div class=\"card mt-3\"><div class=\"card-header\"><h6 class=\"mb-0\"><i class=\"fas fa-clock me-2\"></i>Retention Policy</h6></div><div class=\"card-body\"><div class=\"form-check mb-3\"><input class=\"form-check-input\" type=\"checkbox\" id=\"enableRetention\" name=\"enableRetention\" onchange=\"toggleRetentionFields()\"> <label class=\"form-check-label\" for=\"enableRetention\">Enable data retention</label></div><div id=\"retentionFields\" style=\"display: none;\"><div class=\"row\"><div class=\"col-md-6\"><div class=\"mb-3\"><label for=\"retentionValue\" class=\"form-label\">Retention Duration</label> <input type=\"number\" class=\"form-control\" id=\"retentionValue\" name=\"retentionValue\" min=\"1\" value=\"7\"></div></div><div class=\"col-md-6\"><div class=\"mb-3\"><label for=\"retentionUnit\" class=\"form-label\">Unit</label> <select class=\"form-control\" id=\"retentionUnit\" name=\"retentionUnit\"><option value=\"hours\">Hours</option> <option value=\"days\" selected>Days</option></select></div></div></div><div class=\"alert alert-info\"><i class=\"fas fa-info-circle me-2\"></i> Data older than this duration will be automatically purged to save storage space.</div></div></div></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=\"createTopic()\"><i class=\"fas fa-plus me-1\"></i>Create Topic</button></div></div></div></div><script type=\"text/javascript\">\n // Topic management functions\n function showCreateTopicModal() {\n var modal = new bootstrap.Modal(document.getElementById('createTopicModal'));\n modal.show();\n }\n\n function toggleRetentionFields() {\n var enableRetention = document.getElementById('enableRetention').checked;\n var retentionFields = document.getElementById('retentionFields');\n \n if (enableRetention) {\n retentionFields.style.display = 'block';\n } else {\n retentionFields.style.display = 'none';\n }\n }\n\n function createTopic() {\n var form = document.getElementById('createTopicForm');\n var formData = new FormData(form);\n \n if (!form.checkValidity()) {\n form.classList.add('was-validated');\n return;\n }\n \n var namespace = formData.get('namespace');\n var name = formData.get('name');\n var partitionCount = formData.get('partitionCount');\n var enableRetention = formData.get('enableRetention');\n var retentionValue = enableRetention === 'on' ? parseInt(formData.get('retentionValue')) : 0;\n var retentionUnit = enableRetention === 'on' ? formData.get('retentionUnit') : 'hours';\n \n // Convert retention to seconds\n var retentionSeconds = 0;\n if (enableRetention === 'on' && retentionValue > 0) {\n if (retentionUnit === 'hours') {\n retentionSeconds = retentionValue * 3600;\n } else if (retentionUnit === 'days') {\n retentionSeconds = retentionValue * 86400;\n }\n }\n \n var topicData = {\n namespace: namespace,\n name: name,\n partition_count: parseInt(partitionCount),\n retention: {\n enabled: enableRetention === 'on',\n retention_seconds: retentionSeconds\n }\n };\n \n // Create the topic\n fetch(basePath('/api/mq/topics/create'), {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json'\n },\n body: JSON.stringify(topicData)\n })\n .then(response => {\n if (response.ok) {\n return response.json();\n }\n throw new Error('Failed to create topic');\n })\n .then(data => {\n // Hide modal and refresh page\n var modal = bootstrap.Modal.getInstance(document.getElementById('createTopicModal'));\n modal.hide();\n location.reload();\n })\n .catch(error => {\n console.error('Error:', error);\n alert('Error creating topic: ' + error.message);\n });\n }\n\n function exportTopicsCSV() {\n var csvContent = 'Namespace,Topic Name,Partitions,Retention Enabled,Retention Value,Retention Unit\\n';\n \n var rows = document.querySelectorAll('#topicsTable tbody tr.topic-row');\n rows.forEach(function(row) {\n var cells = row.querySelectorAll('td');\n var namespace = cells[0].textContent.trim();\n var topicName = cells[1].textContent.trim();\n var partitions = cells[2].textContent.trim();\n var retention = cells[3].textContent.trim();\n \n var retentionEnabled = retention !== 'Disabled';\n var retentionValue = retentionEnabled ? retention.split(' ')[0] : '';\n var retentionUnit = retentionEnabled ? retention.split(' ')[1] : '';\n \n csvContent += namespace + ',' + topicName + ',' + partitions + ',' + retentionEnabled + ',' + retentionValue + ',' + retentionUnit + '\\n';\n });\n \n var blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });\n var link = document.createElement('a');\n var url = URL.createObjectURL(blob);\n link.setAttribute('href', url);\n link.setAttribute('download', 'topics_export.csv');\n link.style.visibility = 'hidden';\n document.body.appendChild(link);\n link.click();\n document.body.removeChild(link);\n }\n\n // Topic details functionality\n document.addEventListener('DOMContentLoaded', function() {\n // Handle view topic details buttons\n document.querySelectorAll('[data-action=\"view-topic-details\"]').forEach(function(button) {\n button.addEventListener('click', function(e) {\n e.stopPropagation();\n var topicName = this.getAttribute('data-topic-name');\n var detailsRow = document.getElementById('details-' + topicName.replace(/\\./g, '_'));\n \n if (detailsRow.style.display === 'none') {\n detailsRow.style.display = 'table-row';\n this.innerHTML = '<i class=\"fas fa-eye-slash\"></i>';\n \n // Load topic details\n loadTopicDetails(topicName);\n } else {\n detailsRow.style.display = 'none';\n this.innerHTML = '<i class=\"fas fa-eye\"></i>';\n }\n });\n });\n });\n\n function loadTopicDetails(topicName) {\n var detailsRow = document.getElementById('details-' + topicName.replace(/\\./g, '_'));\n var contentDiv = detailsRow.querySelector('.topic-details-content');\n \n fetch(basePath('/admin/topics/' + encodeURIComponent(topicName) + '/details'))\n .then(response => response.json())\n .then(data => {\n var html = '<div class=\"row\">';\n html += '<div class=\"col-md-6\">';\n html += '<h6>Topic Configuration</h6>';\n html += '<ul class=\"list-unstyled\">';\n html += '<li><strong>Full Name:</strong> ' + data.name + '</li>';\n html += '<li><strong>Partitions:</strong> ' + data.partitions + '</li>';\n html += '<li><strong>Created:</strong> ' + (data.created || 'N/A') + '</li>';\n html += '</ul>';\n html += '</div>';\n html += '<div class=\"col-md-6\">';\n html += '<h6>Retention Policy</h6>';\n if (data.retention && data.retention.enabled) {\n html += '<p><i class=\"fas fa-check-circle text-success\"></i> Enabled</p>';\n html += '<p><strong>Duration:</strong> ' + data.retention.value + ' ' + data.retention.unit + '</p>';\n } else {\n html += '<p><i class=\"fas fa-times-circle text-danger\"></i> Disabled</p>';\n }\n html += '</div>';\n html += '</div>';\n \n contentDiv.innerHTML = html;\n })\n .catch(error => {\n console.error('Error loading topic details:', error);\n contentDiv.innerHTML = '<div class=\"alert alert-danger\">Failed to load topic details</div>';\n });\n }\n </script>")if templ_7745c5c3_Err != nil {return templ_7745c5c3_Err}