This commit is contained in:
pika 2025-04-03 14:08:11 +02:00
parent 0a31714a93
commit 66fe31eabe
3 changed files with 419 additions and 206 deletions

View file

@ -19,6 +19,7 @@ import markdown
from datetime import datetime
from flask import flash
from app.utils.app_utils import is_port_in_use, validate_port_data
from difflib import SequenceMatcher
bp = Blueprint("api", __name__, url_prefix="/api")
csrf = CSRFProtect()
@ -424,7 +425,7 @@ def get_free_port(server_id):
@bp.route("/validate/app-name", methods=["GET"])
@login_required
def validate_app_name():
"""API endpoint to validate application name in real-time"""
"""API endpoint to validate application name in real-time with fuzzy matching"""
name = request.args.get("name", "").strip()
server_id = request.args.get("server_id")
app_id = request.args.get("app_id")
@ -448,18 +449,41 @@ def validate_app_name():
"edit_url": url_for('dashboard.app_edit', app_id=existing_app.id)
})
# Check for similar names
similar_apps = App.query.filter(
App.name.ilike(f"%{name}%"),
App.server_id == server_id
).limit(3).all()
# Get all apps on this server for similarity check
server_apps = App.query.filter(App.server_id == server_id).all()
if similar_apps and (not app_id or not any(str(app.id) == app_id for app in similar_apps)):
similar_names = [{"name": app.name, "id": app.id} for app in similar_apps]
# Filter out the current app if we're editing
if app_id:
server_apps = [app for app in server_apps if str(app.id) != app_id]
# Find similar apps using fuzzy matching
similar_apps = []
for app in server_apps:
# Calculate similarity ratio using SequenceMatcher
similarity = SequenceMatcher(None, name.lower(), app.name.lower()).ratio()
# Consider similar if:
# 1. One is a substring of the other OR
# 2. They have high similarity ratio (over 0.7)
is_substring = name.lower() in app.name.lower() or app.name.lower() in name.lower()
is_similar = similarity > 0.7
if (is_substring or is_similar) and len(name) >= 3:
similar_apps.append({
"name": app.name,
"id": app.id,
"similarity": similarity
})
# Sort by similarity (highest first) and limit to top 3
similar_apps = sorted(similar_apps, key=lambda x: x["similarity"], reverse=True)[:3]
if similar_apps:
return jsonify({
"valid": True,
"warning": "Similar application names found",
"similar_apps": similar_names
"similar_apps": similar_apps
})
return jsonify({"valid": True})

View file

@ -234,6 +234,27 @@ def app_new(server_id=None):
documentation = request.form.get("documentation", "")
url = request.form.get("url", "")
# Validate application name
if not name:
flash("Application name is required", "danger")
return render_template(
"dashboard/app_form.html",
edit_mode=False,
servers=servers,
selected_server_id=server_id
)
# Check for duplicate application names on the same server
existing_app = App.query.filter_by(name=name, server_id=server_id).first()
if existing_app:
flash(f"An application with the name '{name}' already exists on this server", "danger")
return render_template(
"dashboard/app_form.html",
edit_mode=False,
servers=servers,
selected_server_id=server_id
)
# Process port data from form
port_data = []
port_numbers = request.form.getlist("port_numbers[]")
@ -245,36 +266,75 @@ def app_new(server_id=None):
protocol = protocols[i] if i < len(protocols) else "TCP"
description = descriptions[i] if i < len(descriptions) else ""
port_data.append((port_numbers[i], protocol, description))
# Check for port conflicts proactively
conflicts = []
seen_ports = set() # To track ports already seen in this submission
for i, (port_number, protocol, _) in enumerate(port_data):
try:
clean_port = int(port_number)
# Check if this port has already been seen in this submission
port_key = f"{clean_port}/{protocol}"
if port_key in seen_ports:
conflicts.append((clean_port, protocol, "Duplicate port in submission"))
continue
seen_ports.add(port_key)
# Server-side validation
from app.utils.app_utils import save_app
# Check if the port is in use by another application
in_use, conflicting_app_name = is_port_in_use(
clean_port, protocol, server_id
)
if in_use:
conflicts.append((clean_port, protocol, f"Port {clean_port}/{protocol} is already in use by application '{conflicting_app_name}'"))
except (ValueError, TypeError):
continue
success, app, error = save_app(name, server_id, documentation, port_data, url=url)
if conflicts:
for conflict in conflicts:
flash(f"Conflict: {conflict[0]}/{conflict[1]} - {conflict[2]}", "danger")
return render_template(
"dashboard/app_form.html",
edit_mode=False,
servers=servers,
selected_server_id=server_id
)
if success:
flash(f"Application '{name}' created successfully", "success")
return redirect(url_for("dashboard.app_view", app_id=app.id))
else:
flash(error, "danger")
# Create the application
try:
new_app = App(
name=name,
server_id=server_id,
documentation=documentation,
url=url
)
db.session.add(new_app)
db.session.flush() # Get the app ID without committing
# Check if it's a port conflict and provide direct link
if "already in use by application" in error:
try:
app_name = error.split("'")[1] # Extract app name from error
conflict_app = App.query.filter_by(name=app_name, server_id=server_id).first()
if conflict_app:
edit_url = url_for('dashboard.app_edit', app_id=conflict_app.id)
flash(f'<a href="{edit_url}" class="alert-link">Edit conflicting application</a>', "info")
except:
pass
# Add ports
for port_number, protocol, description in port_data:
new_port = Port(
app_id=new_app.id,
port_number=int(port_number),
protocol=protocol,
description=description
)
db.session.add(new_port)
db.session.commit()
flash(f"Application '{name}' created successfully", "success")
return redirect(url_for("dashboard.app_view", app_id=new_app.id))
except Exception as e:
db.session.rollback()
flash(f"Error creating application: {str(e)}", "danger")
# GET request or validation failed - render the form
return render_template(
"dashboard/app_form.html",
title="New Application",
edit_mode=False,
servers=servers,
selected_server_id=server_id,
selected_server_id=server_id
)
@ -308,6 +368,32 @@ def app_edit(app_id):
documentation = request.form.get("documentation", "")
url = request.form.get("url", "") # Get the URL
# Validate application name
if not name:
flash("Application name is required", "danger")
return render_template(
"dashboard/app_form.html",
edit_mode=True,
app=app,
servers=servers
)
# Check for duplicate application names on the same server (excluding this app)
existing_app = App.query.filter(
App.name == name,
App.server_id == server_id,
App.id != app_id
).first()
if existing_app:
flash(f"An application with the name '{name}' already exists on this server", "danger")
return render_template(
"dashboard/app_form.html",
edit_mode=True,
app=app,
servers=servers
)
# Process port data from form
port_data = []
port_numbers = request.form.getlist("port_numbers[]")
@ -347,7 +433,12 @@ def app_edit(app_id):
if conflicts:
for conflict in conflicts:
flash(f"Conflict: {conflict[0]}/{conflict[1]} - {conflict[2]}", "danger")
return render_template("dashboard/app_edit.html", app=app, servers=servers)
return render_template(
"dashboard/app_form.html",
edit_mode=True,
app=app,
servers=servers
)
# Update application details
app.name = name
@ -372,7 +463,12 @@ def app_edit(app_id):
flash("Application updated successfully", "success")
return redirect(url_for("dashboard.app_view", app_id=app_id))
return render_template("dashboard/app_edit.html", app=app, servers=servers)
return render_template(
"dashboard/app_form.html",
edit_mode=True,
app=app,
servers=servers
)
@bp.route("/app/<int:app_id>/delete", methods=["POST"])

View file

@ -6,25 +6,8 @@
<div class="row align-items-center">
<div class="col">
<h2 class="page-title">
{{ title }}
{% if edit_mode %}Edit Application: {{ app.name }}{% else %}New Application{% endif %}
</h2>
<div class="text-muted mt-1">
{% if edit_mode %}Edit{% else %}Create{% endif %} application details and configure ports
</div>
</div>
<div class="col-auto ms-auto">
<div class="btn-list">
<a href="{{ dashboard_link }}" class="btn btn-outline-primary">
<span class="ti ti-dashboard"></span>
Dashboard
</a>
{% if edit_mode %}
<a href="{{ url_for('dashboard.app_view', app_id=app.id) }}" class="btn btn-outline-secondary">
<span class="ti ti-eye"></span>
View Application
</a>
{% endif %}
</div>
</div>
</div>
</div>
@ -35,7 +18,7 @@
{% if messages %}
{% for category, message in messages %}
<div class="alert alert-{{ category }} alert-dismissible fade show" role="alert">
{{ message }}
{{ message|safe }}
<button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
</div>
{% endfor %}
@ -43,77 +26,55 @@
{% endwith %}
<form method="POST"
action="{% if edit_mode %}{{ url_for('dashboard.app_edit', app_id=app.id) }}{% else %}{{ url_for('dashboard.app_new') }}{% endif %}">
action="{{ url_for('dashboard.app_edit', app_id=app.id) if edit_mode else url_for('dashboard.app_new', server_id=selected_server_id) }}">
<input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
{% if app %}
<input type="hidden" id="app-id" name="app_id" value="{{ app.id }}">
{% endif %}
<div class="mb-3">
<label for="app-name" class="form-label required">Application Name</label>
<input type="text" class="form-control" id="app-name" name="name" required
value="{% if app %}{{ app.name }}{% endif %}">
<div id="name-feedback"></div>
<label class="form-label required">Application Name</label>
<input type="text" class="form-control" name="name" value="{{ app.name if edit_mode else '' }}" required>
</div>
<div class="mb-3">
<label class="form-label">Application URL (Optional)</label>
<div class="input-group">
<span class="input-group-text">
<span class="ti ti-link"></span>
</span>
<input type="url" class="form-control" name="url" id="url" value="{{ app.url if app else '' }}"
placeholder="https://example.com">
</div>
<small class="form-hint">
If provided, the application name will be clickable and link to this URL.
</small>
<label class="form-label">URL</label>
<input type="url" class="form-control" name="url" value="{{ app.url if edit_mode else '' }}"
placeholder="https://example.com">
<small class="form-hint">Optional URL for accessing the application</small>
</div>
<div class="mb-3">
<label for="server-id" class="form-label required">Server</label>
<select class="form-select" id="server-id" name="server_id" required>
<option value="">Select Server</option>
<label class="form-label required">Server</label>
<select class="form-select" name="server_id" required id="server-select">
<option value="">Select a server</option>
{% for server in servers %}
<option value="{{ server.id }}" {% if (app and app.server_id==server.id) or (selected_server_id and
selected_server_id|int==server.id|int) %}selected{% endif %}>
<option value="{{ server.id }}" {% if (edit_mode and server.id==app.server_id) or (not edit_mode and
server.id==selected_server_id) %}selected{% endif %}>
{{ server.hostname }} ({{ server.ip_address }})
</option>
{% endfor %}
</select>
</div>
<div class="mb-3">
<label class="form-label">Documentation</label>
<textarea class="form-control" name="documentation" rows="5"
placeholder="Add documentation about this application">{{ app.documentation if edit_mode else '' }}</textarea>
</div>
<div class="mb-3">
<div class="d-flex justify-content-between align-items-center mb-2">
<label class="form-label mb-0">Application Ports</label>
<div class="btn-group">
<button type="button" class="btn btn-sm btn-outline-primary" id="add-port-btn">
<span class="ti ti-plus"></span> Add Port
</button>
<button type="button" class="btn btn-sm btn-outline-secondary" id="random-port-btn"
title="Generate random available port">
<span class="ti ti-dice"></span> Random Port
</button>
</div>
</div>
<label class="form-label">Ports</label>
<div class="table-responsive">
<table class="table table-vcenter card-table" id="ports-table">
<thead>
<tr>
<th>Port</th>
<th>Port Number</th>
<th>Protocol</th>
<th>Description</th>
<th width="40"></th>
<th width="50"></th>
</tr>
</thead>
<tbody>
{% if app and app.ports %}
{% if edit_mode and app.ports %}
{% for port in app.ports %}
<tr>
<td>
<input type="number" name="port_numbers[]" class="form-control" min="1" max="65535"
value="{{ port.port_number }}" required>
value="{{ port.port_number }}">
</td>
<td>
<select name="protocols[]" class="form-select">
@ -133,14 +94,14 @@
</tr>
{% endfor %}
{% else %}
<!-- Always show at least one empty port row if no ports exist -->
<tr>
<td>
<input type="number" name="port_numbers[]" class="form-control" min="1" max="65535" required>
<input type="number" name="port_numbers[]" class="form-control" min="1" max="65535"
placeholder="Port number">
</td>
<td>
<select name="protocols[]" class="form-select">
<option value="TCP" selected>TCP</option>
<option value="TCP">TCP</option>
<option value="UDP">UDP</option>
</select>
</td>
@ -157,94 +118,26 @@
</tbody>
</table>
</div>
<small class="form-hint">Configure the network ports used by this application</small>
</div>
<div class="mb-3">
<label class="form-label">Documentation</label>
<textarea class="form-control" name="documentation" id="documentation" rows="10"
placeholder="Enter documentation in Markdown format">{{ app.documentation if app else '' }}</textarea>
<small class="form-hint">
Use <a href="https://www.markdownguide.org/basic-syntax/" target="_blank">Markdown syntax</a>
to format your documentation. You can use GitHub-style alerts:
</small>
<div class="mt-2 d-flex gap-2 flex-wrap">
<code>> [!NOTE] This is a note</code>
<code>> [!TIP] This is a tip</code>
<code>> [!IMPORTANT] Important info</code>
<code>> [!WARNING] Warning message</code>
<code>> [!CAUTION] Critical caution</code>
<div class="mt-3">
<button type="button" class="btn btn-sm btn-outline-primary" onclick="addPortRow()">
<span class="ti ti-plus me-1"></span> Add Port
</button>
</div>
</div>
<div class="form-footer">
<button type="submit" class="btn btn-primary">Save Application</button>
{% if edit_mode %}
<a href="{{ url_for('dashboard.app_view', app_id=app.id) }}" class="btn btn-outline-secondary ms-2">Cancel</a>
{% else %}
<a href="{{ dashboard_link }}" class="btn btn-outline-secondary ms-2">Cancel</a>
{% endif %}
<div class="d-flex">
<a href="{{ url_for('dashboard.app_view', app_id=app.id) if edit_mode else url_for('dashboard.app_new') }}"
class="btn btn-link">Cancel</a>
<button type="submit" class="btn btn-primary ms-auto">
{% if edit_mode %}Save Changes{% else %}Create Application{% endif %}
</button>
</div>
</div>
</form>
</div>
</div>
</div>
{% endblock %}
{% block extra_js %}
<script>
{% if app and app.id %}
const appId = {{ app.id | tojson }};
{% else %}
const appId = null;
{% endif %}
// Initialize everything once the DOM is loaded
document.addEventListener('DOMContentLoaded', function () {
// Connect port management buttons
const addPortBtn = document.getElementById('add-port-btn');
const randomPortBtn = document.getElementById('random-port-btn');
if (addPortBtn) {
addPortBtn.addEventListener('click', function () {
addPortRow();
});
}
if (randomPortBtn) {
randomPortBtn.addEventListener('click', function () {
generateRandomPort();
});
}
});
// Show notifications
function showNotification(message, type = 'info') {
const alertDiv = document.createElement('div');
alertDiv.className = `alert alert-${type} alert-dismissible fade show`;
alertDiv.innerHTML = `
${message}
<button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
`;
const container = document.querySelector('.card-body');
if (container) {
container.insertBefore(alertDiv, container.firstChild);
// Auto-dismiss after 5 seconds
setTimeout(() => {
alertDiv.classList.remove('show');
setTimeout(() => alertDiv.remove(), 150);
}, 5000);
}
}
</script>
<script>
document.body.addEventListener('htmx:configRequest', (event) => {
event.detail.headers['X-CSRFToken'] = "{{ csrf_token() }}";
});
</script>
<script>
// Make sure removePortRow is in the global scope
@ -270,16 +163,12 @@
// Add a visual indicator that this row is empty
row.classList.add('table-secondary', 'opacity-50');
// Show a helping message
showNotification('Application saved with no ports. Use "Add Port" to add ports.', 'info');
} else {
// Remove the row if there are other rows
row.remove();
}
};
// Port management functions
function addPortRow(portNumber = '', protocol = 'TCP', description = '') {
const tbody = document.querySelector('#ports-table tbody');
@ -293,7 +182,7 @@
newRow.innerHTML = `
<td class="position-relative">
<input type="number" name="port_numbers[]" class="form-control"
min="1" max="65535" value="${portNumber}" required>
min="1" max="65535" value="${portNumber}" placeholder="Port number">
<div class="feedback"></div>
</td>
<td>
@ -313,36 +202,240 @@
</td>
`;
tbody.appendChild(newRow);
// Set up validation for the new row
setTimeout(setupPortValidation, 50);
}
async function generateRandomPort() {
try {
const serverId = document.querySelector('select[name="server_id"]').value;
if (!serverId) {
showNotification('Please select a server first', 'warning');
return;
}
document.addEventListener('DOMContentLoaded', function () {
// Get form elements
const nameField = document.querySelector('input[name="name"]');
const serverSelect = document.getElementById('server-select');
const submitButton = document.querySelector('button[type="submit"]');
const response = await fetch(`/api/server/${serverId}/free-port`);
const data = await response.json();
// Set up name validation
if (nameField && serverSelect) {
// Validate on typing (with debounce)
nameField.addEventListener('input', function () {
validateAppName(nameField, serverSelect, 300);
});
if (data.success && data.port) {
addPortRow(data.port);
} else {
showNotification(data.error || 'No available ports found', 'warning');
}
} catch (error) {
console.error('Error generating random port:', error);
showNotification('Failed to generate random port', 'danger');
// Also validate on blur for completeness
nameField.addEventListener('blur', function () {
validateAppName(nameField, serverSelect, 0);
});
serverSelect.addEventListener('change', function () {
if (nameField.value.trim()) {
validateAppName(nameField, serverSelect, 0);
}
});
}
// Set up port validation for all port inputs
function setupPortValidation() {
const portInputs = document.querySelectorAll('input[name="port_numbers[]"]');
const protocolSelects = document.querySelectorAll('select[name="protocols[]"]');
portInputs.forEach((input, index) => {
const protocolSelect = protocolSelects[index];
// Validate on typing (with debounce)
input.addEventListener('input', function () {
validatePort(input, protocolSelect, 300);
});
// Also validate on blur for completeness
input.addEventListener('blur', function () {
validatePort(input, protocolSelect, 0);
});
if (protocolSelect) {
protocolSelect.addEventListener('change', function () {
if (input.value.trim()) {
validatePort(input, protocolSelect, 0);
}
});
}
});
}
// Initial setup
setupPortValidation();
// Re-setup validation after adding a new port row
const originalAddPortRow = window.addPortRow;
window.addPortRow = function (portNumber = '', protocol = 'TCP', description = '') {
originalAddPortRow(portNumber, protocol, description);
setupPortValidation();
};
// Validate application name
function validateAppName(nameField, serverSelect, debounceTime = 300) {
// Create feedback element if it doesn't exist
if (!nameField.nextElementSibling || !nameField.nextElementSibling.classList.contains('feedback')) {
const feedback = document.createElement('div');
feedback.className = 'feedback';
nameField.parentNode.insertBefore(feedback, nameField.nextSibling);
}
const feedbackElement = nameField.nextElementSibling;
const name = nameField.value.trim();
const serverId = serverSelect.value;
const appId = {% if edit_mode %} { { app.id } } {% else %} null{% endif %};
if (!name || !serverId) {
clearFeedback(feedbackElement);
nameField.classList.remove('is-invalid');
return;
}
// Show loading indicator for better UX
if (debounceTime > 0) {
showLoading(feedbackElement, 'Checking...');
}
// Debounce to avoid too many requests
clearTimeout(nameField.timer);
nameField.timer = setTimeout(() => {
fetch(`/api/validate/app-name?name=${encodeURIComponent(name)}&server_id=${serverId}${appId ? '&app_id=' + appId : ''}`)
.then(response => response.json())
.then(data => {
clearFeedback(feedbackElement);
if (!data.valid) {
nameField.classList.add('is-invalid');
showError(feedbackElement, data.message);
if (data.edit_url) {
feedbackElement.innerHTML += ` <a href="${data.edit_url}" class="alert-link">View existing app</a>`;
}
} else if (data.warning) {
nameField.classList.remove('is-invalid');
nameField.classList.add('is-warning');
showWarning(feedbackElement, data.warning);
if (data.similar_apps && data.similar_apps.length > 0) {
const similarList = document.createElement('ul');
similarList.className = 'mt-1';
data.similar_apps.forEach(app => {
const li = document.createElement('li');
li.innerHTML = `<a href="/dashboard/app/${app.id}" class="alert-link">${app.name}</a>`;
similarList.appendChild(li);
});
feedbackElement.appendChild(similarList);
}
} else {
nameField.classList.remove('is-invalid');
nameField.classList.add('is-valid');
showSuccess(feedbackElement, 'Application name available');
}
})
.catch(error => {
console.error('Validation error:', error);
clearFeedback(feedbackElement);
nameField.classList.remove('is-invalid');
nameField.classList.remove('is-valid');
});
}, debounceTime);
}
// Validate port
function validatePort(portField, protocolField, debounceTime = 300) {
// Create feedback element if it doesn't exist
if (!portField.nextElementSibling || !portField.nextElementSibling.classList.contains('feedback')) {
const feedback = document.createElement('div');
feedback.className = 'feedback';
portField.parentNode.insertBefore(feedback, portField.nextSibling);
}
const feedbackElement = portField.nextElementSibling;
const port = portField.value.trim();
const protocol = protocolField.value;
const serverId = serverSelect.value;
const appId = {% if edit_mode %}{{ app.id }}{% else %}null{% endif %};
if (!port || !serverId) {
clearFeedback(feedbackElement);
portField.classList.remove('is-invalid');
return;
}
// Check for duplicate ports within the form first
const allPortFields = document.querySelectorAll('input[name="port_numbers[]"]');
const allProtocolFields = document.querySelectorAll('select[name="protocols[]"]');
let duplicateFound = false;
allPortFields.forEach((field, index) => {
if (field !== portField && field.value === port && allProtocolFields[index].value === protocol) {
duplicateFound = true;
}
});
if (duplicateFound) {
portField.classList.add('is-invalid');
clearFeedback(feedbackElement);
showError(feedbackElement, `Duplicate port ${port}/${protocol} in your form`);
return;
}
// Show loading indicator for better UX
if (debounceTime > 0) {
showLoading(feedbackElement, 'Checking...');
}
// Debounce to avoid too many requests
clearTimeout(portField.timer);
portField.timer = setTimeout(() => {
fetch(`/api/validate/app-port?port_number=${encodeURIComponent(port)}&protocol=${protocol}&server_id=${serverId}${appId ? '&app_id=' + appId : ''}`)
.then(response => response.json())
.then(data => {
clearFeedback(feedbackElement);
if (!data.valid) {
portField.classList.add('is-invalid');
showError(feedbackElement, data.message);
if (data.edit_url) {
feedbackElement.innerHTML += ` <a href="${data.edit_url}" class="alert-link">Edit conflicting app</a>`;
}
} else {
portField.classList.remove('is-invalid');
portField.classList.add('is-valid');
showSuccess(feedbackElement, 'Port available');
}
})
.catch(error => {
console.error('Validation error:', error);
clearFeedback(feedbackElement);
portField.classList.remove('is-invalid');
portField.classList.remove('is-valid');
});
}, debounceTime);
}
// Helper functions for feedback
function clearFeedback(element) {
element.innerHTML = '';
element.className = 'feedback';
}
function showError(element, message) {
element.innerHTML = message;
element.className = 'feedback invalid-feedback d-block';
}
function showWarning(element, message) {
element.innerHTML = message;
element.className = 'feedback text-warning d-block';
}
function showSuccess(element, message) {
element.innerHTML = message;
element.className = 'feedback valid-feedback d-block';
}
function showLoading(element, message) {
element.innerHTML = `<span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span> ${message}`;
element.className = 'feedback text-muted d-block';
}
});
</script>
{% endblock %}
{% block scripts %}
{{ super() }}
<script src="{{ url_for('static', filename='js/validation.js') }}"></script>
{% endblock %}