feat: ✨ ip address history
This commit is contained in:
@@ -180,7 +180,99 @@ def invalidate_cache_for_device(device_id):
|
|||||||
"""Invalidate all cache entries related to a device"""
|
"""Invalidate all cache entries related to a device"""
|
||||||
cache.invalidate_device(device_id)
|
cache.invalidate_device(device_id)
|
||||||
cache.clear('devices')
|
cache.clear('devices')
|
||||||
cache.clear('device_list')
|
|
||||||
|
def get_ip_history_from_audit_logs(device_id=None, ip_address=None, conn=None):
|
||||||
|
"""
|
||||||
|
Extract IP assignment history from audit logs.
|
||||||
|
Returns a list of history entries sorted by timestamp (newest first).
|
||||||
|
Each entry contains: ip, action, device_name, subnet_name, subnet_cidr, user_name, timestamp
|
||||||
|
"""
|
||||||
|
import re
|
||||||
|
close_conn = False
|
||||||
|
if conn is None:
|
||||||
|
from flask import current_app
|
||||||
|
conn = get_db_connection(current_app)
|
||||||
|
close_conn = True
|
||||||
|
|
||||||
|
try:
|
||||||
|
cursor = conn.cursor(dictionary=True)
|
||||||
|
|
||||||
|
# Get device name if filtering by device_id
|
||||||
|
device_name = None
|
||||||
|
if device_id:
|
||||||
|
cursor.execute('SELECT name FROM Device WHERE id = %s', (device_id,))
|
||||||
|
device_result = cursor.fetchone()
|
||||||
|
if device_result:
|
||||||
|
device_name = device_result[0]
|
||||||
|
else:
|
||||||
|
# Device doesn't exist, return empty history
|
||||||
|
return []
|
||||||
|
|
||||||
|
# Build query to get relevant audit log entries
|
||||||
|
query = '''
|
||||||
|
SELECT al.id, al.action, al.details, al.timestamp,
|
||||||
|
COALESCE(u.name, 'Deleted User') as user_name,
|
||||||
|
s.name as subnet_name, s.cidr as subnet_cidr
|
||||||
|
FROM AuditLog al
|
||||||
|
LEFT JOIN User u ON al.user_id = u.id
|
||||||
|
LEFT JOIN Subnet s ON al.subnet_id = s.id
|
||||||
|
WHERE (al.action = 'device_add_ip' OR al.action = 'device_delete_ip')
|
||||||
|
'''
|
||||||
|
params = []
|
||||||
|
|
||||||
|
if ip_address:
|
||||||
|
query += ' AND al.details LIKE %s'
|
||||||
|
params.append(f'%IP {ip_address}%')
|
||||||
|
|
||||||
|
query += ' ORDER BY al.timestamp DESC'
|
||||||
|
|
||||||
|
cursor.execute(query, params)
|
||||||
|
logs = cursor.fetchall()
|
||||||
|
|
||||||
|
history = []
|
||||||
|
# Pattern to extract IP, subnet info, and device name from audit log details
|
||||||
|
# Format: "Assigned IP 192.168.1.1 (SubnetName 192.168.1.0/24) to device DeviceName"
|
||||||
|
# Format: "Removed IP 192.168.1.1 (SubnetName 192.168.1.0/24) from device DeviceName"
|
||||||
|
ip_pattern = r'IP\s+([\d\.]+)'
|
||||||
|
device_pattern = r'(?:to|from)\s+device\s+([^\s]+)'
|
||||||
|
|
||||||
|
for log in logs:
|
||||||
|
details = log['details'] or ''
|
||||||
|
|
||||||
|
# Extract IP address
|
||||||
|
ip_match = re.search(ip_pattern, details)
|
||||||
|
if not ip_match:
|
||||||
|
continue
|
||||||
|
|
||||||
|
extracted_ip = ip_match.group(1)
|
||||||
|
|
||||||
|
# If filtering by specific IP, skip if it doesn't match
|
||||||
|
if ip_address and extracted_ip != ip_address:
|
||||||
|
continue
|
||||||
|
|
||||||
|
# Extract device name
|
||||||
|
device_match = re.search(device_pattern, details)
|
||||||
|
extracted_device_name = device_match.group(1) if device_match else 'Unknown'
|
||||||
|
|
||||||
|
# If filtering by device_id, verify device name matches
|
||||||
|
if device_id and device_name:
|
||||||
|
if extracted_device_name != device_name:
|
||||||
|
continue
|
||||||
|
|
||||||
|
history.append({
|
||||||
|
'ip': extracted_ip,
|
||||||
|
'action': 'assigned' if log['action'] == 'device_add_ip' else 'removed',
|
||||||
|
'device_name': extracted_device_name,
|
||||||
|
'subnet_name': log['subnet_name'] or 'Unknown',
|
||||||
|
'subnet_cidr': log['subnet_cidr'] or '',
|
||||||
|
'user_name': log['user_name'],
|
||||||
|
'timestamp': log['timestamp']
|
||||||
|
})
|
||||||
|
|
||||||
|
return history
|
||||||
|
finally:
|
||||||
|
if close_conn:
|
||||||
|
conn.close()
|
||||||
|
|
||||||
def invalidate_cache_for_subnet(subnet_id):
|
def invalidate_cache_for_subnet(subnet_id):
|
||||||
"""Invalidate all cache entries related to a subnet"""
|
"""Invalidate all cache entries related to a subnet"""
|
||||||
@@ -856,12 +948,34 @@ def register_routes(app, limiter=None):
|
|||||||
in_range = False
|
in_range = False
|
||||||
ips = filtered_ips
|
ips = filtered_ips
|
||||||
available_ips_by_subnet[subnet['id']] = ips
|
available_ips_by_subnet[subnet['id']] = ips
|
||||||
|
# Get IP history for this device
|
||||||
|
ip_history = get_ip_history_from_audit_logs(device_id=device_id, conn=conn)
|
||||||
|
|
||||||
return render_with_user('device.html',
|
return render_with_user('device.html',
|
||||||
device={'id': device[0], 'name': device[1], 'description': device[2], 'device_type_id': device[3]},
|
device={'id': device[0], 'name': device[1], 'description': device[2], 'device_type_id': device[3]},
|
||||||
subnets=subnets, device_ips=device_ips, available_ips_by_subnet=available_ips_by_subnet,
|
subnets=subnets, device_ips=device_ips, available_ips_by_subnet=available_ips_by_subnet,
|
||||||
device_types=device_types, device_tags=device_tags, all_tags=all_tags,
|
device_types=device_types, device_tags=device_tags, all_tags=all_tags,
|
||||||
can_assign_device_tag=has_permission('assign_device_tag'),
|
can_assign_device_tag=has_permission('assign_device_tag'),
|
||||||
can_remove_device_tag=has_permission('remove_device_tag'))
|
can_remove_device_tag=has_permission('remove_device_tag'),
|
||||||
|
ip_history=ip_history)
|
||||||
|
|
||||||
|
@app.route('/api/device/<int:device_id>/ip_history')
|
||||||
|
@permission_required('view_device')
|
||||||
|
def device_ip_history(device_id):
|
||||||
|
"""Get IP history for a device as JSON"""
|
||||||
|
from flask import current_app
|
||||||
|
with get_db_connection(current_app) as conn:
|
||||||
|
ip_history = get_ip_history_from_audit_logs(device_id=device_id, conn=conn)
|
||||||
|
return jsonify({'history': ip_history})
|
||||||
|
|
||||||
|
@app.route('/api/ip/<ip_address>/history')
|
||||||
|
@permission_required('view_subnet')
|
||||||
|
def ip_address_history(ip_address):
|
||||||
|
"""Get IP history for a specific IP address as JSON"""
|
||||||
|
from flask import current_app
|
||||||
|
with get_db_connection(current_app) as conn:
|
||||||
|
ip_history = get_ip_history_from_audit_logs(ip_address=ip_address, conn=conn)
|
||||||
|
return jsonify({'history': ip_history, 'ip': ip_address})
|
||||||
|
|
||||||
@app.route('/update_device_type', methods=['POST'])
|
@app.route('/update_device_type', methods=['POST'])
|
||||||
@permission_required('edit_device')
|
@permission_required('edit_device')
|
||||||
|
|||||||
@@ -0,0 +1,104 @@
|
|||||||
|
// IP History Modal functionality
|
||||||
|
document.addEventListener('DOMContentLoaded', function() {
|
||||||
|
const modal = document.getElementById('ip-history-modal');
|
||||||
|
const closeBtn = document.getElementById('close-ip-history-modal');
|
||||||
|
const content = document.getElementById('ip-history-content');
|
||||||
|
const ipAddressSpan = document.getElementById('modal-ip-address');
|
||||||
|
|
||||||
|
// Open modal when IP is clicked
|
||||||
|
document.querySelectorAll('.ip-history-btn').forEach(btn => {
|
||||||
|
btn.addEventListener('click', function() {
|
||||||
|
const ip = this.getAttribute('data-ip');
|
||||||
|
ipAddressSpan.textContent = ip;
|
||||||
|
modal.classList.remove('hidden');
|
||||||
|
modal.classList.add('flex');
|
||||||
|
loadIPHistory(ip);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
// Close modal
|
||||||
|
closeBtn.addEventListener('click', function() {
|
||||||
|
modal.classList.add('hidden');
|
||||||
|
modal.classList.remove('flex');
|
||||||
|
});
|
||||||
|
|
||||||
|
// Close modal when clicking outside
|
||||||
|
modal.addEventListener('click', function(e) {
|
||||||
|
if (e.target === modal) {
|
||||||
|
modal.classList.add('hidden');
|
||||||
|
modal.classList.remove('flex');
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// Close modal with Escape key
|
||||||
|
document.addEventListener('keydown', function(e) {
|
||||||
|
if (e.key === 'Escape' && !modal.classList.contains('hidden')) {
|
||||||
|
modal.classList.add('hidden');
|
||||||
|
modal.classList.remove('flex');
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
function loadIPHistory(ip) {
|
||||||
|
content.innerHTML = '<div class="text-center text-gray-600 dark:text-gray-400">Loading...</div>';
|
||||||
|
|
||||||
|
fetch(`/api/ip/${encodeURIComponent(ip)}/history`)
|
||||||
|
.then(response => response.json())
|
||||||
|
.then(data => {
|
||||||
|
if (data.history && data.history.length > 0) {
|
||||||
|
displayHistory(data.history);
|
||||||
|
} else {
|
||||||
|
content.innerHTML = '<div class="text-center text-gray-600 dark:text-gray-400">No history found for this IP address.</div>';
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.catch(error => {
|
||||||
|
console.error('Error loading IP history:', error);
|
||||||
|
content.innerHTML = '<div class="text-center text-red-500">Error loading IP history. Please try again.</div>';
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function displayHistory(history) {
|
||||||
|
let html = '<div class="space-y-3">';
|
||||||
|
|
||||||
|
history.forEach((entry, index) => {
|
||||||
|
const isAssigned = entry.action === 'assigned';
|
||||||
|
const icon = isAssigned ? 'fa-plus-circle text-green-500' : 'fa-minus-circle text-red-500';
|
||||||
|
const actionText = isAssigned ? 'Assigned' : 'Removed';
|
||||||
|
|
||||||
|
// Format timestamp
|
||||||
|
let timestamp = 'Unknown';
|
||||||
|
if (entry.timestamp) {
|
||||||
|
try {
|
||||||
|
const date = new Date(entry.timestamp);
|
||||||
|
timestamp = date.toLocaleString();
|
||||||
|
} catch (e) {
|
||||||
|
timestamp = entry.timestamp;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
html += `
|
||||||
|
<div class="flex items-start gap-3 pb-3 ${index < history.length - 1 ? 'border-b border-gray-400 dark:border-zinc-600' : ''}">
|
||||||
|
<div class="flex-shrink-0 mt-1">
|
||||||
|
<i class="fas ${icon}"></i>
|
||||||
|
</div>
|
||||||
|
<div class="flex-1 min-w-0">
|
||||||
|
<div class="flex items-center gap-2 flex-wrap">
|
||||||
|
<span class="font-semibold">${actionText}</span>
|
||||||
|
<span class="text-gray-600 dark:text-gray-400">to</span>
|
||||||
|
<span class="font-semibold">${entry.device_name || 'Unknown'}</span>
|
||||||
|
</div>
|
||||||
|
<div class="text-sm text-gray-600 dark:text-gray-400 mt-1">
|
||||||
|
${entry.subnet_name || 'Unknown'} (${entry.subnet_cidr || 'N/A'})
|
||||||
|
</div>
|
||||||
|
<div class="text-xs text-gray-500 dark:text-gray-500 mt-1">
|
||||||
|
by ${entry.user_name || 'Unknown'} • ${timestamp}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
`;
|
||||||
|
});
|
||||||
|
|
||||||
|
html += '</div>';
|
||||||
|
content.innerHTML = html;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
@@ -75,6 +75,45 @@
|
|||||||
</ul>
|
</ul>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
<!-- IP History Section -->
|
||||||
|
{% if ip_history %}
|
||||||
|
<div class="ip-history mb-6">
|
||||||
|
<h3 class="text-lg font-bold mb-2">IP Assignment History:</h3>
|
||||||
|
<div class="bg-gray-200 dark:bg-zinc-700 rounded-lg p-4 max-h-96 overflow-y-auto">
|
||||||
|
<div class="space-y-3">
|
||||||
|
{% for entry in ip_history %}
|
||||||
|
<div class="flex items-start gap-3 pb-3 {% if not loop.last %}border-b border-gray-400 dark:border-zinc-600{% endif %}">
|
||||||
|
<div class="flex-shrink-0 mt-1">
|
||||||
|
{% if entry.action == 'assigned' %}
|
||||||
|
<i class="fas fa-plus-circle text-green-500"></i>
|
||||||
|
{% else %}
|
||||||
|
<i class="fas fa-minus-circle text-red-500"></i>
|
||||||
|
{% endif %}
|
||||||
|
</div>
|
||||||
|
<div class="flex-1 min-w-0">
|
||||||
|
<div class="flex items-center gap-2 flex-wrap">
|
||||||
|
<span class="font-mono font-semibold">{{ entry.ip }}</span>
|
||||||
|
<span class="text-sm text-gray-600 dark:text-gray-400">
|
||||||
|
{% if entry.action == 'assigned' %}Assigned{% else %}Removed{% endif %}
|
||||||
|
</span>
|
||||||
|
<span class="text-sm text-gray-600 dark:text-gray-400">
|
||||||
|
to {{ entry.device_name }}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
<div class="text-sm text-gray-600 dark:text-gray-400 mt-1">
|
||||||
|
{{ entry.subnet_name }} ({{ entry.subnet_cidr }})
|
||||||
|
</div>
|
||||||
|
<div class="text-xs text-gray-500 dark:text-gray-500 mt-1">
|
||||||
|
by {{ entry.user_name }} • {{ entry.timestamp.strftime('%Y-%m-%d %H:%M:%S') if entry.timestamp else 'Unknown' }}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
{% endfor %}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
{% endif %}
|
||||||
|
|
||||||
<!-- Tags Section -->
|
<!-- Tags Section -->
|
||||||
<div class="tags-section mb-6">
|
<div class="tags-section mb-6">
|
||||||
<h3 class="text-lg font-bold mb-2">Tags:</h3>
|
<h3 class="text-lg font-bold mb-2">Tags:</h3>
|
||||||
|
|||||||
+20
-1
@@ -50,7 +50,11 @@
|
|||||||
<tbody class="divide-y divide-gray-700">
|
<tbody class="divide-y divide-gray-700">
|
||||||
{% for ip in ip_addresses %}
|
{% for ip in ip_addresses %}
|
||||||
<tr id="ip-{{ ip[0] }}">
|
<tr id="ip-{{ ip[0] }}">
|
||||||
<td class="font-bold text-center">{{ ip[1] }}</td>
|
<td class="font-bold text-center">
|
||||||
|
<button type="button" class="ip-history-btn hover:text-blue-400 cursor-pointer" data-ip="{{ ip[1] }}" title="View IP history">
|
||||||
|
{{ ip[1] }}
|
||||||
|
</button>
|
||||||
|
</td>
|
||||||
<td class="text-center">
|
<td class="text-center">
|
||||||
{% if ip[2] == 'DHCP' %}
|
{% if ip[2] == 'DHCP' %}
|
||||||
<span class="font-semibold">DHCP</span>
|
<span class="font-semibold">DHCP</span>
|
||||||
@@ -72,7 +76,22 @@
|
|||||||
</form>
|
</form>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
<!-- IP History Modal -->
|
||||||
|
<div id="ip-history-modal" class="hidden fixed inset-0 bg-black/30 backdrop-blur-md flex items-center justify-center z-50">
|
||||||
|
<div class="bg-gray-200 dark:bg-zinc-800 rounded-lg p-6 max-w-2xl w-full mx-4 max-h-[90vh] overflow-y-auto shadow-2xl border border-gray-300 dark:border-zinc-700">
|
||||||
|
<div class="flex justify-between items-center mb-4">
|
||||||
|
<h2 class="text-2xl font-bold">IP History: <span id="modal-ip-address" class="font-mono"></span></h2>
|
||||||
|
<button type="button" id="close-ip-history-modal" class="text-gray-600 dark:text-gray-400 hover:text-gray-800 dark:hover:text-gray-200 hover:cursor-pointer text-2xl">×</button>
|
||||||
|
</div>
|
||||||
|
<div id="ip-history-content" class="space-y-3">
|
||||||
|
<div class="text-center text-gray-600 dark:text-gray-400">Loading...</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
<script src="/static/js/export_csv.js"></script>
|
<script src="/static/js/export_csv.js"></script>
|
||||||
<script src="/static/js/subnet.js"></script>
|
<script src="/static/js/subnet.js"></script>
|
||||||
|
<script src="/static/js/ip_history.js"></script>
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
Reference in New Issue
Block a user