Compare commits
13 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
481966fcba | ||
|
|
7e2851e40a | ||
|
|
bd08dcc212 | ||
|
|
22469ac206 | ||
|
|
79dbd98ca6 | ||
|
|
a404a37a60 | ||
|
|
6a5ddd66ba | ||
|
|
35e59c4879 | ||
|
|
2b863776ae | ||
|
|
269b098f0d | ||
|
|
af252c4498 | ||
|
|
e0490e42c5 | ||
|
|
4c4d254852 |
@@ -36,21 +36,8 @@ services:
|
||||
networks:
|
||||
- snoopBack
|
||||
|
||||
vault:
|
||||
image: hashicorp/vault:1.16
|
||||
environment:
|
||||
VAULT_API_ADDR: http://0.0.0.0:8200
|
||||
VAULT_TOKEN: root
|
||||
ports:
|
||||
- 8200:8200
|
||||
cap_add:
|
||||
- IPC_LOCK
|
||||
volumes:
|
||||
- vault-data:/vault/data
|
||||
networks:
|
||||
- snoopBack
|
||||
|
||||
snoop-api:
|
||||
restart: unless-stopped
|
||||
build:
|
||||
context: ./server
|
||||
dockerfile: Dockerfile
|
||||
@@ -61,6 +48,7 @@ services:
|
||||
VAULT_TOKEN: "root"
|
||||
VAULT_KV_PATH: "kv/data/snoop"
|
||||
MINIO_ENDPOINT: "http://minio:9000"
|
||||
JWT_SECRET: ${JWT_SECRET}
|
||||
env_file:
|
||||
- .env
|
||||
depends_on:
|
||||
@@ -75,6 +63,7 @@ services:
|
||||
|
||||
|
||||
web:
|
||||
restart: unless-stopped
|
||||
build:
|
||||
context: ./management-ui
|
||||
dockerfile: Dockerfile
|
||||
@@ -90,17 +79,84 @@ services:
|
||||
- snoop-api
|
||||
ports:
|
||||
- "80:80"
|
||||
- "443:443"
|
||||
volumes:
|
||||
- ./nginx/dev.conf:/etc/nginx/conf.d/default.conf:ro,Z
|
||||
# - ./nginx/nginx_ssl/fullchain.pem:/etc/nginx/ssl/certs/fullchain.pem
|
||||
# - ./nginx/nginx_ssl/privkey.pem:/etc/nginx/ssl/certs/privkey.pem
|
||||
- ./nginx/nginx_ssl:/etc/nginx/ssl/certs/:ro,Z
|
||||
- ./nginx/nginx_ssl/iot_int_cert.pem:/etc/nginx/ssl/iot_int_cert.pem:ro,Z
|
||||
- ./nginx/nginx_ssl/iot.crl:/etc/nginx/ssl/iot.crl:ro,Z
|
||||
networks:
|
||||
- proxy
|
||||
|
||||
mediamtx:
|
||||
image: bluenviron/mediamtx:latest
|
||||
# restart: unless-stopped
|
||||
# Expose default listeners for all common protocols
|
||||
ports:
|
||||
- "8554:8554" # RTSP
|
||||
- "1935:1935" # RTMP
|
||||
- "8888:8888" # HLS / LL-HLS (HTTP)
|
||||
- "8889:8889" # WebRTC HTTP (WHIP/WHEP/pages)
|
||||
- "8189:8189/udp" # WebRTC ICE UDP
|
||||
- "8890:8890/udp" # SRT
|
||||
- "9997:9997" # Control API (enabled in config below; map if you want to access from host)
|
||||
volumes:
|
||||
- ./mediamtx/mediamtx.yml:/mediamtx.yml:ro,Z
|
||||
- mediamtx-recordings:/recordings
|
||||
networks:
|
||||
- proxy
|
||||
- snoopBack
|
||||
|
||||
rclone:
|
||||
image: rclone/rclone:latest
|
||||
command: rcd --rc-addr=:5572 --rc-no-auth
|
||||
environment:
|
||||
RCLONE_CONFIG_MINIO_TYPE: s3
|
||||
RCLONE_CONFIG_MINIO_PROVIDER: Minio
|
||||
RCLONE_CONFIG_MINIO_ENDPOINT: http://minio:9000
|
||||
RCLONE_CONFIG_MINIO_ACCESS_KEY_ID: minioadmin
|
||||
RCLONE_CONFIG_MINIO_SECRET_ACCESS_KEY: minioadmin
|
||||
RCLONE_CONFIG_MINIO_REGION: us-east-1
|
||||
RCLONE_CONFIG_MINIO_FORCE_PATH_STYLE: "true"
|
||||
volumes:
|
||||
- mediamtx-recordings:/recordings
|
||||
networks:
|
||||
- snoopBack
|
||||
- proxy
|
||||
|
||||
# NEW: EMQX MQTT broker
|
||||
emqx:
|
||||
image: emqx/emqx:latest # EMQX 5.x
|
||||
restart: unless-stopped
|
||||
environment:
|
||||
# set a fixed node name (nice when you later add clustering)
|
||||
EMQX_NODE__NAME: emqx@node1
|
||||
# set dashboard admin user/pass (change these in prod!)
|
||||
EMQX_DASHBOARD__DEFAULT_USERNAME: admin
|
||||
EMQX_DASHBOARD__DEFAULT_PASSWORD: changeme123
|
||||
# optional: enable WebSocket listener on 8083 (on by default in 5.x)
|
||||
# EMQX_LISTENERS__WS__DEFAULT__ENABLE: "true"
|
||||
volumes:
|
||||
- emqx-data:/opt/emqx/data
|
||||
- emqx-log:/opt/emqx/log
|
||||
ports:
|
||||
- "1883:1883" # MQTT (TCP)
|
||||
- "8083:8083" # MQTT over WebSocket (WS)
|
||||
# - "8883:8883" # MQTT over TLS (uncomment when you add certs)
|
||||
# - "8084:8084" # WSS (uncomment with TLS)
|
||||
- "18083:18083" # Dashboard
|
||||
networks:
|
||||
- snoopBack
|
||||
- proxy # so Nginx can reverse-proxy WS at /mqtt/ws
|
||||
|
||||
volumes:
|
||||
pgdata:
|
||||
miniodata:
|
||||
vault-data:
|
||||
mediamtx-recordings:
|
||||
emqx-data:
|
||||
emqx-log:
|
||||
|
||||
networks:
|
||||
proxy:
|
||||
|
||||
25
management-ui/package-lock.json
generated
25
management-ui/package-lock.json
generated
@@ -14,6 +14,7 @@
|
||||
"axios": "^1.11.0",
|
||||
"class-variance-authority": "^0.7.1",
|
||||
"clsx": "^2.1.1",
|
||||
"leaflet": "^1.9.4",
|
||||
"lucide-vue-next": "^0.525.0",
|
||||
"reka-ui": "^2.5.0",
|
||||
"tailwind-merge": "^3.3.1",
|
||||
@@ -28,6 +29,7 @@
|
||||
"devDependencies": {
|
||||
"@iconify-json/radix-icons": "^1.2.2",
|
||||
"@iconify/vue": "^5.0.0",
|
||||
"@types/leaflet": "^1.9.20",
|
||||
"@types/node": "^24.1.0",
|
||||
"@vitejs/plugin-vue": "^6.0.0",
|
||||
"@vue/tsconfig": "^0.7.0",
|
||||
@@ -1273,6 +1275,23 @@
|
||||
"integrity": "sha512-dWHzHa2WqEXI/O1E9OjrocMTKJl2mSrEolh1Iomrv6U+JuNwaHXsXx9bLu5gG7BUWFIN0skIQJQ/L1rIex4X6w==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/@types/geojson": {
|
||||
"version": "7946.0.16",
|
||||
"resolved": "https://registry.npmjs.org/@types/geojson/-/geojson-7946.0.16.tgz",
|
||||
"integrity": "sha512-6C8nqWur3j98U6+lXDfTUWIfgvZU+EumvpHKcYjujKH7woYyLj2sUmff0tRhrqM7BohUw7Pz3ZB1jj2gW9Fvmg==",
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/@types/leaflet": {
|
||||
"version": "1.9.20",
|
||||
"resolved": "https://registry.npmjs.org/@types/leaflet/-/leaflet-1.9.20.tgz",
|
||||
"integrity": "sha512-rooalPMlk61LCaLOvBF2VIf9M47HgMQqi5xQ9QRi7c8PkdIe0WrIi5IxXUXQjAdL0c+vcQ01mYWbthzmp9GHWw==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@types/geojson": "*"
|
||||
}
|
||||
},
|
||||
"node_modules/@types/node": {
|
||||
"version": "24.1.0",
|
||||
"resolved": "https://registry.npmjs.org/@types/node/-/node-24.1.0.tgz",
|
||||
@@ -1996,6 +2015,12 @@
|
||||
"jiti": "lib/jiti-cli.mjs"
|
||||
}
|
||||
},
|
||||
"node_modules/leaflet": {
|
||||
"version": "1.9.4",
|
||||
"resolved": "https://registry.npmjs.org/leaflet/-/leaflet-1.9.4.tgz",
|
||||
"integrity": "sha512-nxS1ynzJOmOlHp+iL3FyWqK89GtNL8U8rvlMOsQdTTssxZwCXh8N2NB3GDQOL+YR3XnWyZAxwQixURb+FA74PA==",
|
||||
"license": "BSD-2-Clause"
|
||||
},
|
||||
"node_modules/lightningcss": {
|
||||
"version": "1.30.1",
|
||||
"resolved": "https://registry.npmjs.org/lightningcss/-/lightningcss-1.30.1.tgz",
|
||||
|
||||
@@ -15,6 +15,7 @@
|
||||
"axios": "^1.11.0",
|
||||
"class-variance-authority": "^0.7.1",
|
||||
"clsx": "^2.1.1",
|
||||
"leaflet": "^1.9.4",
|
||||
"lucide-vue-next": "^0.525.0",
|
||||
"reka-ui": "^2.5.0",
|
||||
"tailwind-merge": "^3.3.1",
|
||||
@@ -29,6 +30,7 @@
|
||||
"devDependencies": {
|
||||
"@iconify-json/radix-icons": "^1.2.2",
|
||||
"@iconify/vue": "^5.0.0",
|
||||
"@types/leaflet": "^1.9.20",
|
||||
"@types/node": "^24.1.0",
|
||||
"@vitejs/plugin-vue": "^6.0.0",
|
||||
"@vue/tsconfig": "^0.7.0",
|
||||
|
||||
@@ -1,40 +1,66 @@
|
||||
<script setup lang="ts">
|
||||
import { DropdownMenu, DropdownMenuItem,
|
||||
DropdownMenuTrigger, DropdownMenuContent } from '@/components/ui/dropdown-menu';
|
||||
import { Ellipsis } from 'lucide-vue-next';
|
||||
import EditDeviceDialog from './EditDeviceDialog.vue';
|
||||
import DeleteDeviceDialog from './DeleteDeviceDialog.vue';
|
||||
import { ref } from 'vue';
|
||||
import { ref } from 'vue'
|
||||
import {
|
||||
DropdownMenu, DropdownMenuItem,
|
||||
DropdownMenuTrigger, DropdownMenuContent
|
||||
} from '@/components/ui/dropdown-menu'
|
||||
import EditDeviceDialog from './EditDeviceDialog.vue'
|
||||
import DeleteDeviceDialog from './DeleteDeviceDialog.vue'
|
||||
import DeviceCertificateDialog from './DeviceCertificateDialog.vue'
|
||||
import DeviceTasksDialog from './DeviceTasksDialog.vue'
|
||||
import { Ellipsis } from 'lucide-vue-next'
|
||||
import type { Device, Users } from '@/lib/interfaces'
|
||||
// import { api } from '@/lib/api'
|
||||
|
||||
|
||||
const props = defineProps<{ row: Device; allUsers?: Users[] }>()
|
||||
|
||||
const isEditOpen = ref(false)
|
||||
const isDeleteOpen = ref(false)
|
||||
const isTasksOpen = ref(false)
|
||||
const itCertsOpen = ref(false)
|
||||
|
||||
const emit = defineEmits<{
|
||||
(e: 'updated', payload: { name: string; userIds: string[] }): void
|
||||
(e: 'deleted'): void
|
||||
}>()
|
||||
|
||||
// your actual delete logic
|
||||
function onDeleteConfirmed() {
|
||||
// e.g. await api.deleteUser(props.userId)
|
||||
// await api.delete(`/devices/${encodeURIComponent(props.row.guid)}`)
|
||||
isDeleteOpen.value = false
|
||||
emit('deleted')
|
||||
}
|
||||
function onEditConfirm() {
|
||||
isEditOpen.value = false
|
||||
function onEditConfirm(_payload: { name: string; userIds: string[] }) {
|
||||
isEditOpen.value = false
|
||||
emit('updated', _payload)
|
||||
}
|
||||
|
||||
function onTaskConfirm() {
|
||||
isTasksOpen.value = false
|
||||
}
|
||||
|
||||
function onCertsConfirm() {
|
||||
itCertsOpen.value = false
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<DropdownMenu>
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<button class="p-2 rounded hover:bg-muted">
|
||||
<Ellipsis/>
|
||||
</button>
|
||||
<button class="p-2 rounded hover:bg-muted">
|
||||
<Ellipsis />
|
||||
</button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end" class="w-[160px]">
|
||||
<DropdownMenuItem @click.prevent="isEditOpen = true">
|
||||
Rename
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem @click.prevent="isDeleteOpen = true">
|
||||
Delete
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem @click.prevent="isEditOpen = true">Rename</DropdownMenuItem>
|
||||
<DropdownMenuItem @click.prevent="isTasksOpen = true">Tasks</DropdownMenuItem>
|
||||
<DropdownMenuItem @click.prevent="itCertsOpen = true">Certificates</DropdownMenuItem>
|
||||
<DropdownMenuItem class="text-destructive" @click.prevent="isDeleteOpen = true">Delete</DropdownMenuItem>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
<EditDeviceDialog v-model:modelValue="isEditOpen"@confirm="onEditConfirm()" />
|
||||
<DeleteDeviceDialog v-model:modelValue="isDeleteOpen" @confirm="onDeleteConfirmed" />
|
||||
</DropdownMenu>
|
||||
|
||||
<EditDeviceDialog v-model:modelValue="isEditOpen" :device="props.row" :all-users="props.allUsers" @updated="onEditConfirm" />
|
||||
<DeleteDeviceDialog v-model:modelValue="isDeleteOpen" :device="props.row" @confirm="onDeleteConfirmed" />
|
||||
<DeviceCertificateDialog v-model:modelValue="itCertsOpen" :device="props.row" @confirm="onCertsConfirm" />
|
||||
<DeviceTasksDialog v-model:modelValue="isTasksOpen" :device="props.row" @confirm="onTaskConfirm" />
|
||||
</template>
|
||||
66
management-ui/src/customcompometns/AdminTrackerDropdown.vue
Normal file
66
management-ui/src/customcompometns/AdminTrackerDropdown.vue
Normal file
@@ -0,0 +1,66 @@
|
||||
<script setup lang="ts">
|
||||
import { ref } from 'vue'
|
||||
import {
|
||||
DropdownMenu, DropdownMenuItem,
|
||||
DropdownMenuTrigger, DropdownMenuContent
|
||||
} from '@/components/ui/dropdown-menu'
|
||||
import EditTrackerDialog from './EditTrackerDialog.vue'
|
||||
import DeleteDeviceDialog from './DeleteDeviceDialog.vue'
|
||||
import DeviceCertificateDialog from './DeviceCertificateDialog.vue'
|
||||
import DeviceTasksDialog from './DeviceTasksDialog.vue'
|
||||
import { Ellipsis } from 'lucide-vue-next'
|
||||
import type { Device, Users } from '@/lib/interfaces'
|
||||
// import { api } from '@/lib/api'
|
||||
|
||||
|
||||
const props = defineProps<{ row: Device; allUsers?: Users[] }>()
|
||||
|
||||
const isEditOpen = ref(false)
|
||||
const isDeleteOpen = ref(false)
|
||||
const isTasksOpen = ref(false)
|
||||
const itCertsOpen = ref(false)
|
||||
|
||||
const emit = defineEmits<{
|
||||
(e: 'updated', payload: { name: string; userIds: string[] }): void
|
||||
(e: 'deleted'): void
|
||||
}>()
|
||||
|
||||
function onDeleteConfirmed() {
|
||||
// await api.delete(`/devices/${encodeURIComponent(props.row.guid)}`)
|
||||
isDeleteOpen.value = false
|
||||
emit('deleted')
|
||||
}
|
||||
function onEditConfirm(_payload: { name: string; userIds: string[] }) {
|
||||
isEditOpen.value = false
|
||||
emit('updated', _payload)
|
||||
}
|
||||
|
||||
function onTaskConfirm() {
|
||||
isTasksOpen.value = false
|
||||
}
|
||||
|
||||
function onCertsConfirm() {
|
||||
itCertsOpen.value = false
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<button class="p-2 rounded hover:bg-muted">
|
||||
<Ellipsis />
|
||||
</button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end" class="w-[160px]">
|
||||
<DropdownMenuItem @click.prevent="isEditOpen = true">Rename</DropdownMenuItem>
|
||||
<DropdownMenuItem @click.prevent="isTasksOpen = true">Tasks</DropdownMenuItem>
|
||||
<DropdownMenuItem @click.prevent="itCertsOpen = true">Certificates</DropdownMenuItem>
|
||||
<DropdownMenuItem class="text-destructive" @click.prevent="isDeleteOpen = true">Delete</DropdownMenuItem>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
|
||||
<EditTrackerDialog v-model:modelValue="isEditOpen" :device="props.row" :all-users="props.allUsers" @updated="onEditConfirm" />
|
||||
<DeleteDeviceDialog v-model:modelValue="isDeleteOpen" :device="props.row" @confirm="onDeleteConfirmed" />
|
||||
<DeviceCertificateDialog v-model:modelValue="itCertsOpen" :device="props.row" @confirm="onCertsConfirm" />
|
||||
<DeviceTasksDialog v-model:modelValue="isTasksOpen" :device="props.row" @confirm="onTaskConfirm" />
|
||||
</template>
|
||||
@@ -1,16 +1,16 @@
|
||||
<script setup lang="ts">
|
||||
import { ref } from 'vue'
|
||||
import {
|
||||
DropdownMenu, DropdownMenuItem,
|
||||
DropdownMenuTrigger, DropdownMenuContent
|
||||
} from '@/components/ui/dropdown-menu'
|
||||
|
||||
import EditUserDialog from './EditUserDialog.vue'
|
||||
import DeleteUserDialog from './DeleteUserDialog.vue'
|
||||
import { Ellipsis } from 'lucide-vue-next'
|
||||
import { ref } from 'vue'
|
||||
import { api } from '@/lib/api' // <-- use your axios/fetch wrapper
|
||||
import { api } from '@/lib/api'
|
||||
import type { Users } from '@/lib/interfaces'
|
||||
|
||||
const props = defineProps<{ userId: string }>()
|
||||
const props = defineProps<{ row: Users }>() // ← accept full row
|
||||
const emit = defineEmits<{
|
||||
(e: 'deleted', id: string): void
|
||||
(e: 'error', err: unknown): void
|
||||
@@ -20,18 +20,17 @@ const isEditOpen = ref(false)
|
||||
const isDeleteOpen = ref(false)
|
||||
const deleting = ref(false)
|
||||
|
||||
// DELETE /users/:id
|
||||
async function onDeleteConfirmed() {
|
||||
try {
|
||||
deleting.value = true
|
||||
await api.delete(`/users/${encodeURIComponent(props.userId)}`)
|
||||
emit('deleted', props.userId)
|
||||
await api.delete(`/users/${encodeURIComponent(String(props.row.id))}`)
|
||||
emit('deleted', String(props.row.id))
|
||||
} catch (err) {
|
||||
console.error(err)
|
||||
emit('error', err)
|
||||
} finally {
|
||||
deleting.value = false
|
||||
// The dialog already closes itself on confirm; nothing else required.
|
||||
// DeleteUserDialog closes itself after confirm
|
||||
}
|
||||
}
|
||||
|
||||
@@ -49,21 +48,13 @@ function onEditConfirm() {
|
||||
</DropdownMenuTrigger>
|
||||
|
||||
<DropdownMenuContent align="end" class="w-[160px]">
|
||||
<DropdownMenuItem @click.prevent="isEditOpen = true">
|
||||
Edit
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem @click.prevent="isEditOpen = true">Edit</DropdownMenuItem>
|
||||
<DropdownMenuItem @click.prevent="isDeleteOpen = true" :disabled="deleting">
|
||||
Delete
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
|
||||
<EditUserDialog v-model:modelValue="isEditOpen" @confirm="onEditConfirm()" />
|
||||
|
||||
<!-- pass 'deleting' to disable the confirm button during request -->
|
||||
<DeleteUserDialog
|
||||
v-model:modelValue="isDeleteOpen"
|
||||
:loading="deleting"
|
||||
@confirm="onDeleteConfirmed"
|
||||
/>
|
||||
<EditUserDialog v-model:modelValue="isEditOpen" @confirm="onEditConfirm" />
|
||||
<DeleteUserDialog v-model:modelValue="isDeleteOpen" :loading="deleting" @confirm="onDeleteConfirmed" />
|
||||
</template>
|
||||
@@ -1,38 +1,34 @@
|
||||
<script setup lang="ts">
|
||||
import { Tabs, TabsContent, TabsTrigger, TabsList } from '@/components/ui/tabs';
|
||||
import DataTableNoCheckbox from './DataTableNoCheckbox.vue';
|
||||
import AdminUserDropdonw from './AdminUserDropdonw.vue';
|
||||
import AdminDeviceDropdown from './AdminDeviceDropdown.vue';
|
||||
import type { Device, Users } from '@/lib/interfaces';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { onBeforeUnmount, onMounted, ref } from 'vue';
|
||||
import { api } from '@/lib/api';
|
||||
|
||||
|
||||
import { Tabs, TabsContent, TabsTrigger, TabsList } from '@/components/ui/tabs'
|
||||
import DataTableNoCheckbox from './DataTableNoCheckbox.vue'
|
||||
import AdminUserDropdonw from './AdminUserDropdonw.vue'
|
||||
import AdminDeviceDropdown from './AdminDeviceDropdown.vue'
|
||||
import AdminTrackerDropdown from './AdminTrackerDropdown.vue'
|
||||
import type { Device, Users } from '@/lib/interfaces'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { onBeforeUnmount, onMounted, ref, computed } from 'vue'
|
||||
import { api } from '@/lib/api'
|
||||
|
||||
// ---------------- Users ----------------
|
||||
const user_columns = [
|
||||
{ accessorKey: 'id', header: 'ID' },
|
||||
{ accessorKey: 'username', header: 'Username' },
|
||||
{ accessorKey: 'role', header: 'Role' },
|
||||
]
|
||||
|
||||
const user_data = ref<Users[]>([])
|
||||
const usersLoading = ref(false)
|
||||
const usersError = ref<string | null>(null)
|
||||
|
||||
function isUsersArray(data: unknown): data is Users[] {
|
||||
return Array.isArray(data) && data.every(
|
||||
(u) =>
|
||||
u &&
|
||||
typeof u === 'object' &&
|
||||
typeof (u as any).id === 'number' &&
|
||||
typeof (u as any).username === 'string' &&
|
||||
typeof (u as any).role === 'string'
|
||||
(u) => u && typeof u === 'object'
|
||||
&& typeof (u as any).id === 'number'
|
||||
&& typeof (u as any).username === 'string'
|
||||
&& typeof (u as any).role === 'string'
|
||||
)
|
||||
}
|
||||
|
||||
let ctrl: AbortController | null = null
|
||||
|
||||
async function loadUsers() {
|
||||
usersError.value = null
|
||||
usersLoading.value = true
|
||||
@@ -40,27 +36,23 @@ async function loadUsers() {
|
||||
ctrl?.abort()
|
||||
ctrl = new AbortController()
|
||||
const { data } = await api.get('/users', { signal: ctrl.signal })
|
||||
|
||||
if (!isUsersArray(data)) {
|
||||
throw new Error('Unexpected response shape')
|
||||
}
|
||||
|
||||
if (!isUsersArray(data)) throw new Error('Unexpected response shape')
|
||||
user_data.value = data
|
||||
} catch (e: any) {
|
||||
// keep error generic; specifics are logged server-side
|
||||
if (e?.name === 'CanceledError' || e?.message === 'canceled') return
|
||||
if (e?.response?.status === 403) {
|
||||
usersError.value = 'Access denied.'
|
||||
} else {
|
||||
usersError.value = 'Failed to load users.'
|
||||
}
|
||||
usersError.value = e?.response?.status === 403 ? 'Access denied.' : 'Failed to load users.'
|
||||
} finally {
|
||||
usersLoading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
// Helper to map ids -> usernames (for immediate UI update after dialog save)
|
||||
const idToName = computed(() => new Map(user_data.value.map(u => [String(u.id), u.username])))
|
||||
function usernamesFromIds(ids: string[]): string {
|
||||
return ids.map(id => idToName.value.get(String(id))).filter(Boolean).join(', ')
|
||||
}
|
||||
|
||||
// ---------- Devices (NEW) ----------
|
||||
// ---------------- Devices ----------------
|
||||
type ApiDeviceUser = { id: number; username: string; role: string }
|
||||
type ApiDevice = { guid: string; name: string; users?: ApiDeviceUser[] }
|
||||
type DevicesResponse = { devices: ApiDevice[]; offset: number; limit: number; total: number }
|
||||
@@ -69,29 +61,22 @@ function isDevicesResponse(d: unknown): d is DevicesResponse {
|
||||
const x = d as any
|
||||
return !!x && Array.isArray(x.devices) &&
|
||||
x.devices.every((dev: any) =>
|
||||
dev &&
|
||||
typeof dev.guid === 'string' &&
|
||||
typeof dev.name === 'string' &&
|
||||
(
|
||||
dev.users === undefined ||
|
||||
(
|
||||
Array.isArray(dev.users) &&
|
||||
dev.users.every((u: any) => u && typeof u.username === 'string')
|
||||
)
|
||||
)
|
||||
dev && typeof dev.guid === 'string' && typeof dev.name === 'string' &&
|
||||
(dev.users === undefined ||
|
||||
(Array.isArray(dev.users) && dev.users.every((u: any) => u && typeof u.username === 'string')))
|
||||
)
|
||||
}
|
||||
|
||||
const device_columns = [
|
||||
{ accessorKey: 'guid', header: 'GUID' },
|
||||
{ accessorKey: 'devicename', header: 'Device' },
|
||||
{ accessorKey: 'assigned_users', header: 'Users' },
|
||||
]
|
||||
|
||||
const device_data = ref<Device[]>([])
|
||||
const devicesLoading = ref(false)
|
||||
const devicesError = ref<string | null>(null)
|
||||
|
||||
const device_columns = [
|
||||
{ accessorKey: 'guid', header: 'GUID' },
|
||||
{ accessorKey: 'devicename', header: 'Device' },
|
||||
{ accessorKey: 'assigned_users', header: 'Users' },
|
||||
]
|
||||
|
||||
let devicesCtrl: AbortController | null = null
|
||||
async function loadDevices() {
|
||||
devicesError.value = null
|
||||
@@ -100,10 +85,7 @@ async function loadDevices() {
|
||||
devicesCtrl?.abort()
|
||||
devicesCtrl = new AbortController()
|
||||
const { data } = await api.get('/devices', { signal: devicesCtrl.signal })
|
||||
|
||||
if (!isDevicesResponse(data)) throw new Error('Unexpected devices response')
|
||||
|
||||
// Transform API -> table shape
|
||||
device_data.value = data.devices.map((d) => ({
|
||||
guid: d.guid,
|
||||
devicename: d.name,
|
||||
@@ -117,38 +99,131 @@ async function loadDevices() {
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------- Trackers ----------------
|
||||
type ApiTracker = { guid: string; name: string; users?: ApiDeviceUser[] }
|
||||
type TrackersResponse = { trackers: ApiTracker[]; offset: number; limit: number; total: number }
|
||||
|
||||
function isTrackersResponse(t: unknown): t is TrackersResponse {
|
||||
const x = t as any
|
||||
return !!x && Array.isArray(x.trackers) &&
|
||||
x.trackers.every((dev: any) =>
|
||||
dev && typeof dev.guid === 'string' && typeof dev.name === 'string' &&
|
||||
(dev.users === undefined ||
|
||||
(Array.isArray(dev.users) && dev.users.every((u: any) => u && typeof u.username === 'string')))
|
||||
)
|
||||
}
|
||||
|
||||
const tracker_columns = [
|
||||
{ accessorKey: 'guid', header: 'GUID' },
|
||||
{ accessorKey: 'devicename', header: 'Tracker' },
|
||||
{ accessorKey: 'assigned_users', header: 'Users' },
|
||||
]
|
||||
|
||||
const trackers_data = ref<Device[]>([])
|
||||
const trackersLoading = ref(false)
|
||||
const trackersError = ref<string | null>(null)
|
||||
|
||||
let treckerCtrl: AbortController | null = null
|
||||
async function loadTrackers() {
|
||||
trackersError.value = null
|
||||
trackersLoading.value = true
|
||||
try {
|
||||
treckerCtrl?.abort()
|
||||
treckerCtrl = new AbortController()
|
||||
const { data } = await api.get('/trackers', { signal: treckerCtrl.signal })
|
||||
if (!isTrackersResponse(data)) throw new Error('Unexpected trackers response')
|
||||
trackers_data.value = data.trackers.map((d) => ({
|
||||
guid: d.guid,
|
||||
devicename: d.name,
|
||||
assigned_users: Array.isArray(d.users) ? d.users.map(u => u.username).join(', ') : '',
|
||||
}))
|
||||
} catch (e: any) {
|
||||
if (e?.name === 'CanceledError' || e?.message === 'canceled') return
|
||||
trackersError.value = 'Failed to load trackers.'
|
||||
} finally {
|
||||
trackersLoading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------- Immediate UI updates from dropdown dialogs ----------------
|
||||
function handleDeviceUpdated(row: Device, payload: { name: string; userIds: string[] }) {
|
||||
const guid = row.guid
|
||||
const usersStr = usernamesFromIds(payload.userIds)
|
||||
device_data.value = device_data.value.map(d =>
|
||||
d.guid === guid ? { ...d, devicename: payload.name, assigned_users: usersStr } : d
|
||||
)
|
||||
}
|
||||
function handleDeviceDeleted(row: Device) {
|
||||
const guid = row.guid
|
||||
device_data.value = device_data.value.filter(d => d.guid !== guid)
|
||||
}
|
||||
|
||||
// If trackers use the same dropdown to edit, keep these too:
|
||||
function handleTrackerUpdated(row: Device, payload: { name: string; userIds: string[] }) {
|
||||
const guid = row.guid
|
||||
const usersStr = usernamesFromIds(payload.userIds)
|
||||
trackers_data.value = trackers_data.value.map(d =>
|
||||
d.guid === guid ? { ...d, devicename: payload.name, assigned_users: usersStr } : d
|
||||
)
|
||||
}
|
||||
function handleTrackerDeleted(row: Device) {
|
||||
const guid = row.guid
|
||||
trackers_data.value = trackers_data.value.filter(d => d.guid !== guid)
|
||||
}
|
||||
|
||||
// ---------------- lifecycle ----------------
|
||||
onMounted(() => {
|
||||
loadUsers()
|
||||
loadDevices()
|
||||
loadTrackers()
|
||||
})
|
||||
onBeforeUnmount(() => {
|
||||
ctrl?.abort()
|
||||
devicesCtrl?.abort()
|
||||
ctrl?.abort()
|
||||
devicesCtrl?.abort()
|
||||
treckerCtrl?.abort()
|
||||
})
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<a href="/create">
|
||||
<Button>
|
||||
Create
|
||||
</Button>
|
||||
</a>
|
||||
<a href="/create">
|
||||
<Button>Create</Button>
|
||||
</a>
|
||||
|
||||
<Tabs default-value="users">
|
||||
<TabsList class="space-x-8">
|
||||
<TabsTrigger value="users">
|
||||
Users
|
||||
</TabsTrigger>
|
||||
<TabsTrigger value="devices">
|
||||
Devices
|
||||
</TabsTrigger>
|
||||
</TabsList>
|
||||
<TabsContent value="users">
|
||||
<DataTableNoCheckbox :columns="user_columns" :data="user_data" :dropdownComponent="AdminUserDropdonw" />
|
||||
</TabsContent>
|
||||
<TabsContent value="devices">
|
||||
<DataTableNoCheckbox :columns="device_columns" :data="device_data"
|
||||
:dropdownComponent="AdminDeviceDropdown" />
|
||||
</TabsContent>
|
||||
</Tabs>
|
||||
<Tabs default-value="users">
|
||||
<TabsList class="space-x-8">
|
||||
<TabsTrigger value="users">Users</TabsTrigger>
|
||||
<TabsTrigger value="devices">Devices</TabsTrigger>
|
||||
<TabsTrigger value="trackers">Trackers</TabsTrigger>
|
||||
</TabsList>
|
||||
|
||||
<TabsContent value="users">
|
||||
<DataTableNoCheckbox
|
||||
:columns="user_columns"
|
||||
:data="user_data"
|
||||
:dropdownComponent="AdminUserDropdonw"
|
||||
/>
|
||||
</TabsContent>
|
||||
|
||||
<TabsContent value="devices">
|
||||
<DataTableNoCheckbox
|
||||
:columns="device_columns"
|
||||
:data="device_data"
|
||||
:dropdownComponent="AdminDeviceDropdown"
|
||||
@row-updated="handleDeviceUpdated"
|
||||
@row-deleted="handleDeviceDeleted"
|
||||
:dropdownProps="{ allUsers: user_data }"
|
||||
/>
|
||||
</TabsContent>
|
||||
|
||||
<TabsContent value="trackers">
|
||||
<DataTableNoCheckbox
|
||||
:columns="tracker_columns"
|
||||
:data="trackers_data"
|
||||
:dropdownComponent="AdminTrackerDropdown"
|
||||
@row-updated="handleTrackerUpdated"
|
||||
@row-deleted="handleTrackerDeleted"
|
||||
:dropdownProps="{ allUsers: user_data }"
|
||||
/>
|
||||
</TabsContent>
|
||||
</Tabs>
|
||||
</template>
|
||||
@@ -1,6 +1,6 @@
|
||||
<script setup lang="ts">
|
||||
import { useFilter } from 'reka-ui'
|
||||
import { computed, ref, onMounted, onBeforeUnmount } from 'vue'
|
||||
import { computed, ref, onMounted, onBeforeUnmount, watch } from 'vue'
|
||||
import {
|
||||
Combobox, ComboboxAnchor, ComboboxEmpty, ComboboxGroup,
|
||||
ComboboxInput, ComboboxItem, ComboboxList
|
||||
@@ -11,63 +11,52 @@ import {
|
||||
import type { Users } from '@/lib/interfaces'
|
||||
import { api } from '@/lib/api'
|
||||
|
||||
// ——— v-model plumbing ———
|
||||
const props = defineProps<{
|
||||
modelValue: string[] // selected user IDs (strings)
|
||||
}>()
|
||||
const emit = defineEmits<{
|
||||
(e: 'update:modelValue', v: string[]): void
|
||||
modelValue: string[] // selected user IDs
|
||||
allUsers?: Users[] // OPTIONAL: full users list provided by parent
|
||||
}>()
|
||||
const emit = defineEmits<{ (e:'update:modelValue', v:string[]):void }>()
|
||||
|
||||
// computed proxy to v-model
|
||||
// computed proxy
|
||||
const selected = computed<string[]>({
|
||||
get: () => props.modelValue ?? [],
|
||||
set: (v) => emit('update:modelValue', v),
|
||||
})
|
||||
|
||||
// ——— local state ———
|
||||
const open = ref(false)
|
||||
const searchTerm = ref('')
|
||||
const loading = ref(false)
|
||||
const error = ref<string | null>(null)
|
||||
|
||||
const allUsers = ref<Users[]>([])
|
||||
/** SOURCE of truth for users used by the combobox */
|
||||
const internalUsers = ref<Users[]>([]) // used only when parent didn't pass allUsers
|
||||
const usingExternal = computed(() => Array.isArray(props.allUsers))
|
||||
const effectiveUsers = computed<Users[]>(() => usingExternal.value ? (props.allUsers as Users[]) : internalUsers.value)
|
||||
|
||||
// self-fetch only when parent didn't provide allUsers
|
||||
let ctrl: AbortController | null = null
|
||||
|
||||
async function loadUsers() {
|
||||
error.value = null
|
||||
loading.value = true
|
||||
if (usingExternal.value) return
|
||||
try {
|
||||
ctrl?.abort()
|
||||
ctrl = new AbortController()
|
||||
const { data } = await api.get<Users[]>('/users', { signal: ctrl.signal })
|
||||
if (!Array.isArray(data)) throw new Error('Unexpected response')
|
||||
allUsers.value = data.filter(
|
||||
(u: any) => typeof u?.id === 'number' && typeof u?.username === 'string'
|
||||
)
|
||||
} catch (e: any) {
|
||||
if (e?.name === 'CanceledError' || e?.message === 'canceled') return
|
||||
error.value = 'Failed to load users.'
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
if (Array.isArray(data)) {
|
||||
internalUsers.value = data.filter((u:any) => typeof u?.id === 'number' && typeof u?.username === 'string')
|
||||
}
|
||||
} catch { /* ignore */ }
|
||||
}
|
||||
|
||||
onMounted(loadUsers)
|
||||
onBeforeUnmount(() => ctrl?.abort())
|
||||
|
||||
type UserOption = { value: string; label: string }
|
||||
const users = computed<UserOption[]>(() =>
|
||||
allUsers.value.map(u => ({ value: String(u.id), label: u.username }))
|
||||
effectiveUsers.value.map(u => ({ value: String(u.id), label: u.username }))
|
||||
)
|
||||
|
||||
const { contains } = useFilter({ sensitivity: 'base' })
|
||||
const filteredUsers = computed(() => {
|
||||
const selectedSet = new Set(selected.value)
|
||||
const options = users.value.filter(o => !selectedSet.has(o.value))
|
||||
return searchTerm.value
|
||||
? options.filter(o => contains(o.label, searchTerm.value))
|
||||
: options
|
||||
return searchTerm.value ? options.filter(o => contains(o.label, searchTerm.value)) : options
|
||||
})
|
||||
|
||||
function userLabelById(id: string) {
|
||||
@@ -77,21 +66,30 @@ function userLabelById(id: string) {
|
||||
function onSelect(ev: CustomEvent) {
|
||||
const val = String((ev as any).detail?.value ?? '')
|
||||
if (!val) return
|
||||
if (!selected.value.includes(val)) {
|
||||
// assign a new array so v-model updates properly
|
||||
selected.value = [...selected.value, val]
|
||||
}
|
||||
if (!selected.value.includes(val)) selected.value = [...selected.value, val]
|
||||
searchTerm.value = ''
|
||||
if (filteredUsers.value.length === 0) {
|
||||
open.value = false
|
||||
}
|
||||
if (filteredUsers.value.length === 0) open.value = false
|
||||
}
|
||||
|
||||
// When parent switches between external/internal data at runtime, refetch if needed.
|
||||
watch(() => props.allUsers, () => { if (!usingExternal.value) loadUsers() })
|
||||
|
||||
// Debug: whenever modelValue changes (from dialog)
|
||||
watch(() => props.modelValue, (v) => {
|
||||
console.log('[AssignDevice:props.modelValue]', v)
|
||||
}, { immediate: true })
|
||||
|
||||
// Debug: when effective users list is ready
|
||||
watch(() => effectiveUsers.value, (v) => {
|
||||
console.log('[AssignDevice:effectiveUsers]', v?.length, 'items')
|
||||
})
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<Combobox v-model="selected" v-model:open="open" :ignore-filter="true">
|
||||
<ComboboxAnchor as-child>
|
||||
<TagsInput v-model="selected" class="px-2 gap-2 w-90">
|
||||
<div class="relative w-full">
|
||||
<TagsInput v-model="selected" class="w-full px-2 gap-2">
|
||||
<div class="flex gap-2 flex-wrap items-center">
|
||||
<TagsInputItem v-for="id in selected" :key="id" :value="id">
|
||||
<span class="px-1">{{ userLabelById(id) }}</span>
|
||||
@@ -99,26 +97,22 @@ function onSelect(ev: CustomEvent) {
|
||||
</TagsInputItem>
|
||||
</div>
|
||||
|
||||
<ComboboxInput v-model="searchTerm" as-child>
|
||||
<TagsInputInput
|
||||
placeholder="User..."
|
||||
class="min-w-[300px] w-full p-0 border-none focus-visible:ring-0 h-auto"
|
||||
@keydown.enter.prevent
|
||||
/>
|
||||
</ComboboxInput>
|
||||
<ComboboxInput v-model="searchTerm" as-child>
|
||||
<TagsInputInput
|
||||
placeholder="User..."
|
||||
class="min-w-[200px] w-full p-0 border-none focus-visible:ring-0 h-auto"
|
||||
@keydown.enter.prevent
|
||||
/>
|
||||
</ComboboxInput>
|
||||
</TagsInput>
|
||||
|
||||
<!-- match input width -->
|
||||
<ComboboxList
|
||||
class="w-[--reka-popper-anchor-width] min-w-[350px]"
|
||||
>
|
||||
<ComboboxList class="w-[--reka-popper-anchor-width] w-full min-w-[350px]">
|
||||
<ComboboxEmpty>
|
||||
<span v-if="loading">Loading…</span>
|
||||
<span v-else-if="error">{{ error }}</span>
|
||||
<span v-else>No users found.</span>
|
||||
<span v-if="!usingExternal && !effectiveUsers.length">Loading…</span>
|
||||
<span v-else-if="!users.length">No users found.</span>
|
||||
</ComboboxEmpty>
|
||||
|
||||
<ComboboxGroup v-if="!loading && !error && filteredUsers.length">
|
||||
<ComboboxGroup v-if="filteredUsers.length">
|
||||
<ComboboxItem
|
||||
v-for="usr in filteredUsers"
|
||||
:key="usr.value"
|
||||
@@ -129,6 +123,7 @@ function onSelect(ev: CustomEvent) {
|
||||
</ComboboxItem>
|
||||
</ComboboxGroup>
|
||||
</ComboboxList>
|
||||
</div>
|
||||
</ComboboxAnchor>
|
||||
</Combobox>
|
||||
</template>
|
||||
|
||||
@@ -34,6 +34,13 @@ const props = defineProps<{
|
||||
* />
|
||||
*/
|
||||
dropdownComponent?: DefineComponent<{ row: TData }, any, any>
|
||||
// dropdownComponent?: DefineComponent<{ row: TData } & {
|
||||
// onRowUpdated?: (row: TData, payload: any) => void
|
||||
// onRowDeleted?: (row: TData) => void
|
||||
// }, any, any>
|
||||
// onRowUpdated?: (row: TData, payload: any) => void // <-- NEW
|
||||
// onRowDeleted?: (row: TData) => void // <-- NEW
|
||||
dropdownProps?: Record<string, any> // <-- NEW
|
||||
}>()
|
||||
|
||||
// ——— Table setup ———
|
||||
@@ -42,6 +49,11 @@ const table = useVueTable({
|
||||
get columns() { return props.columns },
|
||||
getCoreRowModel: getCoreRowModel(),
|
||||
})
|
||||
|
||||
const emit = defineEmits<{
|
||||
(e: 'row-updated', row: TData, payload: any): void
|
||||
(e: 'row-deleted', row: TData): void
|
||||
}>()
|
||||
</script>
|
||||
|
||||
<template>
|
||||
@@ -93,9 +105,19 @@ const table = useVueTable({
|
||||
|
||||
<!-- dropdown cell -->
|
||||
<TableCell v-if="props.dropdownComponent" class="text-right">
|
||||
<component
|
||||
<!-- <component
|
||||
:is="props.dropdownComponent"
|
||||
:row="row.original"
|
||||
:key="row.id"
|
||||
:on-row-updated="props.onRowUpdated"
|
||||
:on-row-deleted="props.onRowDeleted"
|
||||
/> -->
|
||||
<component
|
||||
:is="props.dropdownComponent"
|
||||
:row="row.original"
|
||||
v-bind="props.dropdownProps"
|
||||
@updated="(payload: any) => emit('row-updated', row.original, payload)"
|
||||
@deleted="() => emit('row-deleted', row.original)"
|
||||
/>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
|
||||
@@ -26,7 +26,7 @@ const emit = defineEmits<{
|
||||
<template>
|
||||
<AlertDialog
|
||||
:open="props.modelValue"
|
||||
@openChange="(v: boolean) => emit('update:modelValue', v)"
|
||||
@update:open="(v: boolean) => emit('update:modelValue', v)"
|
||||
>
|
||||
<AlertDialogContent>
|
||||
<AlertDialogHeader>
|
||||
|
||||
@@ -24,7 +24,7 @@ const emit = defineEmits<{
|
||||
<template>
|
||||
<AlertDialog
|
||||
:open="props.modelValue"
|
||||
@openChange="(v: boolean) => emit('update:modelValue', v)"
|
||||
@update:open="(v: boolean) => emit('update:modelValue', v)"
|
||||
>
|
||||
<AlertDialogContent>
|
||||
<AlertDialogHeader>
|
||||
|
||||
@@ -0,0 +1,49 @@
|
||||
<script setup lang="ts">
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
} from '@/components/ui/dialog'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import type { Device } from '@/lib/interfaces';
|
||||
import type { PropType } from 'vue';
|
||||
|
||||
|
||||
const props = defineProps({
|
||||
modelValue: {
|
||||
type: Boolean as PropType<boolean>,
|
||||
required: true,
|
||||
},
|
||||
device: { type: Object as PropType<Device>, required: false },
|
||||
})
|
||||
|
||||
const emit = defineEmits<{
|
||||
(e: 'update:modelValue', v: boolean): void
|
||||
(e: 'confirm'): void
|
||||
}>()
|
||||
|
||||
function onSave() {
|
||||
emit('confirm')
|
||||
// close the dialog
|
||||
emit('update:modelValue', false)
|
||||
}
|
||||
</script>
|
||||
<template>
|
||||
<Dialog :open="props.modelValue" @update:open="(v: boolean) => emit('update:modelValue', v)">
|
||||
<DialogContent class="sm:min-w-[800px]">
|
||||
<DialogHeader>
|
||||
<DialogTitle>List of certificates</DialogTitle>
|
||||
<DialogDescription>
|
||||
{{ props.device?.guid }}
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
<DialogFooter>
|
||||
<Button @click="onSave">Close</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</template>
|
||||
@@ -32,7 +32,7 @@ const usrIDs = selectedUserIds.value
|
||||
Dashboard
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent class="flex-1 space-y-6">
|
||||
<CardContent class="flex-1 grid gap-4 py-4">
|
||||
<div class="grid gap-5">
|
||||
<div class="grid space-y-2 grid-cols-4 items-center">
|
||||
<Label for="users">Allowed users</Label>
|
||||
|
||||
48
management-ui/src/customcompometns/DeviceTasksDialog.vue
Normal file
48
management-ui/src/customcompometns/DeviceTasksDialog.vue
Normal file
@@ -0,0 +1,48 @@
|
||||
<script setup lang="ts">
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
} from '@/components/ui/dialog'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import type { Device } from '@/lib/interfaces';
|
||||
import type { PropType } from 'vue';
|
||||
|
||||
const props = defineProps({
|
||||
modelValue: {
|
||||
type: Boolean as PropType<boolean>,
|
||||
required: true,
|
||||
},
|
||||
device: { type: Object as PropType<Device>, required: false },
|
||||
})
|
||||
const emit = defineEmits<{
|
||||
(e: 'update:modelValue', v: boolean): void
|
||||
(e: 'confirm'): void
|
||||
}>()
|
||||
|
||||
function onSave() {
|
||||
emit('confirm')
|
||||
// close the dialog
|
||||
emit('update:modelValue', false)
|
||||
}
|
||||
</script>
|
||||
<template>
|
||||
<Dialog :open="props.modelValue" @update:open="(v: boolean) => emit('update:modelValue', v)">
|
||||
<DialogContent class="sm:min-w-[800px]">
|
||||
<DialogHeader>
|
||||
<DialogTitle>Tasks</DialogTitle>
|
||||
<DialogDescription>
|
||||
{{ props.device?.guid }}
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
|
||||
<DialogFooter>
|
||||
<Button @click="onSave">Close</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</template>
|
||||
@@ -1,70 +1,218 @@
|
||||
<script setup lang="ts">
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription, DialogFooter,
|
||||
} from '@/components/ui/dialog'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { Label } from '@/components/ui/label'
|
||||
import { defineProps, defineEmits } from 'vue'
|
||||
import type { PropType } from 'vue'
|
||||
import AssignDevice from './AssignDevice.vue'
|
||||
import type { Device, Users } from '@/lib/interfaces'
|
||||
import { defineProps, defineEmits, ref, watch, computed } from 'vue'
|
||||
import type { PropType } from 'vue'
|
||||
import { api } from '@/lib/api'
|
||||
|
||||
type DeviceWithUsers =
|
||||
& Partial<Device>
|
||||
& { guid?: string; name?: string; devicename?: string; assigned_users?: string }
|
||||
& { users?: Array<{ id: number; username: string; role?: string }> }
|
||||
|
||||
// 1) runtime props so Vue + TS agree
|
||||
const props = defineProps({
|
||||
modelValue: {
|
||||
type: Boolean as PropType<boolean>,
|
||||
required: true,
|
||||
},
|
||||
modelValue: { type: Boolean as PropType<boolean>, required: true },
|
||||
device: { type: Object as PropType<DeviceWithUsers>, required: true },
|
||||
allUsers: { type: Array as PropType<Users[]>, required: false },
|
||||
})
|
||||
|
||||
// 2) two emits: v-model and confirm
|
||||
const emit = defineEmits<{
|
||||
(e: 'update:modelValue', v: boolean): void
|
||||
(e: 'confirm'): void
|
||||
(e: 'updated', payload: { name: string; userIds: string[] }): void
|
||||
}>()
|
||||
|
||||
function onSave() {
|
||||
emit('confirm')
|
||||
// close the dialog
|
||||
emit('update:modelValue', false)
|
||||
const guid = computed(() => String(props.device?.guid ?? ''))
|
||||
const originalName = computed(() => (props.device?.devicename ?? props.device?.name ?? ''))
|
||||
|
||||
const originalIds = ref<string[]>([]) // baseline for compare
|
||||
const name = ref('')
|
||||
const selectedUserIds = ref<string[]>([]) // live edited selection
|
||||
|
||||
// ----- init control: only init once per open/guid -----
|
||||
const initedForGuid = ref<string | null>(null)
|
||||
|
||||
function usernameToId(u: string): string | null {
|
||||
const id = props.allUsers?.find(x => x.username === u)?.id
|
||||
return typeof id === 'number' ? String(id) : null
|
||||
}
|
||||
|
||||
function initFromDevice() {
|
||||
const dev = props.device
|
||||
name.value = originalName.value
|
||||
|
||||
if (Array.isArray(dev?.users) && dev!.users.length) {
|
||||
originalIds.value = dev!.users.map(u => String(u.id))
|
||||
} else {
|
||||
// Map from assigned_users (comma-separated usernames) -> ids (requires allUsers)
|
||||
const usernames = (dev?.assigned_users ?? '')
|
||||
.split(',')
|
||||
.map(s => s.trim())
|
||||
.filter(Boolean)
|
||||
|
||||
if (usernames.length && props.allUsers?.length) {
|
||||
originalIds.value = usernames
|
||||
.map(usernameToId)
|
||||
.filter((x): x is string => !!x)
|
||||
} else {
|
||||
originalIds.value = []
|
||||
}
|
||||
}
|
||||
|
||||
selectedUserIds.value = [...originalIds.value]
|
||||
initedForGuid.value = guid.value
|
||||
|
||||
}
|
||||
|
||||
// When dialog opens, initialize once for this guid
|
||||
watch(
|
||||
() => props.modelValue,
|
||||
(open) => {
|
||||
if (open && guid.value && initedForGuid.value !== guid.value) {
|
||||
initFromDevice()
|
||||
}
|
||||
if (!open) {
|
||||
// reset flag so next open re-inits
|
||||
initedForGuid.value = null
|
||||
}
|
||||
},
|
||||
{ immediate: true }
|
||||
)
|
||||
|
||||
|
||||
// If allUsers arrives later, and we couldn't map on first init, map now.
|
||||
watch(
|
||||
() => props.allUsers,
|
||||
() => {
|
||||
if (!props.modelValue || !guid.value) return
|
||||
|
||||
const dev = props.device
|
||||
const hasUsersArray = Array.isArray(dev?.users) && dev!.users.length > 0
|
||||
const hasAssigned = typeof dev?.assigned_users === 'string' && dev!.assigned_users.trim().length > 0
|
||||
const canMapNow = Array.isArray(props.allUsers) && props.allUsers.length > 0
|
||||
|
||||
// Only re-map if we *didn't* have users[], we *do* have assigned usernames,
|
||||
// we *couldn't* map earlier (originalIds is empty), and now we have allUsers.
|
||||
if (!hasUsersArray && hasAssigned && originalIds.value.length === 0 && canMapNow) {
|
||||
const usernames = dev!.assigned_users!
|
||||
.split(',')
|
||||
.map(s => s.trim())
|
||||
.filter(Boolean)
|
||||
|
||||
const mapped = usernames
|
||||
.map(u => {
|
||||
const id = props.allUsers!.find(x => x.username === u)?.id
|
||||
return typeof id === 'number' ? String(id) : null
|
||||
})
|
||||
.filter((x): x is string => !!x)
|
||||
|
||||
if (mapped.length > 0) {
|
||||
originalIds.value = mapped
|
||||
selectedUserIds.value = [...mapped]
|
||||
}
|
||||
}
|
||||
},
|
||||
{ immediate: false }
|
||||
)
|
||||
|
||||
|
||||
// ---------- Save ----------
|
||||
const saving = ref(false)
|
||||
const errorText = ref<string | null>(null)
|
||||
|
||||
function changedName() {
|
||||
return name.value.trim() !== originalName.value.trim()
|
||||
}
|
||||
function changedUsers() {
|
||||
const a = new Set(originalIds.value)
|
||||
const b = new Set(selectedUserIds.value)
|
||||
if (a.size !== b.size) return true
|
||||
for (const id of a) if (!b.has(id)) return true
|
||||
return false
|
||||
}
|
||||
|
||||
async function onSave() {
|
||||
if (!guid.value) return
|
||||
errorText.value = null
|
||||
saving.value = true
|
||||
try {
|
||||
const ops: Promise<any>[] = []
|
||||
|
||||
const nameChanged = changedName()
|
||||
const usersChanged = changedUsers()
|
||||
console.log('[EditDeviceDialog:onSave]', { nameChanged, usersChanged, name: name.value })
|
||||
|
||||
if (nameChanged) {
|
||||
ops.push(api.post(`/devices/${encodeURIComponent(guid.value)}/rename`, {
|
||||
name: name.value.trim(),
|
||||
} as { name: string }))
|
||||
}
|
||||
|
||||
if (usersChanged) {
|
||||
const userIdsNum = selectedUserIds.value
|
||||
.map(v => Number(v))
|
||||
.filter(n => Number.isFinite(n)) as number[]
|
||||
|
||||
ops.push(api.post(`/devices/${encodeURIComponent(guid.value)}/set_users`, {
|
||||
userIds: userIdsNum,
|
||||
} as { userIds: number[] }))
|
||||
}
|
||||
|
||||
if (ops.length > 0) {
|
||||
await Promise.all(ops)
|
||||
}
|
||||
|
||||
emit('updated', { name: name.value, userIds: [...selectedUserIds.value] })
|
||||
emit('update:modelValue', false)
|
||||
} catch (err: any) {
|
||||
errorText.value = err?.response?.data?.message || 'Failed to save changes.'
|
||||
} finally {
|
||||
saving.value = false
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<Dialog
|
||||
:open="props.modelValue"
|
||||
@openChange="(v: boolean) => emit('update:modelValue', v)"
|
||||
>
|
||||
<DialogContent class="sm:max-w-[425px]">
|
||||
<Dialog :open="props.modelValue" @update:open="(v:boolean)=>emit('update:modelValue', v)">
|
||||
<DialogContent class="sm:min-w-[500px]">
|
||||
<DialogHeader>
|
||||
<DialogTitle>Edit device</DialogTitle>
|
||||
<DialogDescription>
|
||||
Make changes to device settings below.
|
||||
</DialogDescription>
|
||||
<DialogDescription>Make changes to device settings below.</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
<div class="grid gap-4 py-4">
|
||||
<div class="grid grid-cols-4 items-center gap-4">
|
||||
<Label for="guid" class="text-right">GUID</Label>
|
||||
<Input id="guid" class="col-span-3" />
|
||||
<p id="guid" class="col-span-3 break-all text-muted-foreground">{{ guid }}</p>
|
||||
</div>
|
||||
|
||||
<div class="grid grid-cols-4 items-center gap-4">
|
||||
<Label for="name" class="text-right">Name</Label>
|
||||
<Input id="name" class="col-span-3" />
|
||||
<Input id="name" class="col-span-3" v-model="name" :disabled="saving" placeholder="Device name" />
|
||||
</div>
|
||||
|
||||
<div class="grid grid-cols-4 items-center gap-4">
|
||||
<Label for="users" class="text-right">Allowed users</Label>
|
||||
<AssignDevice id="users"/>
|
||||
<AssignDevice
|
||||
id="users"
|
||||
class="col-span-3 w-full"
|
||||
v-model="selectedUserIds"
|
||||
:all-users="props.allUsers"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<p v-if="errorText" class="text-sm text-red-600 mt-1 col-span-4">{{ errorText }}</p>
|
||||
</div>
|
||||
|
||||
<DialogFooter>
|
||||
<Button @click="onSave">Save changes</Button>
|
||||
<Button :disabled="saving" @click="onSave">
|
||||
{{ saving ? 'Saving…' : 'Save changes' }}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
|
||||
216
management-ui/src/customcompometns/EditTrackerDialog.vue
Normal file
216
management-ui/src/customcompometns/EditTrackerDialog.vue
Normal file
@@ -0,0 +1,216 @@
|
||||
<script setup lang="ts">
|
||||
import {
|
||||
Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription, DialogFooter,
|
||||
} from '@/components/ui/dialog'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { Label } from '@/components/ui/label'
|
||||
import AssignDevice from './AssignDevice.vue'
|
||||
import type { Device, Users } from '@/lib/interfaces'
|
||||
import { defineProps, defineEmits, ref, watch, computed } from 'vue'
|
||||
import type { PropType } from 'vue'
|
||||
import { api } from '@/lib/api'
|
||||
|
||||
type DeviceWithUsers =
|
||||
& Partial<Device>
|
||||
& { guid?: string; name?: string; devicename?: string; assigned_users?: string }
|
||||
& { users?: Array<{ id: number; username: string; role?: string }> }
|
||||
|
||||
const props = defineProps({
|
||||
modelValue: { type: Boolean as PropType<boolean>, required: true },
|
||||
device: { type: Object as PropType<DeviceWithUsers>, required: true },
|
||||
allUsers: { type: Array as PropType<Users[]>, required: false },
|
||||
})
|
||||
|
||||
const emit = defineEmits<{
|
||||
(e: 'update:modelValue', v: boolean): void
|
||||
(e: 'updated', payload: { name: string; userIds: string[] }): void
|
||||
}>()
|
||||
|
||||
const guid = computed(() => String(props.device?.guid ?? ''))
|
||||
const originalName = computed(() => (props.device?.devicename ?? props.device?.name ?? ''))
|
||||
|
||||
const originalIds = ref<string[]>([]) // baseline for compare
|
||||
const name = ref('')
|
||||
const selectedUserIds = ref<string[]>([]) // live edited selection
|
||||
|
||||
// ----- init control: only init once per open/guid -----
|
||||
const initedForGuid = ref<string | null>(null)
|
||||
|
||||
function usernameToId(u: string): string | null {
|
||||
const id = props.allUsers?.find(x => x.username === u)?.id
|
||||
return typeof id === 'number' ? String(id) : null
|
||||
}
|
||||
|
||||
function initFromDevice() {
|
||||
const dev = props.device
|
||||
name.value = originalName.value
|
||||
|
||||
if (Array.isArray(dev?.users) && dev!.users.length) {
|
||||
originalIds.value = dev!.users.map(u => String(u.id))
|
||||
} else {
|
||||
// Map from assigned_users (comma-separated usernames) -> ids (requires allUsers)
|
||||
const usernames = (dev?.assigned_users ?? '')
|
||||
.split(',')
|
||||
.map(s => s.trim())
|
||||
.filter(Boolean)
|
||||
|
||||
if (usernames.length && props.allUsers?.length) {
|
||||
originalIds.value = usernames
|
||||
.map(usernameToId)
|
||||
.filter((x): x is string => !!x)
|
||||
} else {
|
||||
originalIds.value = []
|
||||
}
|
||||
}
|
||||
|
||||
selectedUserIds.value = [...originalIds.value]
|
||||
initedForGuid.value = guid.value
|
||||
}
|
||||
|
||||
// When dialog opens, initialize once for this guid
|
||||
watch(
|
||||
() => props.modelValue,
|
||||
(open) => {
|
||||
if (open && guid.value && initedForGuid.value !== guid.value) {
|
||||
initFromDevice()
|
||||
}
|
||||
if (!open) {
|
||||
// reset flag so next open re-inits
|
||||
initedForGuid.value = null
|
||||
}
|
||||
},
|
||||
{ immediate: true }
|
||||
)
|
||||
|
||||
|
||||
// If allUsers arrives later, and we couldn't map on first init, map now.
|
||||
watch(
|
||||
() => props.allUsers,
|
||||
() => {
|
||||
if (!props.modelValue || !guid.value) return
|
||||
|
||||
const dev = props.device
|
||||
const hasUsersArray = Array.isArray(dev?.users) && dev!.users.length > 0
|
||||
const hasAssigned = typeof dev?.assigned_users === 'string' && dev!.assigned_users.trim().length > 0
|
||||
const canMapNow = Array.isArray(props.allUsers) && props.allUsers.length > 0
|
||||
|
||||
// Only re-map if we *didn't* have users[], we *do* have assigned usernames,
|
||||
// we *couldn't* map earlier (originalIds is empty), and now we have allUsers.
|
||||
if (!hasUsersArray && hasAssigned && originalIds.value.length === 0 && canMapNow) {
|
||||
const usernames = dev!.assigned_users!
|
||||
.split(',')
|
||||
.map(s => s.trim())
|
||||
.filter(Boolean)
|
||||
|
||||
const mapped = usernames
|
||||
.map(u => {
|
||||
const id = props.allUsers!.find(x => x.username === u)?.id
|
||||
return typeof id === 'number' ? String(id) : null
|
||||
})
|
||||
.filter((x): x is string => !!x)
|
||||
|
||||
if (mapped.length > 0) {
|
||||
originalIds.value = mapped
|
||||
selectedUserIds.value = [...mapped]
|
||||
}
|
||||
}
|
||||
},
|
||||
{ immediate: false }
|
||||
)
|
||||
|
||||
// ---------- Save ----------
|
||||
const saving = ref(false)
|
||||
const errorText = ref<string | null>(null)
|
||||
|
||||
function changedName() {
|
||||
return name.value.trim() !== originalName.value.trim()
|
||||
}
|
||||
function changedUsers() {
|
||||
const a = new Set(originalIds.value)
|
||||
const b = new Set(selectedUserIds.value)
|
||||
if (a.size !== b.size) return true
|
||||
for (const id of a) if (!b.has(id)) return true
|
||||
return false
|
||||
}
|
||||
|
||||
async function onSave() {
|
||||
if (!guid.value) return
|
||||
errorText.value = null
|
||||
saving.value = true
|
||||
try {
|
||||
const ops: Promise<any>[] = []
|
||||
|
||||
const nameChanged = changedName()
|
||||
const usersChanged = changedUsers()
|
||||
|
||||
if (nameChanged) {
|
||||
ops.push(api.post(`/trackers/${encodeURIComponent(guid.value)}/rename`, {
|
||||
name: name.value.trim(),
|
||||
} as { name: string }))
|
||||
}
|
||||
|
||||
if (usersChanged) {
|
||||
const userIdsNum = selectedUserIds.value
|
||||
.map(v => Number(v))
|
||||
.filter(n => Number.isFinite(n)) as number[]
|
||||
|
||||
ops.push(api.post(`/trackers/${encodeURIComponent(guid.value)}/set_users`, {
|
||||
userIds: userIdsNum,
|
||||
} as { userIds: number[] }))
|
||||
}
|
||||
|
||||
if (ops.length > 0) {
|
||||
await Promise.all(ops)
|
||||
}
|
||||
|
||||
emit('updated', { name: name.value, userIds: [...selectedUserIds.value] })
|
||||
emit('update:modelValue', false)
|
||||
} catch (err: any) {
|
||||
errorText.value = err?.response?.data?.message || 'Failed to save changes.'
|
||||
} finally {
|
||||
saving.value = false
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<Dialog :open="props.modelValue" @update:open="(v:boolean)=>emit('update:modelValue', v)">
|
||||
<DialogContent class="sm:min-w-[500px]">
|
||||
<DialogHeader>
|
||||
<DialogTitle>Edit tracker</DialogTitle>
|
||||
<DialogDescription>Make changes to tracker settings below.</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
<div class="grid gap-4 py-4">
|
||||
<div class="grid grid-cols-4 items-center gap-4">
|
||||
<Label for="guid" class="text-right">GUID</Label>
|
||||
<p id="guid" class="col-span-3 break-all text-muted-foreground">{{ guid }}</p>
|
||||
</div>
|
||||
|
||||
<div class="grid grid-cols-4 items-center gap-4">
|
||||
<Label for="name" class="text-right">Name</Label>
|
||||
<Input id="name" class="col-span-3" v-model="name" :disabled="saving" placeholder="Tracker name" />
|
||||
</div>
|
||||
|
||||
<div class="grid grid-cols-4 items-center gap-4">
|
||||
<Label for="users" class="text-right">Allowed users</Label>
|
||||
<AssignDevice
|
||||
id="users"
|
||||
class="col-span-3 w-full"
|
||||
v-model="selectedUserIds"
|
||||
:all-users="props.allUsers"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<p v-if="errorText" class="text-sm text-red-600 mt-1 col-span-4">{{ errorText }}</p>
|
||||
</div>
|
||||
|
||||
<DialogFooter>
|
||||
<Button :disabled="saving" @click="onSave">
|
||||
{{ saving ? 'Saving…' : 'Save changes' }}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</template>
|
||||
@@ -38,7 +38,7 @@ function onSave() {
|
||||
<template>
|
||||
<Dialog
|
||||
:open="props.modelValue"
|
||||
@openChange="(v: boolean) => emit('update:modelValue', v)"
|
||||
@update:open="(v: boolean) => emit('update:modelValue', v)"
|
||||
>
|
||||
<DialogContent class="sm:max-w-[425px]">
|
||||
<DialogHeader>
|
||||
|
||||
@@ -44,6 +44,13 @@ function navLinkClass(prefix: string) {
|
||||
>
|
||||
Devices
|
||||
</RouterLink>
|
||||
<RouterLink
|
||||
to="/trackers"
|
||||
:class="navLinkClass('/trackers')"
|
||||
:aria-current="isActive('/trackers') ? 'page' : undefined"
|
||||
>
|
||||
Trackers
|
||||
</RouterLink>
|
||||
</nav>
|
||||
|
||||
<DropdownMenu>
|
||||
|
||||
58
management-ui/src/customcompometns/TrackerComponent.vue
Normal file
58
management-ui/src/customcompometns/TrackerComponent.vue
Normal file
@@ -0,0 +1,58 @@
|
||||
<script setup lang="ts">
|
||||
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import TrackerDashboard from './TrackerDashboard.vue';
|
||||
import { nextTick, onMounted, ref, type PropType } from 'vue';
|
||||
import { Card, CardContent, CardHeader } from '@/components/ui/card';
|
||||
import L, {
|
||||
Map as LeafletMap,
|
||||
} from 'leaflet';
|
||||
import 'leaflet/dist/leaflet.css'
|
||||
|
||||
const props = defineProps({
|
||||
guid: { type: String as PropType<string>, required: true },
|
||||
})
|
||||
const mapContainer = ref<HTMLDivElement | null>(null)
|
||||
onMounted(async () => {
|
||||
// wait until the flex layout has settled
|
||||
await nextTick()
|
||||
|
||||
if (!mapContainer.value) return
|
||||
|
||||
const map = L.map(mapContainer.value).setView([48.38, 31.17], 6)
|
||||
L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
|
||||
maxZoom: 19,
|
||||
attribution: '© OpenStreetMap contributors',
|
||||
}).addTo(map)
|
||||
|
||||
// force Leaflet to recalc its size
|
||||
map.invalidateSize()
|
||||
})
|
||||
|
||||
</script>
|
||||
<template>
|
||||
<Tabs default-value="records">
|
||||
<TabsList class="space-x-8">
|
||||
<TabsTrigger value="dashboard">
|
||||
Dashboard
|
||||
</TabsTrigger>
|
||||
<TabsTrigger value="locations">
|
||||
Locations
|
||||
</TabsTrigger>
|
||||
</TabsList>
|
||||
<TabsContent value="dashboard">
|
||||
<TrackerDashboard />
|
||||
</TabsContent>
|
||||
<TabsContent value="locations">
|
||||
<div class="flex h-full">
|
||||
<Card class="w-1/2 p-4 flex flex-col">
|
||||
|
||||
</Card>
|
||||
<div class="w-1/2 p-4">
|
||||
<div ref="mapContainer" class="w-full h-full rounded-lg shadow-inner">
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</TabsContent>
|
||||
</Tabs>
|
||||
</template>
|
||||
77
management-ui/src/customcompometns/TrackerDashboard.vue
Normal file
77
management-ui/src/customcompometns/TrackerDashboard.vue
Normal file
@@ -0,0 +1,77 @@
|
||||
<script setup lang="ts">
|
||||
import {
|
||||
Card,
|
||||
CardContent,
|
||||
CardDescription,
|
||||
CardFooter,
|
||||
CardHeader,
|
||||
CardTitle,
|
||||
} from "@/components/ui/card";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Label } from "@/components/ui/label";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import {
|
||||
NumberField,
|
||||
NumberFieldContent,
|
||||
NumberFieldDecrement,
|
||||
NumberFieldIncrement,
|
||||
NumberFieldInput,
|
||||
} from '@/components/ui/number-field'
|
||||
import AssignDevice from "./AssignDevice.vue";
|
||||
import { ref } from "vue";
|
||||
import Separator from "@/components/ui/separator/Separator.vue";
|
||||
import DataRangePicker from "./DataRangePicker.vue";
|
||||
const selectedUserIds = ref<string[]>([])
|
||||
const usrIDs = selectedUserIds.value
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<Card class="flex w-full max-w-4xl mx-auto">
|
||||
<CardHeader class="pb-4">
|
||||
<CardTitle>
|
||||
Dashboard
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent class="flex-1 space-y-6">
|
||||
<div class="grid gap-5">
|
||||
<div class="grid space-y-2 grid-cols-4 items-center">
|
||||
<Label for="users">Allowed users</Label>
|
||||
<AssignDevice v-model="usrIDs" class="col-span-3 w-full"></AssignDevice>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="flex space-x-4 pt-2 gap-4">
|
||||
<Button>Start</Button>
|
||||
<Button>Stop</Button>
|
||||
</div>
|
||||
<Separator class="my-6">Communication settings</Separator>
|
||||
<div class="grid grid-cols-1 md:grid-cols-2 gap-6">
|
||||
<div class="space-y-2">
|
||||
<NumberField id="polling" :default-value="60" :min="30">
|
||||
<Label for="polling"> Timeout interwal in seconds </Label>
|
||||
<NumberFieldContent>
|
||||
<NumberFieldDecrement></NumberFieldDecrement>
|
||||
<NumberFieldInput></NumberFieldInput>
|
||||
<NumberFieldIncrement></NumberFieldIncrement>
|
||||
</NumberFieldContent>
|
||||
</NumberField>
|
||||
</div>
|
||||
<div class="space-y-2">
|
||||
<NumberField id="jitter" :default-value="10" :min="5">
|
||||
<Label for="jitter"> Jitter in seconds </Label>
|
||||
<NumberFieldContent>
|
||||
<NumberFieldDecrement></NumberFieldDecrement>
|
||||
<NumberFieldInput></NumberFieldInput>
|
||||
<NumberFieldIncrement></NumberFieldIncrement>
|
||||
</NumberFieldContent>
|
||||
</NumberField>
|
||||
</div>
|
||||
</div>
|
||||
<Separator></Separator>
|
||||
<div class="space-y-2 gap-4">
|
||||
<Label for="sleepdate">Date/time to sleep</Label>
|
||||
<DataRangePicker id="sleepdate"></DataRangePicker>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</template>
|
||||
104
management-ui/src/customcompometns/TrackerGrid.vue
Normal file
104
management-ui/src/customcompometns/TrackerGrid.vue
Normal file
@@ -0,0 +1,104 @@
|
||||
<script setup lang="ts">
|
||||
import { defineProps, onBeforeUnmount, onMounted, ref } from 'vue'
|
||||
import { Card, CardHeader, CardTitle, CardContent } from '@/components/ui/card'
|
||||
import type { Device } from '@/lib/interfaces'
|
||||
import { api } from '@/lib/api';
|
||||
|
||||
const props = defineProps<{
|
||||
}>()
|
||||
// ----- API response models (same as before) -----
|
||||
type ApiDeviceUser = { id: number; username: string; role: string }
|
||||
type ApiTracker = { guid: string; name: string; users?: ApiDeviceUser[] }
|
||||
type TrackersResponse = { trackers: ApiTracker[]; offset: number; limit: number; total: number }
|
||||
|
||||
function isTrackersResponse(t: unknown): t is TrackersResponse {
|
||||
const x = t as any
|
||||
return !!x && Array.isArray(x.trackers) &&
|
||||
x.trackers.every((dev: any) =>
|
||||
dev &&
|
||||
typeof dev.guid === 'string' &&
|
||||
typeof dev.name === 'string' &&
|
||||
(
|
||||
dev.users === undefined ||
|
||||
(
|
||||
Array.isArray(dev.users) &&
|
||||
dev.users.every((u: any) => u && typeof u.username === 'string')
|
||||
)
|
||||
)
|
||||
)
|
||||
}
|
||||
|
||||
const trackers_data = ref<Device[]>([])
|
||||
const loading = ref(false)
|
||||
const error = ref<string | null>(null)
|
||||
|
||||
const tracker_columns = [
|
||||
{ accessorKey: 'guid', header: 'GUID' },
|
||||
{ accessorKey: 'devicename', header: 'Tracker' },
|
||||
{ accessorKey: 'assigned_users', header: 'Users' },
|
||||
]
|
||||
|
||||
let treckerCtrl: AbortController | null = null
|
||||
|
||||
async function loadTrackers() {
|
||||
error.value = null
|
||||
loading.value = true
|
||||
try {
|
||||
treckerCtrl?.abort()
|
||||
treckerCtrl = new AbortController()
|
||||
const { data } = await api.get('/trackers', { signal: treckerCtrl.signal })
|
||||
|
||||
if (!isTrackersResponse(data)) throw new Error('Unexpected trackers response')
|
||||
|
||||
// Transform API -> table shape
|
||||
trackers_data.value = data.trackers.map((d) => ({
|
||||
guid: d.guid,
|
||||
devicename: d.name,
|
||||
assigned_users: Array.isArray(d.users) ? d.users.map(u => u.username).join(', ') : '',
|
||||
}))
|
||||
} catch (e: any) {
|
||||
if (e?.name === 'CanceledError' || e?.message === 'canceled') return
|
||||
error.value = 'Failed to load trackers.'
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
}
|
||||
onMounted(loadTrackers)
|
||||
onBeforeUnmount(() => treckerCtrl?.abort())
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="space-y-4">
|
||||
<div v-if="loading">Loading trackers</div>
|
||||
<div v-else-if="error" class="text-red-600">{{ error }}</div>
|
||||
<div v-else class="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-6">
|
||||
<router-link v-for="device in trackers_data" :key="device.guid"
|
||||
:to="{ name: 'TrackerView', params: { guid: device.guid } }" class="block group hover:no-underline">
|
||||
<Card class="h-full transition-shadow group-hover:shadow-lg">
|
||||
<CardHeader class="bg-primary/5">
|
||||
<CardTitle class="text-lg">
|
||||
{{ device.devicename }}
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<p class="text-sm text-muted-foreground mb-2">
|
||||
<span class="font-medium">GUID:</span> {{ device.guid }}
|
||||
</p>
|
||||
<p class="text-sm">
|
||||
<span class="font-medium">Assigned Users:</span><br />
|
||||
{{ device.assigned_users || '—' }}
|
||||
</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</router-link>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
/* ensure cards stretch to fill the anchor height */
|
||||
a>.Card {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
}
|
||||
</style>
|
||||
@@ -27,6 +27,11 @@ type CreateUserPayload = {
|
||||
role: string // 'admin' | 'user'
|
||||
}
|
||||
|
||||
type CreateTrackerPayload = {
|
||||
guid: string
|
||||
name: string
|
||||
userIds: number[]
|
||||
}
|
||||
|
||||
const router = useRouter()
|
||||
|
||||
@@ -49,6 +54,11 @@ const user_form = reactive({
|
||||
isAdmin: false,
|
||||
})
|
||||
|
||||
const tracker_form = reactive({
|
||||
guid: uuidv4(),
|
||||
name: '',
|
||||
})
|
||||
|
||||
// userIds from AssignDevice (expects v-model of string[] ids)
|
||||
const selectedUserIds = ref<string[]>([])
|
||||
|
||||
@@ -65,6 +75,8 @@ watch(
|
||||
userError.value = null
|
||||
userSubmitting.value = false
|
||||
userSuccess.value = null
|
||||
// tracker_form.guid = uuidv4()
|
||||
// tracker_form.name = ''
|
||||
}
|
||||
}
|
||||
)
|
||||
@@ -151,6 +163,35 @@ async function submitUser() {
|
||||
userSubmitting.value = false
|
||||
}
|
||||
}
|
||||
|
||||
async function submitTracker() {
|
||||
errorMsg.value = null
|
||||
if (!canSubmit.value) {
|
||||
errorMsg.value = 'Please provide a valid GUID and name.'
|
||||
return
|
||||
}
|
||||
|
||||
const userIds: number[] = selectedUserIds.value
|
||||
.map((s) => Number(s))
|
||||
.filter((n) => Number.isFinite(n) && n >= 0)
|
||||
|
||||
const payload: CreateDevicePayload = {
|
||||
guid: device_form.guid,
|
||||
name: device_form.name.trim(),
|
||||
userIds,
|
||||
}
|
||||
|
||||
submitting.value = true
|
||||
try {
|
||||
await api.post('/trackers/create', payload)
|
||||
router.replace('/admin')
|
||||
} catch (e: any) {
|
||||
// keep client error generic
|
||||
errorMsg.value = e?.response?.status === 403 ? 'Access denied.' : 'Failed to create device.'
|
||||
} finally {
|
||||
submitting.value = false
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
@@ -239,6 +280,43 @@ async function submitUser() {
|
||||
</Button>
|
||||
</CardFooter>
|
||||
</Card>
|
||||
|
||||
<Card class="h-full flex flex-col">
|
||||
<CardHeader>
|
||||
<CardTitle>Create tracker</CardTitle>
|
||||
</CardHeader>
|
||||
|
||||
<CardContent class="flex-1">
|
||||
<!-- add vertical spacing between rows -->
|
||||
<div class="grid gap-5">
|
||||
<div class="grid grid-cols-4 items-center gap-4">
|
||||
<Label for="guid" class="text-right">GUID</Label>
|
||||
<Input id="guid" class="col-span-3 w-full" v-model="device_form.guid" />
|
||||
</div>
|
||||
|
||||
<div class="grid grid-cols-4 items-center gap-4">
|
||||
<Label for="name" class="text-right">Name</Label>
|
||||
<Input id="name" class="col-span-3 w-full" v-model="device_form.name" />
|
||||
</div>
|
||||
|
||||
<div class="grid grid-cols-4 items-center gap-4">
|
||||
<Label for="users" class="text-right">Allowed users</Label>
|
||||
<!-- make the component span and fill -->
|
||||
<AssignDevice id="users" class="col-span-3 w-full" v-model="selectedUserIds" />
|
||||
</div>
|
||||
<p v-if="errorMsg" class="text-sm text-red-600" aria-live="assertive">
|
||||
{{ errorMsg }}
|
||||
</p>
|
||||
</div>
|
||||
</CardContent>
|
||||
|
||||
<CardFooter>
|
||||
<Button :disabled="!canSubmit" @click="submitTracker">
|
||||
{{ submitting ? 'Saving…' : 'Save' }}
|
||||
</Button>
|
||||
</CardFooter>
|
||||
</Card>
|
||||
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
16
management-ui/src/pages/TrackerViev.vue
Normal file
16
management-ui/src/pages/TrackerViev.vue
Normal file
@@ -0,0 +1,16 @@
|
||||
<script setup lang="ts">
|
||||
import { useColorMode } from '@vueuse/core'
|
||||
import Navbar from '@/customcompometns/Navbar.vue';
|
||||
import { useRoute } from 'vue-router';
|
||||
import { computed } from 'vue';
|
||||
import TrackerComponent from '@/customcompometns/TrackerComponent.vue';
|
||||
const mode = useColorMode()
|
||||
const route = useRoute()
|
||||
const guid = computed(() => String(route.params.guid ?? route.query.guid ?? ''))
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<Navbar>
|
||||
<TrackerComponent :guid="guid"></TrackerComponent>
|
||||
</Navbar>
|
||||
</template>
|
||||
14
management-ui/src/pages/Trackers.vue
Normal file
14
management-ui/src/pages/Trackers.vue
Normal file
@@ -0,0 +1,14 @@
|
||||
<script setup lang="ts">
|
||||
import { useColorMode } from '@vueuse/core'
|
||||
import Navbar from '@/customcompometns/Navbar.vue';
|
||||
import DevicesGrid from '@/customcompometns/DevicesGrid.vue';
|
||||
import TrackerGrid from '@/customcompometns/TrackerGrid.vue';
|
||||
const mode = useColorMode()
|
||||
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<Navbar>
|
||||
<TrackerGrid />
|
||||
</Navbar>
|
||||
</template>
|
||||
@@ -7,6 +7,8 @@ import Devices from '@/pages/Devices.vue';
|
||||
import DeviceView from './pages/DeviceView.vue';
|
||||
import Forbidden from './pages/Forbidden.vue';
|
||||
import Create from './pages/Create.vue';
|
||||
import Trackers from '@/pages/Trackers.vue';
|
||||
import TrackerViev from '@/pages/TrackerViev.vue';
|
||||
import { auth } from './lib/auth';
|
||||
|
||||
|
||||
@@ -64,7 +66,20 @@ const routes = [
|
||||
name: 'Create',
|
||||
component: Create,
|
||||
meta: { requiresAuth: true, roles: ['admin'] }
|
||||
}
|
||||
},
|
||||
{
|
||||
path: '/trackers',
|
||||
name: 'Trackers',
|
||||
component: Trackers,
|
||||
meta: { requiresAuth: true }
|
||||
},
|
||||
{
|
||||
path: '/tracker/:guid', // ← new dynamic segment
|
||||
name: 'TrackerView',
|
||||
component: TrackerViev,
|
||||
props: true, // so `guid` shows up as a prop
|
||||
meta: { requiresAuth: true }
|
||||
},
|
||||
]
|
||||
|
||||
const router = createRouter({
|
||||
|
||||
76
mediamtx/mediamtx.yml
Normal file
76
mediamtx/mediamtx.yml
Normal file
@@ -0,0 +1,76 @@
|
||||
logLevel: info
|
||||
|
||||
# Enable Control API (useful for debugging; bound to localhost by default)
|
||||
api: yes
|
||||
apiAddress: :9997
|
||||
|
||||
# RTSP / RTMP / HLS
|
||||
rtsp: yes
|
||||
rtspAddress: :8554
|
||||
rtmp: yes
|
||||
rtmpAddress: :1935
|
||||
hls: yes
|
||||
hlsAddress: :8888
|
||||
hlsVariant: lowLatency
|
||||
|
||||
# WebRTC (browser-friendly)
|
||||
webrtc: yes
|
||||
webrtcAddress: :8889
|
||||
webrtcLocalUDPAddress: :8189
|
||||
# Optional: add a STUN server if behind NAT
|
||||
# webrtcICEServers2:
|
||||
# - url: stun:stun.l.google.com:19302
|
||||
|
||||
# SRT (for resilient ingest)
|
||||
srt: yes
|
||||
srtAddress: :8890
|
||||
|
||||
authMethod: http
|
||||
authHTTPAddress: http://snoop-api:8080/mediamtx/auth
|
||||
authHTTPExclude:
|
||||
- action: api
|
||||
- action: metrics
|
||||
- action: pprof
|
||||
|
||||
# Recording (optional)
|
||||
pathDefaults:
|
||||
# record settings (per concurrent path/stream)
|
||||
record: yes
|
||||
recordFormat: fmp4
|
||||
recordPath: /recordings/%path/%Y-%m-%d_%H-%M-%S-%f
|
||||
recordSegmentDuration: 10m
|
||||
recordDeleteAfter: 7d
|
||||
|
||||
# upload each completed segment to MinIO under:
|
||||
# livestream/<device-guid>/<filename>
|
||||
# runOnRecordSegmentComplete: >
|
||||
# sh -c 'd="$(dirname "$MTX_SEGMENT_PATH")";
|
||||
# f="$(basename "$MTX_SEGMENT_PATH")";
|
||||
# curl -s -H "Content-Type: application/json"
|
||||
# -X POST "http://rclone:5572/operations/copyfile?_async=true"
|
||||
# -d "{\"srcFs\":\"$d\",\"srcRemote\":\"$f\",
|
||||
# \"dstFs\":\"minio:livestream\",
|
||||
# \"dstRemote\":\"$MTX_PATH/$f\"}"'
|
||||
|
||||
runOnRecordSegmentCreate: >
|
||||
sh -c 'd="$(dirname "$MTX_SEGMENT_PATH")";
|
||||
f="$(basename "$MTX_SEGMENT_PATH")";
|
||||
curl -s -H "Content-Type: application/json"
|
||||
-X POST "http://rclone:5572/operations/copyfile?_async=true"
|
||||
-d "{\"srcFs\":\"$d\",\"srcRemote\":\"$f\",
|
||||
\"dstFs\":\"minio:livestream\",
|
||||
\"dstRemote\":\"$MTX_PATH/$f\"}"'
|
||||
|
||||
authInternalUsers:
|
||||
- user: any
|
||||
pass:
|
||||
ips: ['127.0.0.1','::1']
|
||||
permissions:
|
||||
- action: api
|
||||
- action: metrics
|
||||
- action: pprof
|
||||
|
||||
# Allow all paths by default
|
||||
paths:
|
||||
all:
|
||||
source: publisher
|
||||
118
nginx/dev.conf
118
nginx/dev.conf
@@ -40,4 +40,122 @@ server {
|
||||
proxy_read_timeout 3600s;
|
||||
proxy_send_timeout 3600s;
|
||||
}
|
||||
|
||||
# --- MQTT over WebSocket (EMQX) ---
|
||||
# Clients connect to ws://<host>/mqtt/ws
|
||||
location /mqtt/ws {
|
||||
proxy_pass http://emqx:8083/mqtt; # EMQX WS path is /mqtt
|
||||
proxy_http_version 1.1;
|
||||
proxy_set_header Upgrade $http_upgrade;
|
||||
proxy_set_header Connection $connection_upgrade;
|
||||
proxy_read_timeout 3600s;
|
||||
proxy_send_timeout 3600s;
|
||||
}
|
||||
}
|
||||
|
||||
# ==============================================
|
||||
# HTTPS :443 — mTLS enforced only on listed paths
|
||||
# ==============================================
|
||||
server {
|
||||
listen 443 ssl http2;
|
||||
server_name _;
|
||||
|
||||
ssl_certificate /etc/nginx/ssl/certs/fullchain.pem;
|
||||
ssl_certificate_key /etc/nginx/ssl/certs/privkey.pem;
|
||||
ssl_protocols TLSv1.2 TLSv1.3;
|
||||
ssl_prefer_server_ciphers on;
|
||||
|
||||
# mTLS trust chain (from Vault)
|
||||
ssl_client_certificate /etc/nginx/ssl/iot_int_cert.pem;
|
||||
ssl_verify_client optional; # locations below require SUCCESS
|
||||
ssl_verify_depth 3;
|
||||
|
||||
# Client cert revocation (optional)
|
||||
# ssl_crl /etc/nginx/ssl/iot.crl;
|
||||
|
||||
# Forward client cert details upstream
|
||||
proxy_set_header X-SSL-Client-Verify $ssl_client_verify;
|
||||
proxy_set_header X-SSL-Client-Serial $ssl_client_serial;
|
||||
proxy_set_header X-SSL-Client-Issuer $ssl_client_i_dn;
|
||||
proxy_set_header X-SSL-Client-DN $ssl_client_s_dn;
|
||||
proxy_set_header X-SSL-Client-Cert $ssl_client_escaped_cert;
|
||||
|
||||
proxy_read_timeout 3600s;
|
||||
proxy_send_timeout 3600s;
|
||||
|
||||
error_page 495 = @mtls_error;
|
||||
|
||||
# location @mtls_error {
|
||||
# return 403 "ERR_SSL_VERSION_OR_CIPHER_MISMATCH \n";
|
||||
# }
|
||||
|
||||
location @mtls_error {
|
||||
return 403 "mTLS required or client certificate invalid.\n";
|
||||
}
|
||||
|
||||
location = /_mtls_check {
|
||||
return 200 "$ssl_client_verify\n$ssl_client_s_dn\n$ssl_client_i_dn\n";
|
||||
}
|
||||
|
||||
# ---- mTLS-protected paths ----
|
||||
location ^~ /records {
|
||||
if ($ssl_client_verify != SUCCESS) {
|
||||
return 495;
|
||||
}
|
||||
proxy_pass http://snoop-api:8080;
|
||||
}
|
||||
|
||||
location ^~ /tasks {
|
||||
if ($ssl_client_verify != SUCCESS) {
|
||||
return 495;
|
||||
}
|
||||
proxy_pass http://snoop-api:8080;
|
||||
}
|
||||
|
||||
location ^~ /renew {
|
||||
if ($ssl_client_verify != SUCCESS) {
|
||||
return 495;
|
||||
}
|
||||
proxy_pass http://snoop-api:8080;
|
||||
}
|
||||
|
||||
# MediaMTX HLS
|
||||
location ^~ /hls/ {
|
||||
if ($ssl_client_verify != SUCCESS) {
|
||||
return 495;
|
||||
}
|
||||
proxy_pass http://mediamtx:8888/;
|
||||
}
|
||||
|
||||
# MediaMTX WebRTC (WHIP/WHEP/test)
|
||||
location ^~ /webrtc/ {
|
||||
if ($ssl_client_verify != SUCCESS) {
|
||||
return 495;
|
||||
}
|
||||
proxy_pass http://mediamtx:8889/;
|
||||
proxy_set_header Upgrade $http_upgrade;
|
||||
proxy_set_header Connection $connection_upgrade;
|
||||
}
|
||||
|
||||
# MQTT WS entry points (guarded by mTLS)
|
||||
location = /loc {
|
||||
if ($ssl_client_verify != SUCCESS) {
|
||||
return 495;
|
||||
}
|
||||
proxy_pass http://emqx:8083/mqtt;
|
||||
proxy_http_version 1.1;
|
||||
proxy_set_header Upgrade $http_upgrade;
|
||||
proxy_set_header Connection $connection_upgrade;
|
||||
}
|
||||
|
||||
location = /gtasks {
|
||||
if ($ssl_client_verify != SUCCESS) {
|
||||
return 495;
|
||||
}
|
||||
proxy_pass http://emqx:8083/mqtt;
|
||||
proxy_http_version 1.1;
|
||||
proxy_set_header Upgrade $http_upgrade;
|
||||
proxy_set_header Connection $connection_upgrade;
|
||||
}
|
||||
|
||||
}
|
||||
91
readme.md
91
readme.md
@@ -20,9 +20,10 @@ vault kv put kv/snoop \
|
||||
minio_presign_ttl_seconds="900"
|
||||
```
|
||||
|
||||
Unseal Key: gQrvvJBaGR4CpmkoVq93tWqk5dTpioMAHtNHKMWNlH0=
|
||||
Unseal Key 1: XdERN+/hxR9RjLC/S8c+y0omToYvB7Qs1jaUenZQvphD
|
||||
Unseal Key 2: VBhPBtYcq1GAk7ByPfAsamxV4tJOZ49chAYxxOvc49Oj
|
||||
|
||||
Root Token: root
|
||||
Initial Root Token: hvs.tZ4eh9P18sCZ5c1PZIz59EmH
|
||||
|
||||
|
||||
{
|
||||
@@ -36,3 +37,89 @@ Root Token: root
|
||||
"minio_livestream_bucket": "livestream",
|
||||
"minio_presign_ttl_seconds": "900"
|
||||
}
|
||||
|
||||
### Stand up internal CA (root + intermediate)
|
||||
```bash
|
||||
# Enable PKI backends (root + intermediate)
|
||||
vault secrets enable -path=pki_root pki
|
||||
vault secrets tune -max-lease-ttl=87600h pki_root # 10y
|
||||
|
||||
vault write pki_root/root/generate/internal \
|
||||
common_name="Snoop Root CA" key_type=ec key_bits=256 ttl=87600h
|
||||
|
||||
vault secrets enable -path=pki_iot pki
|
||||
vault secrets tune -max-lease-ttl=17520h pki_iot # 2y
|
||||
|
||||
# Create an intermediate CSR
|
||||
vault write -field=csr pki_iot/intermediate/generate/internal \
|
||||
common_name="Snoop IoT Intermediate" key_type=ec key_bits=256 ttl=17520h > iot_int.csr
|
||||
|
||||
# Sign intermediate with root
|
||||
vault write -field=certificate pki_root/root/sign-intermediate csr=@iot_int.csr \
|
||||
format=pem_bundle ttl=17520h > iot_int_signed.pem
|
||||
|
||||
vault write -field=issuing_ca pki_root/root/sign-intermediate \
|
||||
csr=@iot_int.csr format=pem_bundle ttl=17520h > root_ca.pem
|
||||
|
||||
# Set the signed intermediate in Vault
|
||||
vault write pki_iot/intermediate/set-signed certificate=@iot_int_signed.pem
|
||||
```
|
||||
|
||||
### Configure URLs + a role for devices
|
||||
```bash
|
||||
# Publish issuing + CRL URLs (Nginx will fetch CRL periodically)
|
||||
vault write pki_iot/config/urls \
|
||||
issuing_certificates="https://vault.example.local/v1/pki_iot/ca" \
|
||||
crl_distribution_points="https://vault.example.local/v1/pki_iot/crl"
|
||||
|
||||
# Role that limits cert subjects to your device GUIDs
|
||||
vault write pki_iot/roles/device \
|
||||
allow_any_name=true \
|
||||
allowed_uri_sans="urn:device:*" \
|
||||
allowed_other_sans="" \
|
||||
require_cn=false \
|
||||
cn_validations= \
|
||||
allow_ip_sans=false \
|
||||
allowed_domains="" \
|
||||
enforce_hostnames=false \
|
||||
key_type=ec \
|
||||
key_bits=256 \
|
||||
max_ttl=720h ttl=720h # 30 days
|
||||
```
|
||||
|
||||
### Enrollment flow (device CSR → signed cert)
|
||||
- Device side
|
||||
- Generate keypair on the device (never export private key).
|
||||
- Create CSR with CN=<GUID> and URI SAN urn:device:<GUID>.
|
||||
|
||||
- Server side
|
||||
- Backend verifies a one-time enrollment token (or pre-shared bootstrap secret), calls:
|
||||
```bash
|
||||
vault write pki_iot/sign/device \
|
||||
csr=@device.csr \
|
||||
uri_sans="urn:device:<GUID>" \
|
||||
ttl=720h > device_cert.pem
|
||||
```
|
||||
|
||||
### Revocation
|
||||
- Immediate kill: your backend stores bad serials; deny in app logic.
|
||||
- CRL: `vault write pki_iot/revoke serial_number="<SERIAL>"`.
|
||||
- Fetch CRL periodically to a local file for Nginx:
|
||||
```bash
|
||||
curl -fsSL https://vault.example.local/v1/pki_iot/crl -o /etc/nginx/iot.crl
|
||||
nginx -s reload
|
||||
```
|
||||
- Automate via systemd timer/cron (e.g., every 10–15 min).
|
||||
|
||||
- Nginx fix for DER CRL format
|
||||
```bash
|
||||
# sed -i 's/\r$//' ./nginx/nginx_ssl/int_iot.crl
|
||||
curl http://vault.local:8200/v1/pki_iot/crl -o nginx/nginx_ssl/int_iot.crl
|
||||
openssl crl -in ./nginx/nginx_ssl/int_iot.crl -out ./nginx/nginx_ssl/int_iot.crl.clean -outform PEM
|
||||
mv ./nginx/nginx_ssl/int_iot.crl.clean ./nginx/nginx_ssl/int_iot.crl
|
||||
curl http://vault.local:8200/v1/pki_root/crl -o nginx/nginx_ssl/root_iot.crl
|
||||
openssl crl -in ./nginx/nginx_ssl/root_iot.crl -out ./nginx/nginx_ssl/root_iot.crl.clean -outform PEM
|
||||
mv ./nginx/nginx_ssl/root_iot.crl.clean ./nginx/nginx_ssl/root_iot.crl
|
||||
(sed 's/\r$//' ./nginx/nginx_ssl/int_iot.crl; echo; sed 's/\r$//' ./nginx/nginx_ssl/root_iot.crl; echo) \
|
||||
> ./nginx/nginx_ssl/iot.crl
|
||||
```
|
||||
@@ -10,6 +10,13 @@ import (
|
||||
"smoop-api/internal/vault"
|
||||
)
|
||||
|
||||
type MediaMTXConfig struct {
|
||||
APIBase string // e.g. "http://mediamtx:9997"
|
||||
WebRTCBaseURL string // e.g. "http://mediamtx:8889"
|
||||
PublicBaseURL string // e.g. "https://your-host" (for HLS/WHEP URLs returned to SPA)
|
||||
TokenTTL time.Duration // default ~180s
|
||||
}
|
||||
|
||||
type Config struct {
|
||||
DB struct {
|
||||
DSN string
|
||||
@@ -23,7 +30,9 @@ type Config struct {
|
||||
LivestreamBucket string
|
||||
PresignTTL time.Duration
|
||||
}
|
||||
MediaMTX MediaMTXConfig
|
||||
JWTSecret []byte
|
||||
PkiIot vault.PKIClient
|
||||
}
|
||||
|
||||
func Load() (*Config, error) {
|
||||
@@ -48,6 +57,10 @@ func Load() (*Config, error) {
|
||||
return nil, fmt.Errorf("VAULT_ADDR, VAULT_TOKEN, VAULT_KV_MOUNT and VAULT_KV_KEY must be set (or provide legacy VAULT_KV_PATH)")
|
||||
}
|
||||
|
||||
pki, err := vault.NewPKI(addr, token, "pki_iot", "device", 30*time.Second)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
raw, err := vault.ReadKVv2(addr, token, mount, key)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
@@ -60,6 +73,12 @@ func Load() (*Config, error) {
|
||||
}
|
||||
return v, nil
|
||||
}
|
||||
// getStrOpt := func(k, def string) string {
|
||||
// if v, ok := raw[k].(string); ok && v != "" {
|
||||
// return v
|
||||
// }
|
||||
// return def
|
||||
// }
|
||||
getBool := func(k string) (bool, error) {
|
||||
v, ok := raw[k]
|
||||
if !ok {
|
||||
@@ -77,6 +96,32 @@ func Load() (*Config, error) {
|
||||
return false, fmt.Errorf("invalid bool for key %s", k)
|
||||
}
|
||||
}
|
||||
getTTL := func(k string, def time.Duration) time.Duration {
|
||||
if v, ok := raw[k].(string); ok && strings.TrimSpace(v) != "" {
|
||||
if n, err := strconv.Atoi(strings.TrimSpace(v)); err == nil && n > 0 {
|
||||
return time.Duration(n) * time.Second
|
||||
}
|
||||
}
|
||||
return def
|
||||
}
|
||||
|
||||
// --- NEW: MediaMTX config FROM ENV (NOT from Vault)
|
||||
getRequiredEnv := func(k string) (string, error) {
|
||||
v := strings.TrimSpace(os.Getenv(k))
|
||||
if v == "" {
|
||||
return "", fmt.Errorf("missing required env %s", k)
|
||||
}
|
||||
return v, nil
|
||||
}
|
||||
|
||||
getIntEnv := func(k string, def int) int {
|
||||
if v := strings.TrimSpace(os.Getenv(k)); v != "" {
|
||||
if n, err := strconv.Atoi(v); err == nil {
|
||||
return n
|
||||
}
|
||||
}
|
||||
return def
|
||||
}
|
||||
|
||||
dbDSN, err := getStr("db_dsn")
|
||||
if err != nil {
|
||||
@@ -111,14 +156,29 @@ func Load() (*Config, error) {
|
||||
if v, ok := raw["minio_livestream_bucket"].(string); ok && v != "" {
|
||||
liveBucket = v
|
||||
}
|
||||
presignTTL := 15 * time.Minute
|
||||
if v, ok := raw["minio_presign_ttl_seconds"].(string); ok && v != "" {
|
||||
var sec int
|
||||
fmt.Sscanf(v, "%d", &sec)
|
||||
if sec > 0 {
|
||||
presignTTL = time.Duration(sec) * time.Second
|
||||
}
|
||||
// presignTTL := 15 * time.Minute
|
||||
// if v, ok := raw["minio_presign_ttl_seconds"].(string); ok && v != "" {
|
||||
// var sec int
|
||||
// fmt.Sscanf(v, "%d", &sec)
|
||||
// if sec > 0 {
|
||||
// presignTTL = time.Duration(sec) * time.Second
|
||||
// }
|
||||
// }
|
||||
presignTTL := getTTL("minio_presign_ttl_seconds", 15*time.Minute)
|
||||
|
||||
apiBase, err := getRequiredEnv("MEDIAMTX_API_BASE")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
webrtcBase, err := getRequiredEnv("MEDIAMTX_WEBRTC_BASE_URL")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
publicBase, err := getRequiredEnv("PUBLIC_BASE_URL")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
tokenTTL := getIntEnv("MEDIAMTX_TOKEN_TTL_SECONDS", 180)
|
||||
|
||||
cfg := &Config{}
|
||||
cfg.DB.DSN = dbDSN
|
||||
@@ -130,6 +190,15 @@ func Load() (*Config, error) {
|
||||
cfg.MinIO.LivestreamBucket = liveBucket
|
||||
cfg.MinIO.PresignTTL = presignTTL
|
||||
cfg.JWTSecret = []byte(jwt)
|
||||
|
||||
cfg.MediaMTX = MediaMTXConfig{
|
||||
APIBase: apiBase,
|
||||
WebRTCBaseURL: webrtcBase,
|
||||
PublicBaseURL: publicBase,
|
||||
TokenTTL: time.Duration(tokenTTL),
|
||||
}
|
||||
|
||||
cfg.PkiIot = *pki
|
||||
return cfg, nil
|
||||
}
|
||||
|
||||
@@ -141,6 +210,15 @@ func LoadDev() (*Config, error) {
|
||||
}
|
||||
return v, nil
|
||||
}
|
||||
|
||||
addr := os.Getenv("VAULT_ADDR")
|
||||
token := os.Getenv("VAULT_TOKEN")
|
||||
|
||||
pki, err := vault.NewPKI(addr, token, "pki_iot", "device", 30*time.Second)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
getBoolEnv := func(k string, def bool) bool {
|
||||
v := strings.ToLower(strings.TrimSpace(os.Getenv(k)))
|
||||
if v == "true" || v == "1" || v == "yes" {
|
||||
@@ -191,6 +269,21 @@ func LoadDev() (*Config, error) {
|
||||
}
|
||||
presignTTL := time.Duration(getIntEnv("MINIO_PRESIGN_TTL_SECONDS", 900)) * time.Second
|
||||
|
||||
// NEW: MediaMTX envs
|
||||
apiBase, err := getRequired("MEDIAMTX_API_BASE")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
webrtcBase, err := getRequired("MEDIAMTX_WEBRTC_BASE_URL")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
publicBase, err := getRequired("PUBLIC_BASE_URL")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
tokenTTL := getIntEnv("MEDIAMTX_TOKEN_TTL_SECONDS", 180)
|
||||
|
||||
cfg := &Config{}
|
||||
cfg.DB.DSN = dbDSN
|
||||
cfg.MinIO.Endpoint = endpoint
|
||||
@@ -201,5 +294,14 @@ func LoadDev() (*Config, error) {
|
||||
cfg.MinIO.LivestreamBucket = liveBucket
|
||||
cfg.MinIO.PresignTTL = presignTTL
|
||||
cfg.JWTSecret = []byte(jwt)
|
||||
|
||||
cfg.MediaMTX = MediaMTXConfig{
|
||||
APIBase: apiBase,
|
||||
WebRTCBaseURL: webrtcBase,
|
||||
PublicBaseURL: publicBase,
|
||||
TokenTTL: time.Duration(tokenTTL),
|
||||
}
|
||||
|
||||
cfg.PkiIot = *pki
|
||||
return cfg, nil
|
||||
}
|
||||
|
||||
@@ -1,8 +1,11 @@
|
||||
package crypto
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"smoop-api/internal/dto"
|
||||
|
||||
"github.com/golang-jwt/jwt/v5"
|
||||
)
|
||||
|
||||
@@ -28,3 +31,33 @@ func (j *JWTManager) Generate(userID uint, username, role string) (string, error
|
||||
func (j *JWTManager) Parse(tok string) (*jwt.Token, error) {
|
||||
return jwt.Parse(tok, func(t *jwt.Token) (interface{}, error) { return j.secret, nil })
|
||||
}
|
||||
|
||||
func (j *JWTManager) GenerateMediaToken(sub uint, act, path string, ttl time.Duration) (string, error) {
|
||||
now := time.Now()
|
||||
claims := dto.MediaClaims{
|
||||
Act: act,
|
||||
Path: path,
|
||||
RegisteredClaims: jwt.RegisteredClaims{
|
||||
Subject: fmt.Sprintf("%d", sub),
|
||||
IssuedAt: jwt.NewNumericDate(now),
|
||||
ExpiresAt: jwt.NewNumericDate(now.Add(ttl)),
|
||||
},
|
||||
}
|
||||
t := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
|
||||
return t.SignedString([]byte(j.secret))
|
||||
}
|
||||
|
||||
// NEW: parse a media token into typed claims
|
||||
func (j *JWTManager) ParseMedia(tokenStr string) (*dto.MediaClaims, error) {
|
||||
tok, err := jwt.ParseWithClaims(tokenStr, &dto.MediaClaims{}, func(t *jwt.Token) (interface{}, error) {
|
||||
return []byte(j.secret), nil
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
mc, ok := tok.Claims.(*dto.MediaClaims)
|
||||
if !ok || !tok.Valid {
|
||||
return nil, fmt.Errorf("invalid media token")
|
||||
}
|
||||
return mc, nil
|
||||
}
|
||||
|
||||
@@ -17,5 +17,10 @@ func AutoMigrate(db *gorm.DB) error {
|
||||
&models.Device{},
|
||||
&models.Record{},
|
||||
&models.UserDevice{},
|
||||
&models.Tracker{},
|
||||
&models.UserTracker{},
|
||||
&models.DEviceTask{},
|
||||
&models.DeviceCertificate{},
|
||||
&models.RevokedSerial{},
|
||||
)
|
||||
}
|
||||
|
||||
45
server/internal/dto/mediamtx.go
Normal file
45
server/internal/dto/mediamtx.go
Normal file
@@ -0,0 +1,45 @@
|
||||
package dto
|
||||
|
||||
import "github.com/golang-jwt/jwt/v5"
|
||||
|
||||
type MediaClaims struct {
|
||||
Act string `json:"act"` // "publish" or "read"
|
||||
Path string `json:"path"` // e.g. "live/<guid>"
|
||||
jwt.RegisteredClaims
|
||||
}
|
||||
|
||||
// MediaMTX external-auth POST body (exact keys per mediamtx.yml sample)
|
||||
type MediaMTXAuthReq struct {
|
||||
User string `json:"user"` // optional
|
||||
Password string `json:"password"` // optional
|
||||
Token string `json:"token"` // from Authorization: Bearer or query (?token=)
|
||||
IP string `json:"ip"`
|
||||
Action string `json:"action"` // publish|read|playback|api|metrics|pprof
|
||||
Path string `json:"path"` // e.g. "live/<guid>"
|
||||
Protocol string `json:"protocol"` // rtsp|rtmp|hls|webrtc|srt
|
||||
ID string `json:"id"` // session id
|
||||
Query string `json:"query"` // raw query string
|
||||
}
|
||||
|
||||
type MediaMTXAuthResp struct {
|
||||
// empty 200 means allowed; add fields if you want to return JSON
|
||||
// to mediamtx (not required)
|
||||
}
|
||||
|
||||
// Token minting
|
||||
type PublishTokenReq struct {
|
||||
GUID string `json:"guid" binding:"required,uuid4"`
|
||||
}
|
||||
|
||||
type PublishTokenResp struct {
|
||||
WHIP string `json:"whipUrl"` // http://mediamtx:8889/whip/live/<guid>?token=...
|
||||
}
|
||||
|
||||
type ReadTokenReq struct {
|
||||
GUID string `json:"guid" binding:"required,uuid4"`
|
||||
}
|
||||
|
||||
type ReadTokenResp struct {
|
||||
HLS string `json:"hlsUrl"` // http://<host>/hls/live/<guid>/index.m3u8?token=...
|
||||
WHEP string `json:"whepUrl"` // http://<host>/webrtc/play/live/<guid>?token=...
|
||||
}
|
||||
57
server/internal/dto/task.go
Normal file
57
server/internal/dto/task.go
Normal file
@@ -0,0 +1,57 @@
|
||||
package dto
|
||||
|
||||
import (
|
||||
"smoop-api/internal/models"
|
||||
"time"
|
||||
)
|
||||
|
||||
type TaskDto struct {
|
||||
ID uint `json:"id"`
|
||||
DeviceGUID string `json:"deviceGuid"`
|
||||
Type models.DeviceTaskType `json:"type"`
|
||||
Payload string `json:"payload"` // raw JSON string
|
||||
Status models.TaskStatus `json:"status"`
|
||||
ErrorMsg string `json:"error,omitempty"`
|
||||
Result string `json:"result,omitempty"`
|
||||
CreatedAt time.Time `json:"createdAt"`
|
||||
StartedAt *time.Time `json:"startedAt,omitempty"`
|
||||
FinishedAt *time.Time `json:"finishedAt,omitempty"`
|
||||
}
|
||||
|
||||
func MapTask(t models.DEviceTask) TaskDto {
|
||||
return TaskDto{
|
||||
ID: t.ID,
|
||||
DeviceGUID: t.DeviceGUID,
|
||||
Type: t.Type,
|
||||
Payload: t.Payload,
|
||||
Status: t.Status,
|
||||
ErrorMsg: t.ErrorMsg,
|
||||
Result: t.Result,
|
||||
CreatedAt: t.CreatedAt,
|
||||
StartedAt: t.StartedAt,
|
||||
FinishedAt: t.FinishedAt,
|
||||
}
|
||||
}
|
||||
|
||||
// Create a new task (server/user -> device)
|
||||
type CreateTaskDto struct {
|
||||
Type models.DeviceTaskType `json:"type" binding:"required,oneof=start_stream stop_stream start_recording stop_recording update_config set_deep_sleep"`
|
||||
// Pass raw JSON string as payload (e.g. {"sleepTimeout":5,"jitterMs":50,"recordingDurationSec":60})
|
||||
// Keep it string to let device/server evolve freely.
|
||||
Payload string `json:"payload" binding:"required"`
|
||||
}
|
||||
|
||||
// Device polls: single next task
|
||||
type NextTaskResponseDto struct {
|
||||
HasTask bool `json:"hasTask"`
|
||||
Task *TaskDto `json:"task,omitempty"`
|
||||
}
|
||||
|
||||
// Device posts result
|
||||
type TaskResultDto struct {
|
||||
TaskID uint `json:"taskId" binding:"required"`
|
||||
// success=true => Finished, success=false => Error
|
||||
Success bool `json:"success"`
|
||||
Result string `json:"result"` // raw JSON result from device
|
||||
ErrorMsg string `json:"error"` // device-side reason if !Success
|
||||
}
|
||||
44
server/internal/dto/tracker.go
Normal file
44
server/internal/dto/tracker.go
Normal file
@@ -0,0 +1,44 @@
|
||||
package dto
|
||||
|
||||
import "smoop-api/internal/models"
|
||||
|
||||
type TrackerDto struct {
|
||||
GUID string `json:"guid"`
|
||||
Name string `json:"name"`
|
||||
Users []UserDto `json:"users,omitempty"`
|
||||
}
|
||||
|
||||
type TrackerListDto struct {
|
||||
Trackers []TrackerDto `json:"trackers"`
|
||||
Offset int `json:"offset"`
|
||||
Limit int `json:"limit"`
|
||||
Total int64 `json:"total"`
|
||||
}
|
||||
|
||||
type CreateTrackerDto struct {
|
||||
GUID string `json:"guid" binding:"required"`
|
||||
Name string `json:"name" binding:"required"`
|
||||
UserIDs []uint `json:"userIds"`
|
||||
}
|
||||
|
||||
type RenameTrackerDto struct {
|
||||
Name string `json:"name" binding:"required"`
|
||||
}
|
||||
|
||||
type SetTrackerUsersDto struct {
|
||||
UserIDs []uint `json:"userIds"`
|
||||
}
|
||||
|
||||
func MapTracker(t models.Tracker) TrackerDto {
|
||||
out := TrackerDto{
|
||||
GUID: t.GUID,
|
||||
Name: t.Name,
|
||||
}
|
||||
if len(t.Users) > 0 {
|
||||
out.Users = make([]UserDto, 0, len(t.Users))
|
||||
for _, u := range t.Users {
|
||||
out.Users = append(out.Users, MapUser(u))
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
200
server/internal/handlers/certs.go
Normal file
200
server/internal/handlers/certs.go
Normal file
@@ -0,0 +1,200 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/x509"
|
||||
"encoding/pem"
|
||||
"errors"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"reflect"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"gorm.io/gorm"
|
||||
|
||||
"smoop-api/internal/models"
|
||||
"smoop-api/internal/vault"
|
||||
)
|
||||
|
||||
type CertsHandler struct {
|
||||
db *gorm.DB
|
||||
pki *vault.PKIClient
|
||||
ttl string // e.g. "720h"
|
||||
}
|
||||
|
||||
func NewCertsHandler(db *gorm.DB, pki *vault.PKIClient, ttl string) *CertsHandler {
|
||||
return &CertsHandler{db: db, pki: pki, ttl: ttl}
|
||||
}
|
||||
|
||||
// ---- helpers ----------------------------------------------------------------
|
||||
|
||||
func readCSRFromRequest(c *gin.Context) (string, error) {
|
||||
// Accept: multipart/form with file "csr", or JSON {"csr":"PEM..."} or text/plain body
|
||||
// 1) multipart file
|
||||
if f, err := c.FormFile("csr"); err == nil && f != nil {
|
||||
ff, err := f.Open()
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
defer ff.Close()
|
||||
b, err := io.ReadAll(ff)
|
||||
return string(b), err
|
||||
}
|
||||
// 2) JSON
|
||||
var body struct {
|
||||
CSR string `json:"csr"`
|
||||
}
|
||||
if err := c.ShouldBindJSON(&body); err == nil && body.CSR != "" {
|
||||
return body.CSR, nil
|
||||
}
|
||||
// 3) raw text
|
||||
b, _ := io.ReadAll(c.Request.Body)
|
||||
if len(b) > 0 {
|
||||
return string(b), nil
|
||||
}
|
||||
return "", errors.New("csr required")
|
||||
}
|
||||
|
||||
func parseLeafPEM(pemStr string) (*x509.Certificate, error) {
|
||||
block, _ := pem.Decode([]byte(pemStr))
|
||||
if block == nil {
|
||||
return nil, errors.New("pem decode failed")
|
||||
}
|
||||
return x509.ParseCertificate(block.Bytes)
|
||||
}
|
||||
|
||||
func parseClientCertFromHeader(escaped string) (*x509.Certificate, error) {
|
||||
if escaped == "" {
|
||||
return nil, errors.New("empty client cert header")
|
||||
}
|
||||
raw, err := url.QueryUnescape(escaped)
|
||||
if err != nil {
|
||||
// Some Nginx builds already space-escape; still try raw
|
||||
raw = escaped
|
||||
}
|
||||
block, _ := pem.Decode([]byte(raw))
|
||||
if block == nil {
|
||||
return nil, errors.New("failed to decode PEM in client cert header")
|
||||
}
|
||||
return x509.ParseCertificate(block.Bytes)
|
||||
}
|
||||
|
||||
// ---- enroll (no mTLS, just device exists) -----------------------------------
|
||||
// POST /enroll/:guid
|
||||
func (h *CertsHandler) Enroll(c *gin.Context) {
|
||||
guid := c.Param("guid")
|
||||
// ensure device exists
|
||||
var dev models.Device
|
||||
if err := h.db.First(&dev, "guid = ?", guid).Error; err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
c.JSON(http.StatusNotFound, gin.H{"error": "device not found"})
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": "lookup failed"})
|
||||
return
|
||||
}
|
||||
|
||||
csr, err := readCSRFromRequest(c)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
// sign in Vault
|
||||
ctx, cancel := context.WithTimeout(c, 30*time.Second)
|
||||
defer cancel()
|
||||
sign, err := h.pki.SignCSR(ctx, csr, "urn:device:"+guid, h.ttl)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusBadGateway, gin.H{"error": "vault sign failed"})
|
||||
return
|
||||
}
|
||||
|
||||
// persist cert metadata
|
||||
leaf, err := parseLeafPEM(sign.Certificate)
|
||||
if err == nil {
|
||||
_ = h.db.Create(&models.DeviceCertificate{
|
||||
DeviceGUID: guid,
|
||||
SerialHex: strings.ToUpper(leaf.SerialNumber.Text(16)),
|
||||
IssuerCN: leaf.Issuer.CommonName,
|
||||
SubjectDN: leaf.Subject.String(),
|
||||
NotBefore: leaf.NotBefore,
|
||||
NotAfter: leaf.NotAfter,
|
||||
PemCert: sign.Certificate,
|
||||
}).Error
|
||||
}
|
||||
|
||||
// response bundle
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"certificate": sign.Certificate,
|
||||
"issuing_ca": sign.IssuingCA,
|
||||
"ca_chain": sign.CAChain,
|
||||
})
|
||||
}
|
||||
|
||||
// ---- renew (mTLS; cert must not be revoked; CSR pubkey must match current) --
|
||||
// POST /renew/:guid
|
||||
func (h *CertsHandler) Renew(c *gin.Context) {
|
||||
guidAny, _ := c.Get("mtlsDeviceGUID")
|
||||
serialAny, _ := c.Get("mtlsSerialHex")
|
||||
guid := guidAny.(string)
|
||||
currentSerial := serialAny.(string)
|
||||
|
||||
csr, err := readCSRFromRequest(c)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
// Check CSR pubkey == current client cert pubkey (strong binding)
|
||||
clientCert, err := parseClientCertFromHeader(c.GetHeader("X-SSL-Client-Cert"))
|
||||
if err != nil {
|
||||
c.JSON(http.StatusUnauthorized, gin.H{"error": "invalid client cert"})
|
||||
return
|
||||
}
|
||||
csrBlock, _ := pem.Decode([]byte(csr))
|
||||
if csrBlock == nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "csr decode failed"})
|
||||
return
|
||||
}
|
||||
parsedCSR, err := x509.ParseCertificateRequest(csrBlock.Bytes)
|
||||
if err != nil || parsedCSR.PublicKey == nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "csr parse failed"})
|
||||
return
|
||||
}
|
||||
if !reflect.DeepEqual(parsedCSR.PublicKey, clientCert.PublicKey) {
|
||||
c.JSON(http.StatusForbidden, gin.H{"error": "csr key does not match current certificate key"})
|
||||
return
|
||||
}
|
||||
|
||||
// sign
|
||||
ctx, cancel := context.WithTimeout(c, 30*time.Second)
|
||||
defer cancel()
|
||||
sign, err := h.pki.SignCSR(ctx, csr, "urn:device:"+guid, h.ttl)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusBadGateway, gin.H{"error": "vault sign failed"})
|
||||
return
|
||||
}
|
||||
|
||||
leaf, _ := parseLeafPEM(sign.Certificate)
|
||||
if leaf != nil {
|
||||
_ = h.db.Create(&models.DeviceCertificate{
|
||||
DeviceGUID: guid,
|
||||
SerialHex: strings.ToUpper(leaf.SerialNumber.Text(16)),
|
||||
IssuerCN: leaf.Issuer.CommonName,
|
||||
SubjectDN: leaf.Subject.String(),
|
||||
NotBefore: leaf.NotBefore,
|
||||
NotAfter: leaf.NotAfter,
|
||||
PemCert: sign.Certificate,
|
||||
}).Error
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"certificate": sign.Certificate,
|
||||
"issuing_ca": sign.IssuingCA,
|
||||
"ca_chain": sign.CAChain,
|
||||
"old_serial": currentSerial,
|
||||
})
|
||||
}
|
||||
51
server/internal/handlers/certs_admin.go
Normal file
51
server/internal/handlers/certs_admin.go
Normal file
@@ -0,0 +1,51 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"gorm.io/gorm"
|
||||
|
||||
"smoop-api/internal/models"
|
||||
"smoop-api/internal/vault"
|
||||
)
|
||||
|
||||
type CertsAdminHandler struct {
|
||||
db *gorm.DB
|
||||
pki *vault.PKIClient
|
||||
}
|
||||
|
||||
func NewCertsAdminHandler(db *gorm.DB, pki *vault.PKIClient) *CertsAdminHandler {
|
||||
return &CertsAdminHandler{db: db, pki: pki}
|
||||
}
|
||||
|
||||
type RevokeReq struct {
|
||||
Serial string `json:"serial" binding:"required"` // hex
|
||||
Reason string `json:"reason"`
|
||||
}
|
||||
|
||||
func (h *CertsAdminHandler) Revoke(c *gin.Context) {
|
||||
var req RevokeReq
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
serial := strings.ToUpper(strings.TrimSpace(req.Serial))
|
||||
if serial == "" {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "serial required"})
|
||||
return
|
||||
}
|
||||
|
||||
// store locally (instant kill)
|
||||
if err := h.db.Create(&models.RevokedSerial{SerialHex: serial, Reason: req.Reason}).Error; err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": "db save failed"})
|
||||
return
|
||||
}
|
||||
|
||||
// trigger CRL refresh in Vault (best-effort)
|
||||
_ = h.pki.RebuildCRL(context.Background())
|
||||
|
||||
c.JSON(http.StatusOK, gin.H{"revoked": serial})
|
||||
}
|
||||
@@ -289,3 +289,18 @@ func (h *DevicesHandler) fetchUsers(ids []uint) ([]models.User, error) {
|
||||
}
|
||||
return users, nil
|
||||
}
|
||||
|
||||
func (h *DevicesHandler) ListCertsByDevice(c *gin.Context) {
|
||||
guid := c.Param("guid")
|
||||
var d models.Device
|
||||
if err := h.db.Where("guid = ?", guid).First(&d).Error; err != nil {
|
||||
c.JSON(http.StatusNotFound, gin.H{"error": "device not found"})
|
||||
return
|
||||
}
|
||||
var list []models.DeviceCertificate
|
||||
if err := h.db.Where("device_guid = ?", guid).Order("id desc").Find(&list).Error; err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": "query failed"})
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"certs": list})
|
||||
}
|
||||
|
||||
256
server/internal/handlers/mediamtx.go
Normal file
256
server/internal/handlers/mediamtx.go
Normal file
@@ -0,0 +1,256 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"smoop-api/internal/config"
|
||||
"smoop-api/internal/crypto"
|
||||
"smoop-api/internal/dto"
|
||||
"smoop-api/internal/models"
|
||||
"strings"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
type MediaMTXHandler struct {
|
||||
jwtMgr *crypto.JWTManager
|
||||
db *gorm.DB
|
||||
cfg config.MediaMTXConfig
|
||||
}
|
||||
|
||||
func NewMediaMTXHandler(db *gorm.DB, jwt *crypto.JWTManager, c config.MediaMTXConfig) *MediaMTXHandler {
|
||||
return &MediaMTXHandler{db: db, jwtMgr: jwt, cfg: c}
|
||||
}
|
||||
|
||||
// --- 3.1 External auth endpoint called by MediaMTX
|
||||
// POST /mediamtx/auth
|
||||
func (h *MediaMTXHandler) Auth(c *gin.Context) {
|
||||
var req dto.MediaMTXAuthReq
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "bad auth body"})
|
||||
return
|
||||
}
|
||||
|
||||
// token can come from Authorization: Bearer or from query (?token=)
|
||||
tok := extractBearer(c.GetHeader("Authorization"))
|
||||
if tok == "" {
|
||||
tok = tokenFromQuery(req.Query)
|
||||
}
|
||||
if tok == "" {
|
||||
c.JSON(http.StatusUnauthorized, gin.H{"error": "missing token"})
|
||||
return
|
||||
}
|
||||
|
||||
// parse & validate media token
|
||||
// parsed, err := h.jwtMgr.Parse(tok)
|
||||
// if err != nil || !parsed.Valid {
|
||||
// c.JSON(http.StatusUnauthorized, gin.H{"error": "invalid token"})
|
||||
// return
|
||||
// }
|
||||
// var mc dto.MediaClaims
|
||||
// if err := jwt.MapClaims(parsed.Claims.(jwt.MapClaims)).Decode(&mc); err != nil {
|
||||
// c.JSON(http.StatusUnauthorized, gin.H{"error": "invalid claims"})
|
||||
// return
|
||||
// }
|
||||
|
||||
// // enforce act/path
|
||||
// if mc.Act != req.Action {
|
||||
// c.JSON(http.StatusForbidden, gin.H{"error": "action mismatch"})
|
||||
// return
|
||||
// }
|
||||
// if mc.Path != req.Path {
|
||||
// c.JSON(http.StatusForbidden, gin.H{"error": "path mismatch"})
|
||||
// return
|
||||
// }
|
||||
|
||||
// // Optional: permission checks by role/device
|
||||
// // READ: admins can read anything; users only devices assigned
|
||||
// // PUBLISH: allow devices (sub=0 or special) or admins
|
||||
// switch req.Action {
|
||||
// case "read":
|
||||
// if !h.canRead(mc.Subject, req.Path) {
|
||||
// c.JSON(http.StatusForbidden, gin.H{"error": "no read permission"})
|
||||
// return
|
||||
// }
|
||||
// case "publish":
|
||||
// if !h.canPublish(mc.Subject, req.Path) {
|
||||
// c.JSON(http.StatusForbidden, gin.H{"error": "no publish permission"})
|
||||
// return
|
||||
// }
|
||||
// }
|
||||
|
||||
// parse & validate media token
|
||||
mc, err := h.jwtMgr.ParseMedia(tok)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusUnauthorized, gin.H{"error": "invalid token"})
|
||||
return
|
||||
}
|
||||
|
||||
// enforce act/path
|
||||
if mc.Act != req.Action {
|
||||
c.JSON(http.StatusForbidden, gin.H{"error": "action mismatch"})
|
||||
return
|
||||
}
|
||||
if mc.Path != req.Path {
|
||||
c.JSON(http.StatusForbidden, gin.H{"error": "path mismatch"})
|
||||
return
|
||||
}
|
||||
|
||||
sub := mc.Subject // from RegisteredClaims.Subject
|
||||
switch req.Action {
|
||||
case "read":
|
||||
if !h.canRead(sub, req.Path) {
|
||||
c.JSON(http.StatusForbidden, gin.H{"error": "no read permission"})
|
||||
return
|
||||
}
|
||||
case "publish":
|
||||
if !h.canPublish(sub, req.Path) {
|
||||
c.JSON(http.StatusForbidden, gin.H{"error": "no publish permission"})
|
||||
return
|
||||
}
|
||||
}
|
||||
// allowed
|
||||
c.Status(http.StatusOK)
|
||||
}
|
||||
|
||||
func extractBearer(h string) string {
|
||||
if strings.HasPrefix(strings.ToLower(h), "bearer ") {
|
||||
return strings.TrimSpace(h[7:])
|
||||
}
|
||||
return ""
|
||||
}
|
||||
func tokenFromQuery(raw string) string {
|
||||
if raw == "" {
|
||||
return ""
|
||||
}
|
||||
q, _ := url.ParseQuery(raw)
|
||||
return q.Get("token")
|
||||
}
|
||||
|
||||
// naive helpers: replace with real queries to users/devices tables
|
||||
func (h *MediaMTXHandler) canRead(sub, path string) bool {
|
||||
// path is "live/<guid>"
|
||||
parts := strings.SplitN(path, "/", 2)
|
||||
if len(parts) != 2 {
|
||||
return false
|
||||
}
|
||||
guid := parts[1]
|
||||
|
||||
// Find the user; admins -> allow; else check user_devices join
|
||||
var u models.User
|
||||
if err := h.db.Where("id = ?", sub).First(&u).Error; err == nil && u.Role == models.RoleAdmin {
|
||||
return true
|
||||
}
|
||||
// check assignment
|
||||
var count int64
|
||||
_ = h.db.Table("user_devices").
|
||||
Where("user_id = ? AND device_guid = ?", sub, guid).
|
||||
Count(&count).Error
|
||||
return count > 0
|
||||
}
|
||||
func (h *MediaMTXHandler) canPublish(sub, path string) bool {
|
||||
// For devices you may use sub=0 or map to a device row; here: allow admins only
|
||||
var u models.User
|
||||
if err := h.db.Where("id = ?", sub).First(&u).Error; err == nil && u.Role == models.RoleAdmin {
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// --- 3.2 Mint publish token (device flow) -> returns WHIP URL
|
||||
// POST /mediamtx/token/publish {guid}
|
||||
func (h *MediaMTXHandler) MintPublish(c *gin.Context) {
|
||||
var req dto.PublishTokenReq
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "bad request"})
|
||||
return
|
||||
}
|
||||
path := "live/" + req.GUID
|
||||
tok, _ := h.jwtMgr.GenerateMediaToken(0, "publish", path, h.cfg.TokenTTL) // sub=0 (device)
|
||||
whip := fmt.Sprintf("%s/whip/%s?token=%s", strings.TrimRight(h.cfg.WebRTCBaseURL, "/"), path, url.QueryEscape(tok))
|
||||
c.JSON(http.StatusCreated, dto.PublishTokenResp{WHIP: whip})
|
||||
}
|
||||
|
||||
// --- 3.3 Mint read token (user flow) -> returns HLS + WHEP URLs
|
||||
// POST /mediamtx/token/read {guid}
|
||||
func (h *MediaMTXHandler) MintRead(c *gin.Context) {
|
||||
user, ok := GetUserContext(c)
|
||||
if !ok {
|
||||
c.JSON(http.StatusUnauthorized, gin.H{"error": "unauthorized"})
|
||||
return
|
||||
}
|
||||
var req dto.ReadTokenReq
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "bad request"})
|
||||
return
|
||||
}
|
||||
path := "live/" + req.GUID
|
||||
|
||||
// check permission before minting
|
||||
if user.Role != models.RoleAdmin {
|
||||
var count int64
|
||||
_ = h.db.Table("user_devices").
|
||||
Where("user_id = ? AND device_guid = ?", user.ID, req.GUID).
|
||||
Count(&count).Error
|
||||
if count == 0 {
|
||||
c.JSON(http.StatusForbidden, gin.H{"error": "not allowed for this device"})
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
tok, _ := h.jwtMgr.GenerateMediaToken(user.ID, "read", path, h.cfg.TokenTTL)
|
||||
|
||||
pub := strings.TrimRight(h.cfg.PublicBaseURL, "/")
|
||||
resp := dto.ReadTokenResp{
|
||||
HLS: fmt.Sprintf("%s/hls/%s/index.m3u8?token=%s", pub, path, url.QueryEscape(tok)),
|
||||
WHEP: fmt.Sprintf("%s/webrtc/play/%s?token=%s", pub, path, url.QueryEscape(tok)),
|
||||
}
|
||||
c.JSON(http.StatusCreated, resp)
|
||||
}
|
||||
|
||||
// --- 3.4 Admin "controls" using MediaMTX Control API (v3)
|
||||
type pathsListRes struct {
|
||||
Items []struct {
|
||||
Name string `json:"name"`
|
||||
} `json:"items"`
|
||||
}
|
||||
|
||||
func (h *MediaMTXHandler) ListPaths(c *gin.Context) {
|
||||
// GET {apiBase}/v3/paths/list
|
||||
resp, err := http.Get(strings.TrimRight(h.cfg.APIBase, "/") + "/v3/paths/list")
|
||||
if err != nil {
|
||||
c.JSON(http.StatusBadGateway, gin.H{"error": "mtx api unreachable"})
|
||||
return
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
if resp.StatusCode != 200 {
|
||||
c.JSON(resp.StatusCode, gin.H{"error": "mtx api error"})
|
||||
return
|
||||
}
|
||||
var pl pathsListRes
|
||||
if err := json.NewDecoder(resp.Body).Decode(&pl); err != nil {
|
||||
c.JSON(http.StatusBadGateway, gin.H{"error": "decode error"})
|
||||
return
|
||||
}
|
||||
c.JSON(200, pl)
|
||||
}
|
||||
|
||||
func (h *MediaMTXHandler) KickWebRTC(c *gin.Context) {
|
||||
// POST {apiBase}/v3/webrtcsessions/kick/{id}
|
||||
id := c.Param("id")
|
||||
reqURL := strings.TrimRight(h.cfg.APIBase, "/") + "/v3/webrtcsessions/kick/" + url.PathEscape(id)
|
||||
httpResp, err := http.Post(reqURL, "application/json", http.NoBody)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusBadGateway, gin.H{"error": "mtx api unreachable"})
|
||||
return
|
||||
}
|
||||
defer httpResp.Body.Close()
|
||||
if httpResp.StatusCode/100 != 2 {
|
||||
c.JSON(httpResp.StatusCode, gin.H{"error": "kick failed"})
|
||||
return
|
||||
}
|
||||
c.Status(http.StatusNoContent)
|
||||
}
|
||||
251
server/internal/handlers/tasks.go
Normal file
251
server/internal/handlers/tasks.go
Normal file
@@ -0,0 +1,251 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"gorm.io/gorm"
|
||||
|
||||
"smoop-api/internal/dto"
|
||||
"smoop-api/internal/models"
|
||||
)
|
||||
|
||||
type TasksHandler struct {
|
||||
db *gorm.DB
|
||||
}
|
||||
|
||||
func NewTasksHandler(db *gorm.DB) *TasksHandler { return &TasksHandler{db: db} }
|
||||
|
||||
// -----------------------------------------------------------------------------
|
||||
// 1) Device heartbeat + fetch next task
|
||||
// GET /tasks/:guid
|
||||
// Returns 204 (no task) OR next pending task (and marks it Running)
|
||||
// -----------------------------------------------------------------------------
|
||||
func (h *TasksHandler) DeviceNextTask(c *gin.Context) {
|
||||
guid := c.Param("guid")
|
||||
|
||||
// Optional: verify device exists to avoid orphan tasks
|
||||
var dev models.Device
|
||||
if err := h.db.First(&dev, "guid = ?", guid).Error; err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
c.JSON(http.StatusNotFound, gin.H{"error": "device not found"})
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": "lookup failed"})
|
||||
return
|
||||
}
|
||||
|
||||
var task models.DEviceTask
|
||||
now := time.Now()
|
||||
|
||||
// Atomically pick the oldest pending task for device and mark Running
|
||||
err := h.db.Transaction(func(tx *gorm.DB) error {
|
||||
// FOR UPDATE SKIP LOCKED emulation is not universal in GORM;
|
||||
// simplest: select oldest pending, then optimistic update.
|
||||
if err := tx.
|
||||
// NOTE: if using Postgres, you can append `Clauses(clause.Locking{Strength: "UPDATE SKIP LOCKED"})`
|
||||
// for better concurrency. Keeping generic here.
|
||||
Where("device_guid = ? AND status = ?", guid, models.TaskStatusPending).
|
||||
Order("created_at ASC").
|
||||
Take(&task).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
task.Status = models.TaskStatusRunning
|
||||
task.StartedAt = &now
|
||||
return tx.Save(&task).Error
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
// Heartbeat: no task right now
|
||||
c.Status(http.StatusNoContent)
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": "update failed"})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, dto.NextTaskResponseDto{
|
||||
HasTask: true,
|
||||
Task: ptr(dto.MapTask(task)),
|
||||
})
|
||||
}
|
||||
|
||||
// -----------------------------------------------------------------------------
|
||||
// 2) Device posts result
|
||||
// POST /tasks/:guid
|
||||
// -----------------------------------------------------------------------------
|
||||
func (h *TasksHandler) DevicePostResult(c *gin.Context) {
|
||||
guid := c.Param("guid")
|
||||
var req dto.TaskResultDto
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
var task models.DEviceTask
|
||||
if err := h.db.Where("id = ? AND device_guid = ?", req.TaskID, guid).First(&task).Error; err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
c.JSON(http.StatusNotFound, gin.H{"error": "task not found"})
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": "lookup failed"})
|
||||
return
|
||||
}
|
||||
|
||||
// Only Running tasks can be completed
|
||||
if task.Status != models.TaskStatusRunning {
|
||||
c.JSON(http.StatusConflict, gin.H{"error": "task not in running state"})
|
||||
return
|
||||
}
|
||||
|
||||
now := time.Now()
|
||||
if req.Success {
|
||||
task.Status = models.TaskStatusFinished
|
||||
task.Result = req.Result
|
||||
task.ErrorMsg = ""
|
||||
} else {
|
||||
task.Status = models.TaskStatusError
|
||||
task.Result = req.Result
|
||||
task.ErrorMsg = req.ErrorMsg
|
||||
}
|
||||
task.FinishedAt = &now
|
||||
|
||||
if err := h.db.Save(&task).Error; err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": "save failed"})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, dto.MapTask(task))
|
||||
}
|
||||
|
||||
// -----------------------------------------------------------------------------
|
||||
// 3) Create task for device (user/admin creates work item)
|
||||
// POST /device/:guid/task
|
||||
// -----------------------------------------------------------------------------
|
||||
func (h *TasksHandler) CreateTask(c *gin.Context) {
|
||||
guid := c.Param("guid")
|
||||
|
||||
// Permission check: device must be visible for user (DeviceAccessFilter already applied)
|
||||
if err := h.requireDeviceVisible(c, guid); err != nil {
|
||||
// err already wrote response
|
||||
return
|
||||
}
|
||||
|
||||
var req dto.CreateTaskDto
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
// Validate that device exists
|
||||
var d models.Device
|
||||
if err := h.db.Where("guid = ?", guid).First(&d).Error; err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
c.JSON(http.StatusNotFound, gin.H{"error": "device not found"})
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": "lookup failed"})
|
||||
return
|
||||
}
|
||||
|
||||
task := models.DEviceTask{
|
||||
DeviceGUID: guid,
|
||||
Type: req.Type,
|
||||
Payload: req.Payload, // raw JSON string
|
||||
Status: models.TaskStatusPending,
|
||||
}
|
||||
if err := h.db.Create(&task).Error; err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": "create failed"})
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusCreated, dto.MapTask(task))
|
||||
}
|
||||
|
||||
// -----------------------------------------------------------------------------
|
||||
// 4) List tasks for device (with status & pagination)
|
||||
// GET /device/:guid/tasks?offset=0&limit=50&status=pending|running|finished|error
|
||||
// -----------------------------------------------------------------------------
|
||||
func (h *TasksHandler) ListDeviceTasks(c *gin.Context) {
|
||||
guid := c.Param("guid")
|
||||
|
||||
// Permission check
|
||||
if err := h.requireDeviceVisible(c, guid); err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
offset := atoiDefault(c.DefaultQuery("offset", "0"), 0)
|
||||
limit := atoiDefault(c.DefaultQuery("limit", "50"), 50)
|
||||
if limit <= 0 || limit > 200 {
|
||||
limit = 50
|
||||
}
|
||||
filterStatus := c.Query("status") // optional
|
||||
|
||||
q := h.db.Model(&models.DEviceTask{}).Where("device_guid = ?", guid)
|
||||
if filterStatus != "" {
|
||||
q = q.Where("status = ?", filterStatus)
|
||||
}
|
||||
|
||||
var total int64
|
||||
if err := q.Count(&total).Error; err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": "count failed"})
|
||||
return
|
||||
}
|
||||
|
||||
var tasks []models.DEviceTask
|
||||
if err := q.Order("id DESC").Offset(offset).Limit(limit).Find(&tasks).Error; err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": "query failed"})
|
||||
return
|
||||
}
|
||||
|
||||
out := make([]dto.TaskDto, 0, len(tasks))
|
||||
for _, t := range tasks {
|
||||
out = append(out, dto.MapTask(t))
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"tasks": out,
|
||||
"offset": offset,
|
||||
"limit": limit,
|
||||
"total": total,
|
||||
})
|
||||
}
|
||||
|
||||
// --- helpers -----------------------------------------------------------------
|
||||
|
||||
func (h *TasksHandler) requireDeviceVisible(c *gin.Context, guid string) error {
|
||||
// Admins can always see it; regular users must be assigned
|
||||
uc, ok := GetUserContext(c)
|
||||
if !ok {
|
||||
c.JSON(http.StatusUnauthorized, gin.H{"error": "unauthorized"})
|
||||
return errors.New("unauthorized")
|
||||
}
|
||||
if uc.Role == models.RoleAdmin {
|
||||
return nil
|
||||
}
|
||||
// check assignment
|
||||
var cnt int64
|
||||
if err := h.db.Table("user_devices").
|
||||
Where("user_id = ? AND device_guid = ?", uc.ID, guid).
|
||||
Count(&cnt).Error; err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": "permission check failed"})
|
||||
return err
|
||||
}
|
||||
if cnt == 0 {
|
||||
c.JSON(http.StatusForbidden, gin.H{"error": "forbidden"})
|
||||
return errors.New("forbidden")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func atoiDefault(s string, def int) int {
|
||||
n, err := strconv.Atoi(s)
|
||||
if err != nil {
|
||||
return def
|
||||
}
|
||||
return n
|
||||
}
|
||||
|
||||
func ptr[T any](v T) *T { return &v }
|
||||
212
server/internal/handlers/trackers.go
Normal file
212
server/internal/handlers/trackers.go
Normal file
@@ -0,0 +1,212 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/http"
|
||||
"strconv"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"gorm.io/gorm"
|
||||
|
||||
"smoop-api/internal/dto"
|
||||
"smoop-api/internal/models"
|
||||
)
|
||||
|
||||
type TrackersHandler struct {
|
||||
db *gorm.DB
|
||||
}
|
||||
|
||||
func NewTrackersHandler(db *gorm.DB) *TrackersHandler { return &TrackersHandler{db: db} }
|
||||
|
||||
// GET /trackers — list trackers available for user (admin: all)
|
||||
func (h *TrackersHandler) List(c *gin.Context) {
|
||||
offset, _ := strconv.Atoi(c.DefaultQuery("offset", "0"))
|
||||
limit, _ := strconv.Atoi(c.DefaultQuery("limit", "50"))
|
||||
if limit <= 0 || limit > 200 {
|
||||
limit = 50
|
||||
}
|
||||
|
||||
// Default behavior (fallback if middleware not present): use user context
|
||||
isFilter := true
|
||||
var userID uint
|
||||
|
||||
if v, ok := c.Get("filterTrackers"); ok {
|
||||
if b, ok2 := v.(bool); ok2 {
|
||||
isFilter = b
|
||||
}
|
||||
}
|
||||
if v, ok := c.Get("userID"); ok {
|
||||
if id, ok2 := v.(uint); ok2 {
|
||||
userID = id
|
||||
}
|
||||
}
|
||||
|
||||
// Fallback to claims if middleware wasn’t applied
|
||||
if _, exists := c.Get("filterTrackers"); !exists {
|
||||
if uc, ok := GetUserContext(c); ok {
|
||||
if uc.Role == models.RoleAdmin {
|
||||
isFilter = false
|
||||
} else {
|
||||
isFilter = true
|
||||
userID = uc.ID
|
||||
}
|
||||
} else {
|
||||
c.JSON(http.StatusUnauthorized, gin.H{"error": "unauthorized"})
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
var (
|
||||
total int64
|
||||
list []models.Tracker
|
||||
err error
|
||||
)
|
||||
|
||||
if !isFilter {
|
||||
// Admin: all trackers
|
||||
err = h.db.Model(&models.Tracker{}).Count(&total).Error
|
||||
if err == nil {
|
||||
err = h.db.Preload("Users").Offset(offset).Limit(limit).Find(&list).Error
|
||||
}
|
||||
} else {
|
||||
// Filtered by userID
|
||||
q := h.db.Model(&models.Tracker{}).
|
||||
Joins("JOIN user_trackers ut ON ut.tracker_guid = trackers.guid").
|
||||
Where("ut.user_id = ?", userID)
|
||||
if err = q.Count(&total).Error; err == nil {
|
||||
err = h.db.Preload("Users").
|
||||
Joins("JOIN user_trackers ut ON ut.tracker_guid = trackers.guid").
|
||||
Where("ut.user_id = ?", userID).
|
||||
Offset(offset).Limit(limit).
|
||||
Find(&list).Error
|
||||
}
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": "query failed: " + err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
out := make([]dto.TrackerDto, 0, len(list))
|
||||
for _, t := range list {
|
||||
out = append(out, dto.MapTracker(t))
|
||||
}
|
||||
c.JSON(http.StatusOK, dto.TrackerListDto{
|
||||
Trackers: out, Offset: offset, Limit: limit, Total: total,
|
||||
})
|
||||
}
|
||||
|
||||
// POST /trackers/create — create tracker; optional initial user assignments
|
||||
func (h *TrackersHandler) Create(c *gin.Context) {
|
||||
var req dto.CreateTrackerDto
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
t := models.Tracker{GUID: req.GUID, Name: req.Name}
|
||||
if err := h.db.Create(&t).Error; err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "tracker exists?"})
|
||||
return
|
||||
}
|
||||
// optional users
|
||||
if len(req.UserIDs) > 0 {
|
||||
users, err := h.fetchUsers(req.UserIDs)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
if err := h.db.Model(&t).Association("Users").Append(&users); err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": "link failed"})
|
||||
return
|
||||
}
|
||||
}
|
||||
var withUsers models.Tracker
|
||||
if err := h.db.Preload("Users").Where("guid = ?", t.GUID).First(&withUsers).Error; err != nil {
|
||||
c.JSON(http.StatusCreated, dto.TrackerDto{GUID: t.GUID, Name: t.Name})
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusCreated, dto.MapTracker(withUsers))
|
||||
}
|
||||
|
||||
// POST /trackers/:guid/rename — rename tracker
|
||||
func (h *TrackersHandler) Rename(c *gin.Context) {
|
||||
guid := c.Param("guid")
|
||||
var t models.Tracker
|
||||
if err := h.db.Where("guid = ?", guid).First(&t).Error; err != nil {
|
||||
c.JSON(http.StatusNotFound, gin.H{"error": "tracker not found"})
|
||||
return
|
||||
}
|
||||
var req dto.RenameTrackerDto
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
t.Name = req.Name
|
||||
if err := h.db.Save(&t).Error; err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": "save failed"})
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusCreated, dto.TrackerDto{GUID: t.GUID, Name: t.Name})
|
||||
}
|
||||
|
||||
// POST /trackers/:guid/set_users — replace full user list (admin)
|
||||
func (h *TrackersHandler) SetUsers(c *gin.Context) {
|
||||
guid := c.Param("guid")
|
||||
var t models.Tracker
|
||||
if err := h.db.Where("guid = ?", guid).First(&t).Error; err != nil {
|
||||
c.JSON(http.StatusNotFound, gin.H{"error": "tracker not found"})
|
||||
return
|
||||
}
|
||||
var req dto.SetTrackerUsersDto
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
users := []models.User{}
|
||||
if len(req.UserIDs) > 0 {
|
||||
found, err := h.fetchUsers(req.UserIDs)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
users = found
|
||||
}
|
||||
if err := h.db.Model(&t).Association("Users").Clear(); err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": "clear failed"})
|
||||
return
|
||||
}
|
||||
if len(users) > 0 {
|
||||
if err := h.db.Model(&t).Association("Users").Append(&users); err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": "link failed"})
|
||||
return
|
||||
}
|
||||
}
|
||||
var withUsers models.Tracker
|
||||
_ = h.db.Preload("Users").Where("guid = ?", t.GUID).First(&withUsers).Error
|
||||
c.JSON(http.StatusCreated, dto.MapTracker(withUsers))
|
||||
}
|
||||
|
||||
// local helper (same as devices.go)
|
||||
func (h *TrackersHandler) fetchUsers(ids []uint) ([]models.User, error) {
|
||||
unique := make(map[uint]struct{}, len(ids))
|
||||
clean := make([]uint, 0, len(ids))
|
||||
for _, id := range ids {
|
||||
if id != 0 {
|
||||
if _, ok := unique[id]; !ok {
|
||||
unique[id] = struct{}{}
|
||||
clean = append(clean, id)
|
||||
}
|
||||
}
|
||||
}
|
||||
if len(clean) == 0 {
|
||||
return nil, nil
|
||||
}
|
||||
var users []models.User
|
||||
if err := h.db.Find(&users, clean).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if len(users) != len(clean) {
|
||||
return nil, fmt.Errorf("some users not found")
|
||||
}
|
||||
return users, nil
|
||||
}
|
||||
@@ -35,3 +35,32 @@ func DeviceAccessFilter() gin.HandlerFunc {
|
||||
c.Next()
|
||||
}
|
||||
}
|
||||
|
||||
// TrackerAccessFilter middleware sets filtering context for tracker access
|
||||
func TrackerAccessFilter() gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
userContext, exists := c.Get("user")
|
||||
if !exists {
|
||||
c.JSON(401, gin.H{"error": "unauthorized"})
|
||||
c.Abort()
|
||||
return
|
||||
}
|
||||
|
||||
user, ok := userContext.(handlers.UserContext)
|
||||
if !ok {
|
||||
c.JSON(401, gin.H{"error": "invalid user data"})
|
||||
c.Abort()
|
||||
return
|
||||
}
|
||||
|
||||
// Set filter flag and user ID in context (mirrors devices)
|
||||
if user.Role == models.RoleAdmin {
|
||||
c.Set("filterTrackers", false) // Admin sees all trackers
|
||||
} else {
|
||||
c.Set("filterTrackers", true) // Regular user needs filtering
|
||||
c.Set("userID", user.ID) // Store user ID for filtering (same key as devices)
|
||||
}
|
||||
|
||||
c.Next()
|
||||
}
|
||||
}
|
||||
|
||||
152
server/internal/middleware/mtls.go
Normal file
152
server/internal/middleware/mtls.go
Normal file
@@ -0,0 +1,152 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"crypto/x509"
|
||||
"encoding/hex"
|
||||
"encoding/pem"
|
||||
"errors"
|
||||
"net/url"
|
||||
"strings"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"gorm.io/gorm"
|
||||
|
||||
"smoop-api/internal/models"
|
||||
)
|
||||
|
||||
// Common helpers ---------------------------------------------------------------
|
||||
|
||||
func getHeader(c *gin.Context, k string) string {
|
||||
return strings.TrimSpace(c.GetHeader(k))
|
||||
}
|
||||
|
||||
func parseClientCertFromHeader(escaped string) (*x509.Certificate, error) {
|
||||
if escaped == "" {
|
||||
return nil, errors.New("empty client cert header")
|
||||
}
|
||||
raw, err := url.QueryUnescape(escaped)
|
||||
if err != nil {
|
||||
// Some Nginx builds already space-escape; still try raw
|
||||
raw = escaped
|
||||
}
|
||||
block, _ := pem.Decode([]byte(raw))
|
||||
if block == nil {
|
||||
return nil, errors.New("failed to decode PEM in client cert header")
|
||||
}
|
||||
return x509.ParseCertificate(block.Bytes)
|
||||
}
|
||||
|
||||
func extractGuidFromSAN(cert *x509.Certificate) (string, bool) {
|
||||
for _, u := range cert.URIs {
|
||||
if strings.EqualFold(u.Scheme, "urn") {
|
||||
// urn:device:<GUID> => u.Opaque == "device:<GUID>"
|
||||
parts := strings.SplitN(u.Opaque, ":", 2)
|
||||
if len(parts) == 2 && strings.EqualFold(parts[0], "device") {
|
||||
return parts[1], true
|
||||
}
|
||||
}
|
||||
}
|
||||
return "", false
|
||||
}
|
||||
|
||||
func normalizeSerialHex(b []byte) string {
|
||||
h := strings.ToUpper(hex.EncodeToString(b))
|
||||
// remove leading zeros normalization optional, keep as-is
|
||||
return h
|
||||
}
|
||||
|
||||
func isSerialRevoked(db *gorm.DB, serialHex string) (bool, error) {
|
||||
var cnt int64
|
||||
if err := db.Model(&models.RevokedSerial{}).Where("serial_hex = ?", serialHex).Count(&cnt).Error; err != nil {
|
||||
return false, err
|
||||
}
|
||||
return cnt > 0, nil
|
||||
}
|
||||
|
||||
// Guard for /tasks/:guid and /renew/:guid -------------------------------------
|
||||
// Requires Nginx to forward:
|
||||
//
|
||||
// X-SSL-Client-Verify, X-SSL-Client-Serial, X-SSL-Client-Cert
|
||||
func MTLSGuard(db *gorm.DB) gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
if getHeader(c, "X-SSL-Client-Verify") != "SUCCESS" {
|
||||
c.AbortWithStatus(401)
|
||||
return
|
||||
}
|
||||
|
||||
// Parse client cert (for GUID extraction) and serial
|
||||
cert, err := parseClientCertFromHeader(getHeader(c, "X-SSL-Client-Cert"))
|
||||
if err != nil {
|
||||
c.AbortWithStatusJSON(401, gin.H{"error": "invalid client cert"})
|
||||
return
|
||||
}
|
||||
pathGuid := strings.TrimSpace(c.Param("guid"))
|
||||
certGuid, ok := extractGuidFromSAN(cert)
|
||||
if !ok || certGuid == "" {
|
||||
c.AbortWithStatusJSON(403, gin.H{"error": "guid not present in SAN"})
|
||||
return
|
||||
}
|
||||
if pathGuid == "" || !strings.EqualFold(pathGuid, certGuid) {
|
||||
c.AbortWithStatusJSON(403, gin.H{"error": "guid mismatch"})
|
||||
return
|
||||
}
|
||||
|
||||
serialHex := normalizeSerialHex(cert.SerialNumber.Bytes())
|
||||
rev, err := isSerialRevoked(db, serialHex)
|
||||
if err != nil {
|
||||
c.AbortWithStatusJSON(500, gin.H{"error": "revocation check failed"})
|
||||
return
|
||||
}
|
||||
if rev {
|
||||
c.AbortWithStatus(403)
|
||||
return
|
||||
}
|
||||
|
||||
// Stash for downstream (device + serial)
|
||||
c.Set("mtlsDeviceGUID", certGuid)
|
||||
c.Set("mtlsSerialHex", serialHex)
|
||||
c.Next()
|
||||
}
|
||||
}
|
||||
|
||||
// Guard for /records/upload (guid comes as form field instead of path)
|
||||
func MTLSGuardUpload(db *gorm.DB) gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
if getHeader(c, "X-SSL-Client-Verify") != "SUCCESS" {
|
||||
c.AbortWithStatus(401)
|
||||
return
|
||||
}
|
||||
cert, err := parseClientCertFromHeader(getHeader(c, "X-SSL-Client-Cert"))
|
||||
if err != nil {
|
||||
c.AbortWithStatusJSON(401, gin.H{"error": "invalid client cert"})
|
||||
return
|
||||
}
|
||||
certGuid, ok := extractGuidFromSAN(cert)
|
||||
if !ok || certGuid == "" {
|
||||
c.AbortWithStatusJSON(403, gin.H{"error": "guid not present in SAN"})
|
||||
return
|
||||
}
|
||||
formGuid := strings.TrimSpace(c.PostForm("guid"))
|
||||
if formGuid == "" {
|
||||
// allow query fallback if you want
|
||||
formGuid = strings.TrimSpace(c.Query("guid"))
|
||||
}
|
||||
if !strings.EqualFold(formGuid, certGuid) {
|
||||
c.AbortWithStatusJSON(403, gin.H{"error": "guid mismatch"})
|
||||
return
|
||||
}
|
||||
serialHex := normalizeSerialHex(cert.SerialNumber.Bytes())
|
||||
rev, err := isSerialRevoked(db, serialHex)
|
||||
if err != nil {
|
||||
c.AbortWithStatusJSON(500, gin.H{"error": "revocation check failed"})
|
||||
return
|
||||
}
|
||||
if rev {
|
||||
c.AbortWithStatus(403)
|
||||
return
|
||||
}
|
||||
c.Set("mtlsDeviceGUID", certGuid)
|
||||
c.Set("mtlsSerialHex", serialHex)
|
||||
c.Next()
|
||||
}
|
||||
}
|
||||
24
server/internal/models/cert.go
Normal file
24
server/internal/models/cert.go
Normal file
@@ -0,0 +1,24 @@
|
||||
package models
|
||||
|
||||
import "time"
|
||||
|
||||
// Link a device GUID to issued client certificates.
|
||||
type DeviceCertificate struct {
|
||||
ID uint `gorm:"primaryKey"`
|
||||
DeviceGUID string `gorm:"index;not null"` // GUID
|
||||
SerialHex string `gorm:"uniqueIndex;size:128;not null"` // hex (upper or lower; normalize)
|
||||
IssuerCN string `gorm:"size:255"`
|
||||
SubjectDN string `gorm:"size:1024"`
|
||||
NotBefore time.Time
|
||||
NotAfter time.Time
|
||||
PemCert string `gorm:"type:text"` // PEM of leaf cert
|
||||
CreatedAt time.Time
|
||||
}
|
||||
|
||||
// “Instant kill” list checked by the mTLS guard before allowing access.
|
||||
type RevokedSerial struct {
|
||||
ID uint `gorm:"primaryKey"`
|
||||
SerialHex string `gorm:"uniqueIndex;size:128;not null"`
|
||||
Reason string `gorm:"size:1024"`
|
||||
CreatedAt time.Time
|
||||
}
|
||||
51
server/internal/models/task.go
Normal file
51
server/internal/models/task.go
Normal file
@@ -0,0 +1,51 @@
|
||||
package models
|
||||
|
||||
import "time"
|
||||
|
||||
type TaskStatus string
|
||||
type DeviceTaskType string
|
||||
|
||||
const (
|
||||
TaskStatusPending TaskStatus = "pending"
|
||||
TaskStatusRunning TaskStatus = "running"
|
||||
TaskStatusFinished TaskStatus = "finished"
|
||||
TaskStatusError TaskStatus = "error"
|
||||
)
|
||||
|
||||
const (
|
||||
// 1. start/stop audiostream
|
||||
TaskTypeStartStream DeviceTaskType = "start_stream"
|
||||
TaskTypeStopStream DeviceTaskType = "stop_stream"
|
||||
|
||||
// 2. start/stop recording
|
||||
TaskTypeStartRecording DeviceTaskType = "start_recording"
|
||||
TaskTypeStopRecording DeviceTaskType = "stop_recording"
|
||||
|
||||
// 3. change configuration (sleep timeout, jitter, recording duration)
|
||||
TaskTypeUpdateConfig DeviceTaskType = "update_config"
|
||||
|
||||
// 4. set deep sleep duration (minutes)
|
||||
TaskTypeSetDeepSleep DeviceTaskType = "set_deep_sleep"
|
||||
)
|
||||
|
||||
type DEviceTask struct {
|
||||
ID uint `gorm:"primaryKey"`
|
||||
DeviceGUID string `gorm:"index;not null"`
|
||||
Type DeviceTaskType `gorm:"type:varchar(64);not null"`
|
||||
// JSON payload from server to device (parameters)
|
||||
Payload string `gorm:"type:text;not null;default:'{}'"`
|
||||
Status TaskStatus `gorm:"type:varchar(16);not null;index"`
|
||||
// Optional error/reason from server or device
|
||||
ErrorMsg string `gorm:"type:text"`
|
||||
// Raw result JSON from device (success path)
|
||||
Result string `gorm:"type:text"`
|
||||
|
||||
// State timing
|
||||
CreatedAt time.Time
|
||||
UpdatedAt time.Time
|
||||
StartedAt *time.Time // when device fetched/acknowledged (Running)
|
||||
FinishedAt *time.Time // when device posted result (Finished/Error)
|
||||
|
||||
// Optional: small attempt/lease system if you ever need retries/timeouts
|
||||
// Attempts int `gorm:"not null;default:0"`
|
||||
}
|
||||
11
server/internal/models/tracker.go
Normal file
11
server/internal/models/tracker.go
Normal file
@@ -0,0 +1,11 @@
|
||||
package models
|
||||
|
||||
import "time"
|
||||
|
||||
type Tracker struct {
|
||||
GUID string `gorm:"primaryKey"`
|
||||
Name string `gorm:"size:255;not null"`
|
||||
Users []User `gorm:"many2many:user_trackers;constraint:OnDelete:CASCADE;"`
|
||||
CreatedAt time.Time
|
||||
UpdatedAt time.Time
|
||||
}
|
||||
@@ -10,11 +10,12 @@ const (
|
||||
)
|
||||
|
||||
type User struct {
|
||||
ID uint `gorm:"primaryKey"`
|
||||
Username string `gorm:"uniqueIndex;size:255;not null"`
|
||||
Password string `gorm:"not null"`
|
||||
Role Role `gorm:"type:varchar(16);not null;default:'user'"`
|
||||
Devices []Device `gorm:"many2many:user_devices;constraint:OnDelete:CASCADE;"`
|
||||
ID uint `gorm:"primaryKey"`
|
||||
Username string `gorm:"uniqueIndex;size:255;not null"`
|
||||
Password string `gorm:"not null"`
|
||||
Role Role `gorm:"type:varchar(16);not null;default:'user'"`
|
||||
Devices []Device `gorm:"many2many:user_devices;constraint:OnDelete:CASCADE;"`
|
||||
Trackers []Tracker `gorm:"many2many:user_trackers;constraint:OnDelete:CASCADE;"`
|
||||
CreatedAt time.Time
|
||||
UpdatedAt time.Time
|
||||
}
|
||||
|
||||
12
server/internal/models/user_tracker.go
Normal file
12
server/internal/models/user_tracker.go
Normal file
@@ -0,0 +1,12 @@
|
||||
package models
|
||||
|
||||
import "time"
|
||||
|
||||
type UserTracker struct {
|
||||
UserID uint `gorm:"primaryKey;index;not null"`
|
||||
TrackerGUID string `gorm:"primaryKey;size:64;index;not null"`
|
||||
CreatedAt time.Time
|
||||
|
||||
User User `gorm:"constraint:OnDelete:CASCADE;"`
|
||||
Tracker Tracker `gorm:"constraint:OnDelete:CASCADE;foreignKey:TrackerGUID;references:GUID"`
|
||||
}
|
||||
@@ -26,6 +26,15 @@ func Build(db *gorm.DB, minio *minio.Client, cfg *config.Config) *gin.Engine {
|
||||
recH := handlers.NewRecordsHandler(db, minio, cfg.MinIO.RecordsBucket, cfg.MinIO.PresignTTL)
|
||||
liveH := handlers.NewLivestreamHandler(minio, cfg.MinIO.LivestreamBucket)
|
||||
|
||||
// --- MediaMTX handler
|
||||
mediamtxH := handlers.NewMediaMTXHandler(db, jwtMgr, cfg.MediaMTX)
|
||||
|
||||
/// --- GPS tracker handler
|
||||
trackersH := handlers.NewTrackersHandler(db)
|
||||
|
||||
tasksH := handlers.NewTasksHandler(db)
|
||||
certsH := handlers.NewCertsHandler(db, &cfg.PkiIot, "720h")
|
||||
certsAdminH := handlers.NewCertsAdminHandler(db, &cfg.PkiIot)
|
||||
// --- Public auth
|
||||
r.POST("/auth/signup", authH.SignUp)
|
||||
r.POST("/auth/signin", authH.SignIn)
|
||||
@@ -44,13 +53,17 @@ func Build(db *gorm.DB, minio *minio.Client, cfg *config.Config) *gin.Engine {
|
||||
r.DELETE("/users/:id", authMW, adminOnly, usersH.Delete)
|
||||
|
||||
r.GET("/devices", authMW, middleware.DeviceAccessFilter(), devH.List)
|
||||
r.POST("/devices/create", authMW, devH.Create)
|
||||
r.POST("/devices/create", authMW, adminOnly, devH.Create)
|
||||
r.POST("/devices/:guid/rename", authMW, devH.Rename)
|
||||
r.POST("/devices/:guid/add_to_user", authMW, devH.AddToUser)
|
||||
r.POST("/devices/:guid/set_users", authMW, adminOnly, devH.SetUsers)
|
||||
r.POST("/devices/:guid/remove_from_user", authMW, devH.RemoveFromUser)
|
||||
r.POST("/device/:guid/task", authMW, middleware.DeviceAccessFilter(), tasksH.CreateTask)
|
||||
r.GET("/device/:guid/tasks", authMW, middleware.DeviceAccessFilter(), tasksH.ListDeviceTasks)
|
||||
r.GET("/device/:guid/certs", authMW, adminOnly, devH.ListCertsByDevice)
|
||||
r.POST("/certs/revoke", authMW, adminOnly, certsAdminH.Revoke)
|
||||
|
||||
r.POST("/records/upload", recH.Upload)
|
||||
r.POST("/records/upload", middleware.MTLSGuardUpload(db), recH.Upload)
|
||||
r.GET("/records", authMW, recH.List)
|
||||
r.GET("/records/:id/file", authMW, recH.File)
|
||||
|
||||
@@ -60,6 +73,27 @@ func Build(db *gorm.DB, minio *minio.Client, cfg *config.Config) *gin.Engine {
|
||||
// health
|
||||
r.GET("/healthz", func(c *gin.Context) { c.String(http.StatusOK, "ok") })
|
||||
|
||||
// --- NEW: MediaMTX integration routes
|
||||
// External auth (called by MediaMTX)
|
||||
r.POST("/mediamtx/auth", mediamtxH.Auth)
|
||||
// Token minting for device/user flows
|
||||
r.POST("/mediamtx/token/publish", mediamtxH.MintPublish)
|
||||
r.POST("/mediamtx/token/read", authMW, mediamtxH.MintRead)
|
||||
// Admin controls
|
||||
r.GET("/mediamtx/paths", authMW, adminOnly, mediamtxH.ListPaths)
|
||||
r.POST("/mediamtx/webrtc/kick/:id", authMW, adminOnly, mediamtxH.KickWebRTC)
|
||||
|
||||
r.GET("/trackers", authMW, middleware.TrackerAccessFilter(), trackersH.List)
|
||||
r.POST("/trackers/create", authMW, trackersH.Create)
|
||||
r.POST("/trackers/:guid/rename", authMW, trackersH.Rename)
|
||||
r.POST("/trackers/:guid/set_users", authMW, adminOnly, trackersH.SetUsers)
|
||||
|
||||
// --- Device Job/Task API
|
||||
r.GET("/tasks/:guid", middleware.MTLSGuard(db), tasksH.DeviceNextTask) // heartbeat + fetch next task
|
||||
r.POST("/tasks/:guid", middleware.MTLSGuard(db), tasksH.DevicePostResult) // device posts result
|
||||
|
||||
r.POST("/enroll/:guid", certsH.Enroll) // simple device-exists check is inside handler
|
||||
r.POST("/renew/:guid", middleware.MTLSGuard(db), certsH.Renew)
|
||||
// sensible defaults
|
||||
r.MaxMultipartMemory = 64 << 20 // 64 MiB
|
||||
_ = time.Now() // appease linters
|
||||
|
||||
86
server/internal/vault/pki.go
Normal file
86
server/internal/vault/pki.go
Normal file
@@ -0,0 +1,86 @@
|
||||
package vault
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
vault "github.com/hashicorp/vault-client-go"
|
||||
)
|
||||
|
||||
type PKIClient struct {
|
||||
client *vault.Client
|
||||
mount string // e.g. "pki_iot"
|
||||
role string // e.g. "device"
|
||||
}
|
||||
|
||||
type SignResponse struct {
|
||||
Certificate string `json:"certificate"`
|
||||
IssuingCA string `json:"issuing_ca"`
|
||||
CAChain []string `json:"ca_chain"`
|
||||
PrivateKey string `json:"private_key,omitempty"`
|
||||
PrivateKeyType string `json:"private_key_type,omitempty"`
|
||||
SerialNumber string `json:"serial_number"`
|
||||
}
|
||||
|
||||
func NewPKI(addr, token, mount, role string, timeout time.Duration) (*PKIClient, error) {
|
||||
client, err := vault.New(
|
||||
vault.WithAddress(addr),
|
||||
vault.WithRequestTimeout(timeout),
|
||||
)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("vault new: %w", err)
|
||||
}
|
||||
if err := client.SetToken(token); err != nil {
|
||||
return nil, fmt.Errorf("set token: %w", err)
|
||||
}
|
||||
return &PKIClient{client: client, mount: mount, role: role}, nil
|
||||
}
|
||||
|
||||
// SignCSR calls: /v1/<mount>/sign/<role>
|
||||
func (p *PKIClient) SignCSR(ctx context.Context, csrPEM, uriSAN string, ttl string) (*SignResponse, error) {
|
||||
if p.client == nil {
|
||||
return nil, fmt.Errorf("vault client is nil")
|
||||
}
|
||||
path := fmt.Sprintf("/%s/sign/%s", p.mount, p.role)
|
||||
req := map[string]any{
|
||||
"csr": csrPEM,
|
||||
"uri_sans": uriSAN, // e.g. "urn:device:<GUID>"
|
||||
}
|
||||
if ttl != "" {
|
||||
req["ttl"] = ttl // e.g. "720h"
|
||||
}
|
||||
|
||||
resp, err := p.client.Write(ctx, path, req)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if resp == nil || resp.Data == nil {
|
||||
return nil, fmt.Errorf("vault sign: empty response")
|
||||
}
|
||||
|
||||
// resp.Data contains the fields we need
|
||||
var out SignResponse
|
||||
if err := mapToStruct(resp.Data, &out); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &out, nil
|
||||
}
|
||||
|
||||
// RebuildCRL triggers CRL regeneration (rotate).
|
||||
// HCP: POST /v1/<mount>/crl/rotate or read /crl to force render; we’ll call rotate when available,
|
||||
// else read to ensure CRL is (re)generated.
|
||||
func (p *PKIClient) RebuildCRL(ctx context.Context) error {
|
||||
_, _ = p.client.Write(ctx, fmt.Sprintf("/%s/crl/rotate", p.mount), nil) // best effort
|
||||
_, err := p.client.Read(ctx, fmt.Sprintf("/%s/crl", p.mount))
|
||||
return err
|
||||
}
|
||||
|
||||
func mapToStruct(m map[string]any, out any) error {
|
||||
b, err := json.Marshal(m)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return json.Unmarshal(b, out)
|
||||
}
|
||||
Reference in New Issue
Block a user