3 Commits

Author SHA1 Message Date
jamie f4dc4e0e09 Merge pull request 'V2.1.1' (#58) from v2.1.1 into main
Reviewed-on: http://git.jdbnet.co.uk/jamie/ipam/pulls/58
2026-07-21 11:13:04 +01:00
jamie 7118f917b8 feat: add OpenAPI and Swagger UI endpoints for API documentation
Release / Build & Release (pull_request) Successful in 30s
Release / SonarQube (pull_request) Successful in 25s
2026-07-21 11:12:11 +01:00
jamie 1b3404155c refactor: 🎨 update dashboard activity data structure to use timestamps and add local hour bucketing 2026-07-21 11:05:17 +01:00
8 changed files with 2719 additions and 12 deletions
+2 -1
View File
@@ -10,7 +10,8 @@ LABEL org.opencontainers.image.vendor="JDB-NET"
WORKDIR /app
COPY requirements.txt ./
RUN pip install --no-cache-dir -r requirements.txt
COPY app.py db.py ./
COPY app.py db.py openapi.json ./
COPY static/swagger.html ./static/
COPY --from=frontend /app/static/dist ./static/dist
ARG VERSION=unknown
ENV VERSION=${VERSION}
+26 -7
View File
@@ -2925,14 +2925,14 @@ def api_dashboard():
})
cursor.execute('''
SELECT HOUR(timestamp) AS hour, COUNT(*) AS count
FROM AuditLog
WHERE timestamp >= DATE_SUB(NOW(), INTERVAL 24 HOUR)
GROUP BY HOUR(timestamp)
ORDER BY hour
SELECT timestamp FROM AuditLog
WHERE timestamp >= DATE_SUB(UTC_TIMESTAMP(), INTERVAL 24 HOUR)
''')
activity_by_hour = {row['hour']: row['count'] for row in cursor.fetchall()}
activity = [{'hour': h, 'count': activity_by_hour.get(h, 0)} for h in range(24)]
activity = [
row['timestamp'].strftime('%Y-%m-%d %H:%M:%S')
if hasattr(row['timestamp'], 'strftime') else str(row['timestamp'])
for row in cursor.fetchall()
]
return jsonify({
'stats': {
@@ -3370,6 +3370,25 @@ def api_rack_export(rack_id):
as_attachment=True, download_name=f"{rack['name']}_rack.csv".replace(' ', '_'))
# ── API documentation (OpenAPI + Swagger UI) ────────────────────────────────
OPENAPI_PATH = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'openapi.json')
SWAGGER_HTML = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'static', 'swagger.html')
@app.route('/api/openapi.json')
def api_openapi_spec():
if not os.path.isfile(OPENAPI_PATH):
return jsonify({'error': 'OpenAPI spec not found'}), 404
return send_file(OPENAPI_PATH, mimetype='application/json')
@app.route('/api/docs')
def api_docs():
if not os.path.isfile(SWAGGER_HTML):
return jsonify({'error': 'Swagger UI not found'}), 404
return send_file(SWAGGER_HTML)
# ── SPA static files ──────────────────────────────────────────────────────────
STATIC_ROOT = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'static')
DIST = os.path.join(STATIC_ROOT, 'dist')
+1 -1
View File
@@ -213,7 +213,7 @@ export const api = {
available: number;
status: "active" | "alerting";
}[];
activity: { hour: number; count: number }[];
activity: string[];
}>(await fetchApi("/api/v2/dashboard"));
},
async search(q: string) {
+11
View File
@@ -21,3 +21,14 @@ export function formatLocalTime(ts?: string | null, fallback = "—"): string {
if (!d) return ts?.trim() || fallback;
return d.toLocaleString();
}
/** Bucket audit timestamps from the last 24h by local hour of day (023). */
export function bucketActivityByLocalHour(timestamps: string[]): { hour: number; count: number }[] {
const counts = new Array<number>(24).fill(0);
for (const ts of timestamps) {
const d = parseApiTimestamp(ts);
if (!d) continue;
counts[d.getHours()]++;
}
return counts.map((count, hour) => ({ hour, count }));
}
+2 -1
View File
@@ -3,6 +3,7 @@ import { ref, onMounted, computed } from "vue";
import { RouterLink } from "vue-router";
import { Network, Wifi, Layers, Server } from "lucide-vue-next";
import { api } from "@/api";
import { bucketActivityByLocalHour } from "@/utils/datetime";
interface DashboardStats {
total_ips: number;
@@ -46,7 +47,7 @@ onMounted(async () => {
const d = await api.dashboard();
stats.value = d.stats;
subnetOverview.value = d.subnet_overview;
activity.value = d.activity;
activity.value = bucketActivityByLocalHour(d.activity);
} catch (e) {
error.value = e instanceof Error ? e.message : "Failed to load dashboard";
} finally {
+4 -1
View File
@@ -135,10 +135,13 @@ async function delRole(id: number) {
</div>
<section v-if="tab === 'users'" class="mt-8">
<div class="mb-4 flex items-center justify-between">
<div class="mb-4 flex flex-wrap items-center justify-between gap-3">
<h2 class="font-semibold text-accent">Users</h2>
<div class="flex flex-wrap gap-2">
<a href="/api/docs" target="_blank" rel="noopener noreferrer" class="btn-secondary text-sm">API documentation</a>
<button v-if="auth.can('manage_users')" class="btn-primary text-sm" @click="openAddUser">Add user</button>
</div>
</div>
<ul class="space-y-2">
<li
class="hidden px-4 text-xs font-medium text-slate-500 sm:grid sm:grid-cols-[minmax(0,1fr)_8rem_13rem] sm:items-center sm:gap-4"
+2640
View File
File diff suppressed because it is too large Load Diff
+32
View File
@@ -0,0 +1,32 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>IPAM API Documentation</title>
<link rel="stylesheet" href="https://unpkg.com/swagger-ui-dist@5.17.14/swagger-ui.css" />
<style>
html { box-sizing: border-box; overflow-y: scroll; }
*, *::before, *::after { box-sizing: inherit; }
body { margin: 0; background: #fafafa; }
</style>
</head>
<body>
<div id="swagger-ui"></div>
<script src="https://unpkg.com/swagger-ui-dist@5.17.14/swagger-ui-bundle.js" charset="UTF-8"></script>
<script src="https://unpkg.com/swagger-ui-dist@5.17.14/swagger-ui-standalone-preset.js" charset="UTF-8"></script>
<script>
window.onload = function () {
SwaggerUIBundle({
url: "/api/openapi.json",
dom_id: "#swagger-ui",
deepLinking: true,
presets: [SwaggerUIBundle.presets.apis, SwaggerUIStandalonePreset],
layout: "StandaloneLayout",
tryItOutEnabled: true,
persistAuthorization: true,
});
};
</script>
</body>
</html>