This commit is contained in:
2026-02-13 21:50:00 +01:00
parent dbfd99f410
commit 1825b50dec
11 changed files with 276 additions and 30 deletions

View File

@@ -683,3 +683,106 @@ func (s *Server) handleAdminUI(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/html; charset=utf-8")
w.Write([]byte(adminPanelHTML))
}
// handleAdminResetClientPassword resets a client's API key to a new random value
func (s *Server) handleAdminResetClientPassword(w http.ResponseWriter, r *http.Request) {
admin, err := s.authenticateAdmin(r)
if err != nil || admin == nil {
http.Error(w, "Unauthorized", http.StatusUnauthorized)
return
}
if r.Method != http.MethodPost {
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
return
}
clientID := r.URL.Query().Get("client_id")
if clientID == "" {
http.Error(w, "client_id required", http.StatusBadRequest)
return
}
// Get existing client
client, err := s.db.GetClient(clientID)
if err != nil {
http.Error(w, "Database error", http.StatusInternalServerError)
return
}
if client == nil {
http.Error(w, "Client not found", http.StatusNotFound)
return
}
// Generate new random API key
newAPIKey, err := generateToken()
if err != nil {
http.Error(w, "Failed to generate new API key", http.StatusInternalServerError)
return
}
// Update client with new API key
client.APIKey = hashAPIKey(newAPIKey)
if err := s.db.SaveClient(client); err != nil {
http.Error(w, "Failed to update client", http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(map[string]interface{}{
"success": true,
"message": "Client password reset successfully",
"api_key": newAPIKey, // Return the new key (only shown once!)
})
}
// handleClientChangePassword allows a client to change its own API key
func (s *Server) handleClientChangePassword(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
return
}
var req struct {
ClientID string `json:"client_id"`
CurrentKey string `json:"current_key"`
NewKey string `json:"new_key"`
}
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
http.Error(w, "Invalid request body", http.StatusBadRequest)
return
}
if req.ClientID == "" || req.CurrentKey == "" || req.NewKey == "" {
http.Error(w, "client_id, current_key, and new_key required", http.StatusBadRequest)
return
}
// Authenticate with current key
if !s.authenticate(req.ClientID, req.CurrentKey) {
http.Error(w, "Invalid current API key", http.StatusUnauthorized)
return
}
// Get client
client, err := s.db.GetClient(req.ClientID)
if err != nil || client == nil {
http.Error(w, "Client not found", http.StatusNotFound)
return
}
// Update with new key
client.APIKey = hashAPIKey(req.NewKey)
if err := s.db.SaveClient(client); err != nil {
http.Error(w, "Failed to update password", http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(map[string]interface{}{
"success": true,
"message": "Password changed successfully",
})
}

View File

@@ -339,6 +339,32 @@ const adminPanelHTML = `<!DOCTYPE html>
</div>
</div>
<!-- Client Change Password Modal -->
<div id="client-password-modal" class="modal-overlay hidden" onclick="closeModalOnOverlay(event, 'client-password-modal')">
<div class="modal-content" onclick="event.stopPropagation()">
<div class="modal-header">
<h3>Set Client API Key</h3>
<button type="button" class="close-btn" onclick="closeModal('client-password-modal')">&times;</button>
</div>
<form id="client-password-form">
<input type="hidden" id="client-password-client-id">
<div class="form-group">
<label>Client ID</label>
<input type="text" id="client-password-client-name" readonly>
</div>
<div class="form-group">
<label>New API Key</label>
<input type="text" id="client-password-new" required>
</div>
<div class="form-group">
<label>Confirm API Key</label>
<input type="text" id="client-password-confirm" required>
</div>
<button type="submit" class="btn btn-success" style="width: 100%; margin-top: 20px;">Set API Key</button>
</form>
</div>
</div>
<script>
let currentTab = 'clients';
@@ -432,6 +458,8 @@ const adminPanelHTML = `<!DOCTYPE html>
'<td>' + (c.enabled ? '<span class="badge badge-success">Enabled</span>' : '<span class="badge badge-danger">Disabled</span>') + '</td>' +
'<td>' +
'<button class="btn btn-sm btn-warning" onclick="editClient(\'' + c.client_id + '\')">Edit</button>' +
'<button class="btn btn-sm" style="background: #9b59b6; color: white;" onclick="showClientChangePassword(\'' + c.client_id + '\')">Set Key</button>' +
'<button class="btn btn-sm" style="background: #e67e22; color: white;" onclick="resetClientPassword(\'' + c.client_id + '\')">Reset Key</button>' +
'<button class="btn btn-sm btn-danger" onclick="deleteClient(\'' + c.client_id + '\')">Delete</button>' +
'</td>' +
'</tr>';
@@ -756,6 +784,65 @@ const adminPanelHTML = `<!DOCTYPE html>
}
}
// Reset client password/API key
async function resetClientPassword(clientId) {
if (!confirm('Reset API key for client "' + clientId + '"? The new key will be shown once.')) return;
try {
const res = await fetch('/admin/client/reset-password?client_id=' + clientId, { method: 'POST' });
const data = await res.json();
if (data.success) {
// Show the new API key in a prompt so it can be copied
prompt('New API key for ' + clientId + ' (copy this now - it won\\'t be shown again):', data.api_key);
} else {
alert(data.message || 'Failed to reset client password');
}
} catch (e) {
alert('Failed to reset client password');
}
}
// Show client password change modal
function showClientChangePassword(clientId) {
document.getElementById('client-password-client-id').value = clientId;
document.getElementById('client-password-client-name').value = clientId;
document.getElementById('client-password-new').value = '';
document.getElementById('client-password-confirm').value = '';
showModal('client-password-modal');
}
// Handle client password change form
document.getElementById('client-password-form').addEventListener('submit', async (e) => {
e.preventDefault();
const clientId = document.getElementById('client-password-client-id').value;
const newKey = document.getElementById('client-password-new').value;
const confirmKey = document.getElementById('client-password-confirm').value;
if (newKey !== confirmKey) {
alert('API keys do not match');
return;
}
try {
const res = await fetch('/admin/client/update', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ client_id: clientId, api_key: newKey })
});
const data = await res.json();
if (data.success) {
closeModal('client-password-modal');
alert('API key changed successfully for ' + clientId);
} else {
alert(data.message || 'Failed to change API key');
}
} catch (e) {
alert('Failed to change API key');
}
});
// Initialize
checkAuth();
</script>

View File

@@ -214,7 +214,7 @@ func (s *Server) HandleUpload(w http.ResponseWriter, r *http.Request) {
// S3 upload
storageKey := fmt.Sprintf("%s/%s_%s.zfs", req.ClientID, req.DatasetName, timestamp)
if req.Compressed {
storageKey += ".gz"
storageKey += ".lz4"
}
respondJSON(w, http.StatusOK, UploadResponse{
@@ -507,6 +507,7 @@ func (s *Server) RegisterRoutes(mux *http.ServeMux) {
mux.HandleFunc("/download", s.HandleDownload)
mux.HandleFunc("/health", s.HandleHealth)
mux.HandleFunc("/rotation-policy", s.HandleRotationPolicy)
mux.HandleFunc("/client/change-password", s.handleClientChangePassword)
// Admin API routes
mux.HandleFunc("/admin/login", s.handleAdminLogin)
@@ -517,6 +518,7 @@ func (s *Server) RegisterRoutes(mux *http.ServeMux) {
mux.HandleFunc("/admin/client/create", s.handleAdminCreateClient)
mux.HandleFunc("/admin/client/update", s.handleAdminUpdateClient)
mux.HandleFunc("/admin/client/delete", s.handleAdminDeleteClient)
mux.HandleFunc("/admin/client/reset-password", s.handleAdminResetClientPassword)
mux.HandleFunc("/admin/snapshots", s.handleAdminGetSnapshots)
mux.HandleFunc("/admin/snapshot/delete", s.handleAdminDeleteSnapshot)
mux.HandleFunc("/admin/stats", s.handleAdminGetStats)