Compare commits
30 Commits
master
...
d0da7962e2
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
d0da7962e2 | ||
|
|
1284c1c4c1 | ||
|
|
50850897c0 | ||
|
|
f8f099cccc | ||
|
|
50acf14fe1 | ||
|
|
2ba75d0e87 | ||
|
|
d0cece3001 | ||
|
|
e92194f739 | ||
|
|
ad0fe7b09a | ||
|
|
6d2719faeb | ||
|
|
89c44d2979 | ||
|
|
f59883315d | ||
|
|
af7c659bef | ||
|
|
40b7e590a3 | ||
|
|
bdb89f0966 | ||
|
|
2895c6afdd | ||
|
|
ee210e847e | ||
|
|
481966fcba | ||
|
|
7e2851e40a | ||
|
|
bd08dcc212 | ||
|
|
22469ac206 | ||
|
|
79dbd98ca6 | ||
|
|
a404a37a60 | ||
|
|
6a5ddd66ba | ||
|
|
35e59c4879 | ||
|
|
2b863776ae | ||
|
|
269b098f0d | ||
|
|
af252c4498 | ||
|
|
e0490e42c5 | ||
|
|
4c4d254852 |
72
certs/vault_install.sh
Normal file
72
certs/vault_install.sh
Normal file
@@ -0,0 +1,72 @@
|
||||
#!/usr/bin/env bash
|
||||
# -------------------------------------------------------
|
||||
# HashiCorp Vault Installation and Configuration Script
|
||||
# -------------------------------------------------------
|
||||
set -e
|
||||
# -------------------------------------------------------
|
||||
# 1. Install Vault
|
||||
# -------------------------------------------------------
|
||||
# yum install -y yum-utils
|
||||
# yum-config-manager --add-repo https://rpm.releases.hashicorp.com/RHEL/hashicorp.repo
|
||||
# yum -y install vault
|
||||
# echo "[+] Vault installed successfully."
|
||||
# -------------------------------------------------------
|
||||
# 2. Create directories and set permissions
|
||||
# -------------------------------------------------------
|
||||
useradd --system --home /opt/vault --shell /bin/false vault
|
||||
mkdir -p /opt/vault/data
|
||||
chown -R vault:vault /opt/vault
|
||||
mkdir -p /etc/vault
|
||||
chown -R vault:vault /etc/vault
|
||||
echo "[+] Directories and permissions set."
|
||||
# -------------------------------------------------------
|
||||
# 3. Create Vault configuration file
|
||||
# -------------------------------------------------------
|
||||
cat > /etc/vault/config.hcl <<'EOF'
|
||||
storage "file" {
|
||||
path = "/opt/vault/data"
|
||||
}
|
||||
|
||||
listener "tcp" {
|
||||
address = "127.0.0.1:8200"
|
||||
tls_disable = 1
|
||||
}
|
||||
|
||||
disable_mlock = true
|
||||
ui = true
|
||||
EOF
|
||||
|
||||
echo "[+] Vault configuration file created at /etc/vault/config.hcl."
|
||||
# -------------------------------------------------------
|
||||
# 4. Create systemd service file
|
||||
# -------------------------------------------------------
|
||||
cat > /etc/systemd/system/vault.service <<'EOF'
|
||||
[Unit]
|
||||
Description=HashiCorp Vault
|
||||
After=network-online.target
|
||||
Wants=network-online.target
|
||||
|
||||
[Service]
|
||||
User=vault
|
||||
Group=vault
|
||||
ExecStart=/usr/bin/vault server -config=/etc/vault/config.hcl
|
||||
Restart=on-failure
|
||||
LimitNOFILE=65536
|
||||
|
||||
[Install]
|
||||
WantedBy=multi-user.target
|
||||
EOF
|
||||
|
||||
echo "[+] Vault systemd service file created at /etc/systemd/system/vault.service."
|
||||
# -------------------------------------------------------
|
||||
# 5. Enable and start Vault service
|
||||
# -------------------------------------------------------
|
||||
restorecon -v /usr/bin/vault
|
||||
systemctl daemon-reload
|
||||
systemctl enable vault
|
||||
systemctl start vault
|
||||
echo "[+] Vault service started and enabled."
|
||||
# -------------------------------------------------------
|
||||
# 6. Final status
|
||||
# -------------------------------------------------------
|
||||
systemctl --no-pager status vault | grep "Active:" || echo "[+] Vault service may need manual check."
|
||||
@@ -36,31 +36,19 @@ 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
|
||||
args:
|
||||
APP_DIR: ${API_APP_DIR:-./cmd/api}
|
||||
environment:
|
||||
VAULT_ADDR: "http://vault:8200"
|
||||
VAULT_TOKEN: "root"
|
||||
VAULT_KV_PATH: "kv/data/snoop"
|
||||
VAULT_ADDR: "http://host.docker.internal:8200"
|
||||
VAULT_TOKEN: "hvs.rKzgIc5aaucOCtlJNsUdZuEH"
|
||||
# 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,77 @@ 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:
|
||||
build:
|
||||
context: ./mediamtx
|
||||
dockerfile: Dockerfile
|
||||
restart: unless-stopped
|
||||
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
|
||||
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"
|
||||
networks:
|
||||
- proxy
|
||||
- snoopBack
|
||||
|
||||
|
||||
# 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:
|
||||
|
||||
55
management-ui/package-lock.json
generated
55
management-ui/package-lock.json
generated
@@ -14,8 +14,11 @@
|
||||
"axios": "^1.11.0",
|
||||
"class-variance-authority": "^0.7.1",
|
||||
"clsx": "^2.1.1",
|
||||
"event-source-polyfill": "^1.0.31",
|
||||
"hls.js": "^1.6.13",
|
||||
"leaflet": "^1.9.4",
|
||||
"lucide-vue-next": "^0.525.0",
|
||||
"reka-ui": "^2.5.0",
|
||||
"reka-ui": "^2.6.1",
|
||||
"tailwind-merge": "^3.3.1",
|
||||
"tailwindcss": "^4.1.11",
|
||||
"tw-animate-css": "^1.3.6",
|
||||
@@ -28,6 +31,8 @@
|
||||
"devDependencies": {
|
||||
"@iconify-json/radix-icons": "^1.2.2",
|
||||
"@iconify/vue": "^5.0.0",
|
||||
"@types/event-source-polyfill": "^1.0.5",
|
||||
"@types/leaflet": "^1.9.20",
|
||||
"@types/node": "^24.1.0",
|
||||
"@vitejs/plugin-vue": "^6.0.0",
|
||||
"@vue/tsconfig": "^0.7.0",
|
||||
@@ -1273,6 +1278,30 @@
|
||||
"integrity": "sha512-dWHzHa2WqEXI/O1E9OjrocMTKJl2mSrEolh1Iomrv6U+JuNwaHXsXx9bLu5gG7BUWFIN0skIQJQ/L1rIex4X6w==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/@types/event-source-polyfill": {
|
||||
"version": "1.0.5",
|
||||
"resolved": "https://registry.npmjs.org/@types/event-source-polyfill/-/event-source-polyfill-1.0.5.tgz",
|
||||
"integrity": "sha512-iaiDuDI2aIFft7XkcwMzDWLqo7LVDixd2sR6B4wxJut9xcp/Ev9bO4EFg4rm6S9QxATLBj5OPxdeocgmhjwKaw==",
|
||||
"dev": true,
|
||||
"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",
|
||||
@@ -1810,6 +1839,12 @@
|
||||
"integrity": "sha512-Rfkk/Mp/DL7JVje3u18FxFujQlTNR2q6QfMSMB7AvCBx91NGj/ba3kCfza0f6dVDbw7YlRf/nDrn7pQrCCyQ/w==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/event-source-polyfill": {
|
||||
"version": "1.0.31",
|
||||
"resolved": "https://registry.npmjs.org/event-source-polyfill/-/event-source-polyfill-1.0.31.tgz",
|
||||
"integrity": "sha512-4IJSItgS/41IxN5UVAVuAyczwZF7ZIEsM1XAoUzIHA6A+xzusEZUutdXz2Nr+MQPLxfTiCvqE79/C8HT8fKFvA==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/fdir": {
|
||||
"version": "6.4.6",
|
||||
"resolved": "https://registry.npmjs.org/fdir/-/fdir-6.4.6.tgz",
|
||||
@@ -1987,6 +2022,12 @@
|
||||
"he": "bin/he"
|
||||
}
|
||||
},
|
||||
"node_modules/hls.js": {
|
||||
"version": "1.6.13",
|
||||
"resolved": "https://registry.npmjs.org/hls.js/-/hls.js-1.6.13.tgz",
|
||||
"integrity": "sha512-hNEzjZNHf5bFrUNvdS4/1RjIanuJ6szpWNfTaX5I6WfGynWXGT7K/YQLYtemSvFExzeMdgdE4SsyVLJbd5PcZA==",
|
||||
"license": "Apache-2.0"
|
||||
},
|
||||
"node_modules/jiti": {
|
||||
"version": "2.5.1",
|
||||
"resolved": "https://registry.npmjs.org/jiti/-/jiti-2.5.1.tgz",
|
||||
@@ -1996,6 +2037,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",
|
||||
@@ -2415,9 +2462,9 @@
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/reka-ui": {
|
||||
"version": "2.5.0",
|
||||
"resolved": "https://registry.npmjs.org/reka-ui/-/reka-ui-2.5.0.tgz",
|
||||
"integrity": "sha512-81aMAmJeVCy2k0E6x7n1kypDY6aM1ldLis5+zcdV1/JtoAlSDck5OBsyLRJU9CfgbrQp1ImnRnBSmC4fZ2fkZQ==",
|
||||
"version": "2.6.1",
|
||||
"resolved": "https://registry.npmjs.org/reka-ui/-/reka-ui-2.6.1.tgz",
|
||||
"integrity": "sha512-XK7cJDQoNuGXfCNzBBo/81Yg/OgjPwvbabnlzXG2VsdSgNsT6iIkuPBPr+C0Shs+3bb0x0lbPvgQAhMSCKm5Ww==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@floating-ui/dom": "^1.6.13",
|
||||
|
||||
@@ -15,8 +15,11 @@
|
||||
"axios": "^1.11.0",
|
||||
"class-variance-authority": "^0.7.1",
|
||||
"clsx": "^2.1.1",
|
||||
"event-source-polyfill": "^1.0.31",
|
||||
"hls.js": "^1.6.13",
|
||||
"leaflet": "^1.9.4",
|
||||
"lucide-vue-next": "^0.525.0",
|
||||
"reka-ui": "^2.5.0",
|
||||
"reka-ui": "^2.6.1",
|
||||
"tailwind-merge": "^3.3.1",
|
||||
"tailwindcss": "^4.1.11",
|
||||
"tw-animate-css": "^1.3.6",
|
||||
@@ -29,6 +32,8 @@
|
||||
"devDependencies": {
|
||||
"@iconify-json/radix-icons": "^1.2.2",
|
||||
"@iconify/vue": "^5.0.0",
|
||||
"@types/event-source-polyfill": "^1.0.5",
|
||||
"@types/leaflet": "^1.9.20",
|
||||
"@types/node": "^24.1.0",
|
||||
"@vitejs/plugin-vue": "^6.0.0",
|
||||
"@vue/tsconfig": "^0.7.0",
|
||||
|
||||
@@ -9,22 +9,24 @@ export const buttonVariants = cva(
|
||||
variants: {
|
||||
variant: {
|
||||
default:
|
||||
"bg-primary text-primary-foreground shadow-xs hover:bg-primary/90",
|
||||
"bg-primary text-primary-foreground hover:bg-primary/90",
|
||||
destructive:
|
||||
"bg-destructive text-white shadow-xs hover:bg-destructive/90 focus-visible:ring-destructive/20 dark:focus-visible:ring-destructive/40 dark:bg-destructive/60",
|
||||
"bg-destructive text-white hover:bg-destructive/90 focus-visible:ring-destructive/20 dark:focus-visible:ring-destructive/40 dark:bg-destructive/60",
|
||||
outline:
|
||||
"border bg-background shadow-xs hover:bg-accent hover:text-accent-foreground dark:bg-input/30 dark:border-input dark:hover:bg-input/50",
|
||||
secondary:
|
||||
"bg-secondary text-secondary-foreground shadow-xs hover:bg-secondary/80",
|
||||
"bg-secondary text-secondary-foreground hover:bg-secondary/80",
|
||||
ghost:
|
||||
"hover:bg-accent hover:text-accent-foreground dark:hover:bg-accent/50",
|
||||
link: "text-primary underline-offset-4 hover:underline",
|
||||
},
|
||||
size: {
|
||||
default: "h-9 px-4 py-2 has-[>svg]:px-3",
|
||||
sm: "h-8 rounded-md gap-1.5 px-3 has-[>svg]:px-2.5",
|
||||
lg: "h-10 rounded-md px-6 has-[>svg]:px-4",
|
||||
icon: "size-9",
|
||||
"default": "h-9 px-4 py-2 has-[>svg]:px-3",
|
||||
"sm": "h-8 rounded-md gap-1.5 px-3 has-[>svg]:px-2.5",
|
||||
"lg": "h-10 rounded-md px-6 has-[>svg]:px-4",
|
||||
"icon": "size-9",
|
||||
"icon-sm": "size-8",
|
||||
"icon-lg": "size-10",
|
||||
},
|
||||
},
|
||||
defaultVariants: {
|
||||
@@ -33,5 +35,4 @@ export const buttonVariants = cva(
|
||||
},
|
||||
},
|
||||
)
|
||||
|
||||
export type ButtonVariants = VariantProps<typeof buttonVariants>
|
||||
|
||||
26
management-ui/src/components/ui/pagination/Pagination.vue
Normal file
26
management-ui/src/components/ui/pagination/Pagination.vue
Normal file
@@ -0,0 +1,26 @@
|
||||
<script setup lang="ts">
|
||||
import type { PaginationRootEmits, PaginationRootProps } from "reka-ui"
|
||||
import type { HTMLAttributes } from "vue"
|
||||
import { reactiveOmit } from "@vueuse/core"
|
||||
import { PaginationRoot, useForwardPropsEmits } from "reka-ui"
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
const props = defineProps<PaginationRootProps & {
|
||||
class?: HTMLAttributes["class"]
|
||||
}>()
|
||||
const emits = defineEmits<PaginationRootEmits>()
|
||||
|
||||
const delegatedProps = reactiveOmit(props, "class")
|
||||
const forwarded = useForwardPropsEmits(delegatedProps, emits)
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<PaginationRoot
|
||||
v-slot="slotProps"
|
||||
data-slot="pagination"
|
||||
v-bind="forwarded"
|
||||
:class="cn('mx-auto flex w-full justify-center', props.class)"
|
||||
>
|
||||
<slot v-bind="slotProps" />
|
||||
</PaginationRoot>
|
||||
</template>
|
||||
@@ -0,0 +1,22 @@
|
||||
<script setup lang="ts">
|
||||
import type { PaginationListProps } from "reka-ui"
|
||||
import type { HTMLAttributes } from "vue"
|
||||
import { reactiveOmit } from "@vueuse/core"
|
||||
import { PaginationList } from "reka-ui"
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
const props = defineProps<PaginationListProps & { class?: HTMLAttributes["class"] }>()
|
||||
|
||||
const delegatedProps = reactiveOmit(props, "class")
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<PaginationList
|
||||
v-slot="slotProps"
|
||||
data-slot="pagination-content"
|
||||
v-bind="delegatedProps"
|
||||
:class="cn('flex flex-row items-center gap-1', props.class)"
|
||||
>
|
||||
<slot v-bind="slotProps" />
|
||||
</PaginationList>
|
||||
</template>
|
||||
@@ -0,0 +1,25 @@
|
||||
<script setup lang="ts">
|
||||
import type { PaginationEllipsisProps } from "reka-ui"
|
||||
import type { HTMLAttributes } from "vue"
|
||||
import { reactiveOmit } from "@vueuse/core"
|
||||
import { MoreHorizontal } from "lucide-vue-next"
|
||||
import { PaginationEllipsis } from "reka-ui"
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
const props = defineProps<PaginationEllipsisProps & { class?: HTMLAttributes["class"] }>()
|
||||
|
||||
const delegatedProps = reactiveOmit(props, "class")
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<PaginationEllipsis
|
||||
data-slot="pagination-ellipsis"
|
||||
v-bind="delegatedProps"
|
||||
:class="cn('flex size-9 items-center justify-center', props.class)"
|
||||
>
|
||||
<slot>
|
||||
<MoreHorizontal class="size-4" />
|
||||
<span class="sr-only">More pages</span>
|
||||
</slot>
|
||||
</PaginationEllipsis>
|
||||
</template>
|
||||
@@ -0,0 +1,33 @@
|
||||
<script setup lang="ts">
|
||||
import type { PaginationFirstProps } from "reka-ui"
|
||||
import type { HTMLAttributes } from "vue"
|
||||
import type { ButtonVariants } from '@/components/ui/button'
|
||||
import { reactiveOmit } from "@vueuse/core"
|
||||
import { ChevronLeftIcon } from "lucide-vue-next"
|
||||
import { PaginationFirst, useForwardProps } from "reka-ui"
|
||||
import { cn } from "@/lib/utils"
|
||||
import { buttonVariants } from '@/components/ui/button'
|
||||
|
||||
const props = withDefaults(defineProps<PaginationFirstProps & {
|
||||
size?: ButtonVariants["size"]
|
||||
class?: HTMLAttributes["class"]
|
||||
}>(), {
|
||||
size: "default",
|
||||
})
|
||||
|
||||
const delegatedProps = reactiveOmit(props, "class", "size")
|
||||
const forwarded = useForwardProps(delegatedProps)
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<PaginationFirst
|
||||
data-slot="pagination-first"
|
||||
:class="cn(buttonVariants({ variant: 'ghost', size }), 'gap-1 px-2.5 sm:pr-2.5', props.class)"
|
||||
v-bind="forwarded"
|
||||
>
|
||||
<slot>
|
||||
<ChevronLeftIcon />
|
||||
<span class="hidden sm:block">First</span>
|
||||
</slot>
|
||||
</PaginationFirst>
|
||||
</template>
|
||||
@@ -0,0 +1,34 @@
|
||||
<script setup lang="ts">
|
||||
import type { PaginationListItemProps } from "reka-ui"
|
||||
import type { HTMLAttributes } from "vue"
|
||||
import type { ButtonVariants } from '@/components/ui/button'
|
||||
import { reactiveOmit } from "@vueuse/core"
|
||||
import { PaginationListItem } from "reka-ui"
|
||||
import { cn } from "@/lib/utils"
|
||||
import { buttonVariants } from '@/components/ui/button'
|
||||
|
||||
const props = withDefaults(defineProps<PaginationListItemProps & {
|
||||
size?: ButtonVariants["size"]
|
||||
class?: HTMLAttributes["class"]
|
||||
isActive?: boolean
|
||||
}>(), {
|
||||
size: "icon",
|
||||
})
|
||||
|
||||
const delegatedProps = reactiveOmit(props, "class", "size", "isActive")
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<PaginationListItem
|
||||
data-slot="pagination-item"
|
||||
v-bind="delegatedProps"
|
||||
:class="cn(
|
||||
buttonVariants({
|
||||
variant: isActive ? 'outline' : 'ghost',
|
||||
size,
|
||||
}),
|
||||
props.class)"
|
||||
>
|
||||
<slot />
|
||||
</PaginationListItem>
|
||||
</template>
|
||||
@@ -0,0 +1,33 @@
|
||||
<script setup lang="ts">
|
||||
import type { PaginationLastProps } from "reka-ui"
|
||||
import type { HTMLAttributes } from "vue"
|
||||
import type { ButtonVariants } from '@/components/ui/button'
|
||||
import { reactiveOmit } from "@vueuse/core"
|
||||
import { ChevronRightIcon } from "lucide-vue-next"
|
||||
import { PaginationLast, useForwardProps } from "reka-ui"
|
||||
import { cn } from "@/lib/utils"
|
||||
import { buttonVariants } from '@/components/ui/button'
|
||||
|
||||
const props = withDefaults(defineProps<PaginationLastProps & {
|
||||
size?: ButtonVariants["size"]
|
||||
class?: HTMLAttributes["class"]
|
||||
}>(), {
|
||||
size: "default",
|
||||
})
|
||||
|
||||
const delegatedProps = reactiveOmit(props, "class", "size")
|
||||
const forwarded = useForwardProps(delegatedProps)
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<PaginationLast
|
||||
data-slot="pagination-last"
|
||||
:class="cn(buttonVariants({ variant: 'ghost', size }), 'gap-1 px-2.5 sm:pr-2.5', props.class)"
|
||||
v-bind="forwarded"
|
||||
>
|
||||
<slot>
|
||||
<span class="hidden sm:block">Last</span>
|
||||
<ChevronRightIcon />
|
||||
</slot>
|
||||
</PaginationLast>
|
||||
</template>
|
||||
@@ -0,0 +1,33 @@
|
||||
<script setup lang="ts">
|
||||
import type { PaginationNextProps } from "reka-ui"
|
||||
import type { HTMLAttributes } from "vue"
|
||||
import type { ButtonVariants } from '@/components/ui/button'
|
||||
import { reactiveOmit } from "@vueuse/core"
|
||||
import { ChevronRightIcon } from "lucide-vue-next"
|
||||
import { PaginationNext, useForwardProps } from "reka-ui"
|
||||
import { cn } from "@/lib/utils"
|
||||
import { buttonVariants } from '@/components/ui/button'
|
||||
|
||||
const props = withDefaults(defineProps<PaginationNextProps & {
|
||||
size?: ButtonVariants["size"]
|
||||
class?: HTMLAttributes["class"]
|
||||
}>(), {
|
||||
size: "default",
|
||||
})
|
||||
|
||||
const delegatedProps = reactiveOmit(props, "class", "size")
|
||||
const forwarded = useForwardProps(delegatedProps)
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<PaginationNext
|
||||
data-slot="pagination-next"
|
||||
:class="cn(buttonVariants({ variant: 'ghost', size }), 'gap-1 px-2.5 sm:pr-2.5', props.class)"
|
||||
v-bind="forwarded"
|
||||
>
|
||||
<slot>
|
||||
<span class="hidden sm:block">Next</span>
|
||||
<ChevronRightIcon />
|
||||
</slot>
|
||||
</PaginationNext>
|
||||
</template>
|
||||
@@ -0,0 +1,33 @@
|
||||
<script setup lang="ts">
|
||||
import type { PaginationPrevProps } from "reka-ui"
|
||||
import type { HTMLAttributes } from "vue"
|
||||
import type { ButtonVariants } from '@/components/ui/button'
|
||||
import { reactiveOmit } from "@vueuse/core"
|
||||
import { ChevronLeftIcon } from "lucide-vue-next"
|
||||
import { PaginationPrev, useForwardProps } from "reka-ui"
|
||||
import { cn } from "@/lib/utils"
|
||||
import { buttonVariants } from '@/components/ui/button'
|
||||
|
||||
const props = withDefaults(defineProps<PaginationPrevProps & {
|
||||
size?: ButtonVariants["size"]
|
||||
class?: HTMLAttributes["class"]
|
||||
}>(), {
|
||||
size: "default",
|
||||
})
|
||||
|
||||
const delegatedProps = reactiveOmit(props, "class", "size")
|
||||
const forwarded = useForwardProps(delegatedProps)
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<PaginationPrev
|
||||
data-slot="pagination-previous"
|
||||
:class="cn(buttonVariants({ variant: 'ghost', size }), 'gap-1 px-2.5 sm:pr-2.5', props.class)"
|
||||
v-bind="forwarded"
|
||||
>
|
||||
<slot>
|
||||
<ChevronLeftIcon />
|
||||
<span class="hidden sm:block">Previous</span>
|
||||
</slot>
|
||||
</PaginationPrev>
|
||||
</template>
|
||||
8
management-ui/src/components/ui/pagination/index.ts
Normal file
8
management-ui/src/components/ui/pagination/index.ts
Normal file
@@ -0,0 +1,8 @@
|
||||
export { default as Pagination } from "./Pagination.vue"
|
||||
export { default as PaginationContent } from "./PaginationContent.vue"
|
||||
export { default as PaginationEllipsis } from "./PaginationEllipsis.vue"
|
||||
export { default as PaginationFirst } from "./PaginationFirst.vue"
|
||||
export { default as PaginationItem } from "./PaginationItem.vue"
|
||||
export { default as PaginationLast } from "./PaginationLast.vue"
|
||||
export { default as PaginationNext } from "./PaginationNext.vue"
|
||||
export { default as PaginationPrevious } from "./PaginationPrevious.vue"
|
||||
@@ -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() {
|
||||
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/>
|
||||
<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,42 +1,85 @@
|
||||
<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
|
||||
(e: 'updated', payload: { id: string; username: string; role: 'admin' | 'user' }): void
|
||||
}>()
|
||||
|
||||
const isEditOpen = ref(false)
|
||||
const isDeleteOpen = ref(false)
|
||||
const deleting = ref(false)
|
||||
const updating = 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
|
||||
}
|
||||
}
|
||||
|
||||
function onEditConfirm() {
|
||||
isEditOpen.value = false
|
||||
async function onEditConfirm(payload: { username: string; password?: string; role: 'admin' | 'user' }) {
|
||||
try {
|
||||
updating.value = true
|
||||
|
||||
// Build UpdateUserDto payload
|
||||
const body: {
|
||||
username?: string
|
||||
password?: string
|
||||
role?: 'admin' | 'user'
|
||||
} = {}
|
||||
|
||||
// Only include fields that really changed / are provided
|
||||
if (payload.username && payload.username !== props.row.username) {
|
||||
body.username = payload.username
|
||||
}
|
||||
if (payload.password) {
|
||||
body.password = payload.password
|
||||
}
|
||||
if (payload.role && payload.role !== props.row.role) {
|
||||
body.role = payload.role
|
||||
}
|
||||
|
||||
// If nothing changed, skip request
|
||||
if (Object.keys(body).length === 0) {
|
||||
return
|
||||
}
|
||||
|
||||
await api.put(
|
||||
`/users/${encodeURIComponent(String(props.row.id))}`,
|
||||
body
|
||||
)
|
||||
|
||||
emit('updated', {
|
||||
id: String(props.row.id),
|
||||
username: payload.username || props.row.username,
|
||||
role: payload.role || (props.row.role as 'admin' | 'user'),
|
||||
})
|
||||
} catch (err) {
|
||||
console.error(err)
|
||||
emit('error', err)
|
||||
} finally {
|
||||
updating.value = false
|
||||
// dialog is already closed in EditUserDialog via v-model update
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
@@ -49,21 +92,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" :user="props.row" @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,41 @@ 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) ----------
|
||||
// ---- NEW: immediate UI updates for Users table ----
|
||||
function handleUserUpdated(
|
||||
row: Users,
|
||||
payload: { id: string; username: string; role: 'admin' | 'user' }
|
||||
) {
|
||||
const idNum = Number(payload.id || row.id)
|
||||
user_data.value = user_data.value.map(u =>
|
||||
u.id === idNum
|
||||
? { ...u, username: payload.username, role: payload.role }
|
||||
: u
|
||||
)
|
||||
}
|
||||
|
||||
function handleUserDeleted(row: Users) {
|
||||
const idNum = row.id
|
||||
user_data.value = user_data.value.filter(u => u.id !== idNum)
|
||||
}
|
||||
|
||||
// ---------------- 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 +79,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_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' },
|
||||
]
|
||||
|
||||
const device_data = ref<Device[]>([])
|
||||
const devicesLoading = ref(false)
|
||||
const devicesError = ref<string | null>(null)
|
||||
|
||||
let devicesCtrl: AbortController | null = null
|
||||
async function loadDevices() {
|
||||
devicesError.value = null
|
||||
@@ -100,10 +103,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 +117,133 @@ 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()
|
||||
treckerCtrl?.abort()
|
||||
})
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<a href="/create">
|
||||
<Button>
|
||||
Create
|
||||
</Button>
|
||||
<Button>Create</Button>
|
||||
</a>
|
||||
|
||||
<Tabs default-value="users">
|
||||
<TabsList class="space-x-8">
|
||||
<TabsTrigger value="users">
|
||||
Users
|
||||
</TabsTrigger>
|
||||
<TabsTrigger value="devices">
|
||||
Devices
|
||||
</TabsTrigger>
|
||||
<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" />
|
||||
<DataTableNoCheckbox
|
||||
:columns="user_columns"
|
||||
:data="user_data"
|
||||
:dropdownComponent="AdminUserDropdonw"
|
||||
@row-updated="handleUserUpdated"
|
||||
@row-deleted="handleUserDeleted"
|
||||
/>
|
||||
</TabsContent>
|
||||
|
||||
<TabsContent value="devices">
|
||||
<DataTableNoCheckbox :columns="device_columns" :data="device_data"
|
||||
:dropdownComponent="AdminDeviceDropdown" />
|
||||
<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,21 @@ 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() })
|
||||
|
||||
</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>
|
||||
@@ -102,23 +91,19 @@ function onSelect(ev: CustomEvent) {
|
||||
<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"
|
||||
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 +114,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
|
||||
: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>
|
||||
|
||||
110
management-ui/src/customcompometns/DataTableNoCheckboxScroll.vue
Normal file
110
management-ui/src/customcompometns/DataTableNoCheckboxScroll.vue
Normal file
@@ -0,0 +1,110 @@
|
||||
<script setup lang="ts" generic="TData, TValue">
|
||||
import { defineProps } from 'vue'
|
||||
import type { DefineComponent } from 'vue'
|
||||
import type { ColumnDef } from '@tanstack/vue-table'
|
||||
import {
|
||||
useVueTable,
|
||||
getCoreRowModel,
|
||||
FlexRender,
|
||||
} from '@tanstack/vue-table'
|
||||
|
||||
import {
|
||||
Table, TableHeader, TableRow, TableHead, TableBody, TableCell,
|
||||
} from '@/components/ui/table'
|
||||
import { ScrollArea, ScrollBar } from '@/components/ui/scroll-area' // <-- add ScrollBar
|
||||
|
||||
const props = defineProps<{
|
||||
columns: ColumnDef<TData, TValue>[]
|
||||
data: TData[]
|
||||
dropdownComponent?: DefineComponent<{ row: TData }, any, any>
|
||||
dropdownProps?: Record<string, any>
|
||||
/** Optional tailwind class to control min table width for horizontal scrolling */
|
||||
minTableWidth?: string
|
||||
}>()
|
||||
|
||||
const table = useVueTable({
|
||||
get data() { return props.data },
|
||||
get columns() { return props.columns },
|
||||
getCoreRowModel: getCoreRowModel(),
|
||||
})
|
||||
|
||||
const emit = defineEmits<{
|
||||
(e: 'row-updated', row: TData, payload: any): void
|
||||
(e: 'row-deleted', row: TData): void
|
||||
}>()
|
||||
|
||||
const minWidthClass = props.minTableWidth ?? 'min-w-[1100px]' // tweak as needed
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<!-- Parent must not rely on h-full; use overflow-hidden to contain scrollbars -->
|
||||
<div class="w-full max-h-full border rounded-md flex flex-col overflow-hidden">
|
||||
<!-- This element grows and can scroll internally -->
|
||||
<ScrollArea class="flex-1 min-h-0 w-full">
|
||||
<!-- min-width keeps horizontal scroll available when needed -->
|
||||
<div :class="['w-full', minWidthClass]">
|
||||
<!-- separate borders help sticky headers render above rows -->
|
||||
<Table class="w-full border-separate border-spacing-0">
|
||||
<TableHeader>
|
||||
<TableRow v-for="headerGroup in table.getHeaderGroups()" :key="headerGroup.id">
|
||||
<TableHead
|
||||
v-for="header in headerGroup.headers"
|
||||
:key="header.id"
|
||||
class="sticky top-0 bg-background z-10 whitespace-nowrap"
|
||||
>
|
||||
<FlexRender
|
||||
v-if="!header.isPlaceholder"
|
||||
:render="header.column.columnDef.header"
|
||||
:props="header.getContext()"
|
||||
/>
|
||||
</TableHead>
|
||||
<TableHead
|
||||
v-if="props.dropdownComponent"
|
||||
class="sticky top-0 bg-background z-10 w-12"
|
||||
/>
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
|
||||
<TableBody>
|
||||
<template v-if="table.getRowModel().rows.length">
|
||||
<TableRow
|
||||
v-for="row in table.getRowModel().rows"
|
||||
:key="row.id"
|
||||
class="whitespace-nowrap"
|
||||
>
|
||||
<TableCell v-for="cell in row.getVisibleCells()" :key="cell.id">
|
||||
<FlexRender :render="cell.column.columnDef.cell" :props="cell.getContext()" />
|
||||
</TableCell>
|
||||
|
||||
<TableCell v-if="props.dropdownComponent" class="text-right">
|
||||
<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>
|
||||
</template>
|
||||
|
||||
<template v-else>
|
||||
<TableRow>
|
||||
<TableCell
|
||||
:colspan="props.columns.length + (props.dropdownComponent ? 1 : 0)"
|
||||
class="h-24 text-center"
|
||||
>
|
||||
No data.
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
</template>
|
||||
</TableBody>
|
||||
</Table>
|
||||
</div>
|
||||
|
||||
<!-- Always show both scrollbars when needed -->
|
||||
<ScrollBar orientation="horizontal" />
|
||||
<ScrollBar orientation="vertical" />
|
||||
</ScrollArea>
|
||||
</div>
|
||||
</template>
|
||||
@@ -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>
|
||||
|
||||
134
management-ui/src/customcompometns/DeviceCertificateDialog.vue
Normal file
134
management-ui/src/customcompometns/DeviceCertificateDialog.vue
Normal file
@@ -0,0 +1,134 @@
|
||||
<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'
|
||||
import { ref, watch, computed } from 'vue'
|
||||
import { api } from '@/lib/api'
|
||||
import DataTableNoCheckboxScroll from './DataTableNoCheckboxScroll.vue'
|
||||
import type { ColumnDef } from '@tanstack/vue-table'
|
||||
|
||||
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
|
||||
}>()
|
||||
|
||||
// --- DTOs from backend ---
|
||||
type DeviceCertDto = {
|
||||
id: number
|
||||
deviceGuid: string
|
||||
serialHex: string
|
||||
issuerCN: string
|
||||
subjectDN: string
|
||||
notBefore: string // ISO timestamps as strings when serialized
|
||||
notAfter: string
|
||||
createdAt: string
|
||||
}
|
||||
type DeviceCertListDto = { certs: DeviceCertDto[] }
|
||||
|
||||
// --- local state ---
|
||||
const loading = ref(false)
|
||||
const error = ref<string | null>(null)
|
||||
const certs = ref<DeviceCertDto[]>([])
|
||||
|
||||
const guid = computed(() => props.device?.guid ?? '')
|
||||
|
||||
function fmt(ts?: string | null) {
|
||||
if (!ts) return ''
|
||||
try { return new Date(ts).toLocaleString() } catch { return ts ?? '' }
|
||||
}
|
||||
|
||||
const columns: ColumnDef<DeviceCertDto, any>[] = [
|
||||
{ accessorKey: 'id', header: 'ID' },
|
||||
{ accessorKey: 'serialHex', header: 'Serial (hex)' },
|
||||
{ accessorKey: 'issuerCN', header: 'Issuer CN' },
|
||||
{ accessorKey: 'subjectDN', header: 'Subject DN' },
|
||||
{ accessorKey: 'notBefore', header: 'Not Before', cell: ({ row }) => fmt(row.original.notBefore) },
|
||||
{ accessorKey: 'notAfter', header: 'Not After', cell: ({ row }) => fmt(row.original.notAfter) },
|
||||
{ accessorKey: 'createdAt', header: 'Created', cell: ({ row }) => fmt(row.original.createdAt) },
|
||||
]
|
||||
|
||||
async function loadCerts() {
|
||||
if (!guid.value) return
|
||||
loading.value = true
|
||||
error.value = null
|
||||
try {
|
||||
const { data } = await api.get<DeviceCertListDto>(`/device/${encodeURIComponent(guid.value)}/certs`)
|
||||
certs.value = Array.isArray(data?.certs) ? data.certs : []
|
||||
} catch (e: any) {
|
||||
console.error(e)
|
||||
error.value = e?.response?.data?.message ?? e?.message ?? 'Failed to load certificates.'
|
||||
certs.value = []
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
// open → fetch
|
||||
watch(() => props.modelValue, (open) => {
|
||||
if (open) loadCerts()
|
||||
})
|
||||
|
||||
// guid changes while open → refetch
|
||||
watch(guid, (g, prev) => {
|
||||
if (props.modelValue && g && g !== prev) loadCerts()
|
||||
})
|
||||
|
||||
function close() {
|
||||
emit('update:modelValue', false)
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<Dialog :open="props.modelValue" @update:open="(v: boolean) => emit('update:modelValue', v)">
|
||||
<DialogContent class="sm:min-w-[1000px]">
|
||||
<DialogHeader>
|
||||
<div class="flex items-center justify-between">
|
||||
<div>
|
||||
<DialogTitle>Device certificates</DialogTitle>
|
||||
<DialogDescription class="mt-1 break-all">
|
||||
GUID: {{ guid || '—' }}
|
||||
</DialogDescription>
|
||||
</div>
|
||||
|
||||
<div class="flex gap-2 pt-8">
|
||||
<Button variant="outline" :disabled="loading || !guid" @click="loadCerts">
|
||||
{{ loading ? 'Loading…' : 'Refresh' }}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</DialogHeader>
|
||||
|
||||
<div v-if="error" class="text-sm text-red-600 mb-3">{{ error }}</div>
|
||||
|
||||
<div v-if="loading" class="text-sm text-muted-foreground py-6 text-center">
|
||||
Loading certificates…
|
||||
</div>
|
||||
|
||||
<div v-else>
|
||||
<div class="flex-1 min-h-0 pb-2">
|
||||
<DataTableNoCheckboxScroll
|
||||
:columns="columns"
|
||||
:data="certs"
|
||||
minTableWidth="min-w-[900px]" />
|
||||
</div>
|
||||
|
||||
</div>
|
||||
|
||||
<DialogFooter>
|
||||
<Button @click="close">Close</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</template>
|
||||
@@ -1,41 +1,285 @@
|
||||
<script setup lang="ts">
|
||||
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
|
||||
import DeviceDashboard from './DeviceDashboard.vue';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import DeviceRecordings from './DeviceRecordings.vue';
|
||||
import { type PropType } from 'vue';
|
||||
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs'
|
||||
import DeviceDashboard from './DeviceDashboard.vue'
|
||||
import DeviceRecordings from './DeviceRecordings.vue'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { ref, onBeforeUnmount, type PropType } from 'vue'
|
||||
import type { Task } from '@/lib/interfaces'
|
||||
import { api } from '@/lib/api'
|
||||
import { EventSourcePolyfill } from 'event-source-polyfill'
|
||||
|
||||
// hls.js for non-Safari browsers
|
||||
import Hls from 'hls.js'
|
||||
import { auth } from '@/lib/auth'
|
||||
|
||||
type PublishTokenResp = { hlsUrl: string } | { HLS: string }
|
||||
|
||||
const props = defineProps({
|
||||
guid: { type: String as PropType<string>, required: true },
|
||||
})
|
||||
|
||||
/** UI state **/
|
||||
const sending = ref(false)
|
||||
const streamError = ref<string | null>(null)
|
||||
const waitingLive = ref(false)
|
||||
const hlsUrl = ref<string | null>(null)
|
||||
const playing = ref(false)
|
||||
|
||||
/** Player bits **/
|
||||
const audioEl = ref<HTMLAudioElement | null>(null)
|
||||
const hls = ref<any | null>(null)
|
||||
|
||||
/** SSE (wait-for-live) **/
|
||||
const es = ref<EventSource | null>(null)
|
||||
|
||||
/** Helpers **/
|
||||
function closeEventSource() {
|
||||
try { es.value?.close() } catch { }
|
||||
es.value = null
|
||||
waitingLive.value = false
|
||||
}
|
||||
|
||||
function teardownHls() {
|
||||
try {
|
||||
if (hls.value) {
|
||||
try { hls.value.stopLoad?.() } catch { }
|
||||
try { hls.value.detachMedia?.() } catch { }
|
||||
try { hls.value.destroy?.() } catch { }
|
||||
}
|
||||
} catch { }
|
||||
hls.value = null
|
||||
|
||||
if (audioEl.value) {
|
||||
audioEl.value.pause?.()
|
||||
audioEl.value.removeAttribute('src')
|
||||
try { audioEl.value.load?.() } catch { }
|
||||
}
|
||||
playing.value = false
|
||||
hlsUrl.value = null
|
||||
}
|
||||
|
||||
/** Get fresh read token → HLS URL **/
|
||||
async function fetchHlsUrl(): Promise<string> {
|
||||
const body = { guid: props.guid }
|
||||
const { data } = await api.post<PublishTokenResp>('/mediamtx/token/read', body)
|
||||
const url = (data as any).HLS ?? (data as any).hlsUrl
|
||||
if (!url || typeof url !== 'string') throw new Error('No HLS url in token response')
|
||||
return url
|
||||
}
|
||||
|
||||
/** Attach player and play **/
|
||||
async function attachAndPlay(url: string) {
|
||||
streamError.value = null
|
||||
hlsUrl.value = url
|
||||
teardownHls()
|
||||
|
||||
const el = audioEl.value
|
||||
if (!el) {
|
||||
streamError.value = 'Audio element is not available.'
|
||||
return
|
||||
}
|
||||
|
||||
el.controls = true
|
||||
el.autoplay = true
|
||||
|
||||
// Non-Safari: hls.js
|
||||
if (Hls && typeof (Hls as any).isSupported === 'function' && Hls.isSupported()) {
|
||||
const instance = new (Hls as any)({
|
||||
enableWorker: true,
|
||||
lowLatencyMode: true,
|
||||
backBufferLength: 60,
|
||||
})
|
||||
hls.value = instance
|
||||
|
||||
instance.on(Hls.Events.ERROR, (_evt: any, data: any) => {
|
||||
if (data?.fatal) {
|
||||
streamError.value = `HLS fatal error: ${data?.details || 'unknown'}`
|
||||
teardownHls()
|
||||
}
|
||||
})
|
||||
|
||||
instance.loadSource(url)
|
||||
instance.attachMedia(el)
|
||||
instance.on(Hls.Events.MANIFEST_PARSED, async () => {
|
||||
try {
|
||||
await el.play()
|
||||
playing.value = true
|
||||
} catch (err: any) {
|
||||
streamError.value = err?.message ?? 'Autoplay was blocked'
|
||||
playing.value = false
|
||||
}
|
||||
})
|
||||
} else {
|
||||
// Safari / iOS (native HLS)
|
||||
if (el.canPlayType('application/vnd.apple.mpegurl')) {
|
||||
el.src = url
|
||||
try {
|
||||
await el.play()
|
||||
playing.value = true
|
||||
} catch (err: any) {
|
||||
streamError.value = err?.message ?? 'Autoplay was blocked'
|
||||
playing.value = false
|
||||
}
|
||||
} else {
|
||||
streamError.value = 'HLS is not supported in this browser.'
|
||||
playing.value = false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Start streaming:
|
||||
* 1) tell device to start_stream
|
||||
* 2) wait via SSE for “live”
|
||||
* 3) on live → fetch token → play
|
||||
*/
|
||||
async function startStreaming() {
|
||||
streamError.value = null
|
||||
sending.value = true
|
||||
closeEventSource()
|
||||
|
||||
try {
|
||||
// 1) ask device to start
|
||||
const dto: Task = { type: 'start_stream', payload: '' }
|
||||
await api.post(`/device/${encodeURIComponent(props.guid)}/task`, dto)
|
||||
|
||||
// 2) strictly wait for SSE “live”
|
||||
await waitForLiveThenPlay()
|
||||
} catch (e: any) {
|
||||
console.error('Start streaming error', e)
|
||||
streamError.value = e?.response?.data?.message || e?.message || 'Failed to start streaming'
|
||||
playing.value = false
|
||||
} finally {
|
||||
sending.value = false
|
||||
}
|
||||
}
|
||||
|
||||
/** Wait for server-sent event “live” from /mediamtx/:guid/wait, then fetch token and play **/
|
||||
function waitForLiveThenPlay(): Promise<void> {
|
||||
waitingLive.value = true
|
||||
return new Promise<void>((resolve, reject) => {
|
||||
try {
|
||||
const url = `/api/mediamtx/${encodeURIComponent(props.guid)}/wait`
|
||||
const source = new EventSourcePolyfill(url,
|
||||
{
|
||||
headers: { Authorization: `Bearer ${auth.token.value}` },
|
||||
// NOTE: in browsers there's no way to bypass TLS validation here.
|
||||
}
|
||||
)
|
||||
es.value = source
|
||||
|
||||
const cleanup = () => {
|
||||
source.removeEventListener('live', onLive)
|
||||
source.removeEventListener('timeout', onTimeout)
|
||||
source.onerror = null
|
||||
try { source.close() } catch { }
|
||||
es.value = null
|
||||
waitingLive.value = false
|
||||
}
|
||||
|
||||
const onLive = async () => {
|
||||
try {
|
||||
cleanup()
|
||||
const tokenUrl = await fetchHlsUrl()
|
||||
await attachAndPlay(tokenUrl)
|
||||
resolve()
|
||||
} catch (err) {
|
||||
reject(err)
|
||||
}
|
||||
}
|
||||
|
||||
const onTimeout = () => {
|
||||
cleanup()
|
||||
streamError.value = 'Stream did not become live in time. Try again.'
|
||||
reject(new Error('SSE wait timeout'))
|
||||
}
|
||||
|
||||
source.addEventListener('live', onLive)
|
||||
source.addEventListener('timeout', onTimeout)
|
||||
|
||||
source.onerror = () => {
|
||||
cleanup()
|
||||
streamError.value = 'Live-wait connection ended. Try again.'
|
||||
reject(new Error('SSE error'))
|
||||
}
|
||||
} catch (err) {
|
||||
waitingLive.value = false
|
||||
reject(err)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/** Stop streaming:
|
||||
* 1) tell device to stop_stream
|
||||
* 2) teardown player & close SSE
|
||||
*/
|
||||
async function stopStreaming() {
|
||||
streamError.value = null
|
||||
sending.value = true
|
||||
try {
|
||||
const dto: Task = { type: 'stop_stream', payload: '' }
|
||||
await api.post(`/device/${encodeURIComponent(props.guid)}/task`, dto)
|
||||
} catch (e: any) {
|
||||
console.error('Stop streaming error', e)
|
||||
} finally {
|
||||
sending.value = false
|
||||
closeEventSource()
|
||||
teardownHls()
|
||||
}
|
||||
}
|
||||
|
||||
// Cleanup
|
||||
onBeforeUnmount(() => {
|
||||
closeEventSource()
|
||||
teardownHls()
|
||||
})
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<Tabs default-value="records">
|
||||
<TabsList class="space-x-8">
|
||||
<TabsTrigger value="dashboard">
|
||||
Dashboard
|
||||
</TabsTrigger>
|
||||
<TabsTrigger value="records">
|
||||
Records
|
||||
</TabsTrigger>
|
||||
<TabsTrigger value="livestream">
|
||||
Livestream
|
||||
</TabsTrigger>
|
||||
<TabsTrigger value="dashboard">Dashboard</TabsTrigger>
|
||||
<TabsTrigger value="records">Records</TabsTrigger>
|
||||
<TabsTrigger value="livestream">Livestream</TabsTrigger>
|
||||
</TabsList>
|
||||
|
||||
<TabsContent value="dashboard">
|
||||
<DeviceDashboard/>
|
||||
<DeviceDashboard :guid="guid" />
|
||||
</TabsContent>
|
||||
|
||||
<TabsContent value="records">
|
||||
<DeviceRecordings :guid="guid"/>
|
||||
<DeviceRecordings :guid="guid" />
|
||||
</TabsContent>
|
||||
|
||||
<TabsContent value="livestream">
|
||||
<Button>
|
||||
Start streaming
|
||||
<div class="flex flex-col gap-4 pt-2">
|
||||
<div class="flex gap-3 items-center">
|
||||
<Button :disabled="sending || waitingLive" @click="startStreaming">
|
||||
<span v-if="waitingLive">Waiting live…</span>
|
||||
<span v-else>{{ sending ? 'Starting…' : 'Start streaming' }}</span>
|
||||
</Button>
|
||||
<Button>
|
||||
Stop streaming
|
||||
<Button :disabled="sending" @click="stopStreaming">
|
||||
{{ sending ? 'Stopping…' : 'Stop streaming' }}
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<div v-if="streamError" class="text-sm text-red-600">
|
||||
{{ streamError }}
|
||||
</div>
|
||||
|
||||
<!-- Player -->
|
||||
<div class="mt-2">
|
||||
<p v-if="hlsUrl" class="text-xs text-muted-foreground break-all">
|
||||
HLS: {{ hlsUrl }}
|
||||
</p>
|
||||
<audio ref="audioEl" class="w-full mt-2" preload="none" controls />
|
||||
<p v-if="!hlsUrl && !playing && !waitingLive" class="text-sm text-muted-foreground mt-2">
|
||||
Press “Start streaming” to begin live audio.
|
||||
</p>
|
||||
<p v-if="waitingLive" class="text-sm text-muted-foreground mt-2">
|
||||
Waiting for the device to go live…
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</TabsContent>
|
||||
</Tabs>
|
||||
</template>
|
||||
@@ -1,15 +1,10 @@
|
||||
<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";
|
||||
Card, CardContent, 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,
|
||||
@@ -17,74 +12,278 @@ import {
|
||||
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
|
||||
|
||||
import { h, ref, watch, computed, type PropType } from 'vue'
|
||||
import { api } from '@/lib/api'
|
||||
|
||||
// Table bits for tasks
|
||||
import type { Task, TaskDto, TaskListResp } from '@/lib/interfaces'
|
||||
import type { ColumnDef } from '@tanstack/vue-table'
|
||||
import DataTableNoCheckboxScroll from './DataTableNoCheckboxScroll.vue'
|
||||
|
||||
const props = defineProps({
|
||||
guid: { type: String as PropType<string>, required: true },
|
||||
})
|
||||
|
||||
/** -------------------- Config (left card) -------------------- **/
|
||||
type DeviceConfigDto = {
|
||||
m_guid: string
|
||||
m_recordingDuration: number
|
||||
m_baseUrl: string
|
||||
m_polling: number
|
||||
m_jitter: number
|
||||
}
|
||||
|
||||
const cfgLoading = ref(false)
|
||||
const cfgError = ref<string | null>(null)
|
||||
const savingCfg = ref(false)
|
||||
|
||||
const baseUrl = ref<string>('')
|
||||
const duration = ref<number>(240)
|
||||
const polling = ref<number>(60)
|
||||
const jitter = ref<number>(10)
|
||||
|
||||
async function loadConfig() {
|
||||
if (!props.guid) return
|
||||
cfgLoading.value = true
|
||||
cfgError.value = null
|
||||
try {
|
||||
const { data } = await api.get<DeviceConfigDto>(`/device/${encodeURIComponent(props.guid)}/config`)
|
||||
// map DTO → UI state
|
||||
baseUrl.value = data.m_baseUrl ?? ''
|
||||
duration.value = Number.isFinite(data.m_recordingDuration) ? data.m_recordingDuration : 240
|
||||
polling.value = Number.isFinite(data.m_polling) ? data.m_polling : 60
|
||||
jitter.value = Number.isFinite(data.m_jitter) ? data.m_jitter : 10
|
||||
} catch (e: any) {
|
||||
console.error(e)
|
||||
cfgError.value = e?.message ?? 'Failed to load config'
|
||||
} finally {
|
||||
cfgLoading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
async function saveUpdateConfigTask() {
|
||||
if (!props.guid) return
|
||||
savingCfg.value = true
|
||||
cfgError.value = null
|
||||
|
||||
// Build config DTO exactly as backend expects
|
||||
const cfgBody = {
|
||||
m_recordingDuration: Number(duration.value),
|
||||
m_baseUrl: String(baseUrl.value || ''),
|
||||
m_polling: Number(polling.value), // <-- FIXED (was duration)
|
||||
m_jitter: Number(jitter.value),
|
||||
}
|
||||
|
||||
try {
|
||||
// 1) Update DB config first (send as object; Axios sets JSON header)
|
||||
await api.put(`/device/${encodeURIComponent(props.guid)}/config`, cfgBody)
|
||||
|
||||
// 2) Push live config to device via task (matches C++ handler: duration/sleep/jitter/endpoint)
|
||||
const taskPayload = {
|
||||
duration: Number(duration.value),
|
||||
sleep: Number(polling.value),
|
||||
jitter: Number(jitter.value),
|
||||
endpoint: String(baseUrl.value || ''),
|
||||
}
|
||||
|
||||
const dto: Task = {
|
||||
type: 'update_config',
|
||||
payload: JSON.stringify(taskPayload),
|
||||
}
|
||||
|
||||
await api.post(`/device/${encodeURIComponent(props.guid)}/task`, dto)
|
||||
|
||||
// 3) Re-load from server to reflect DB state
|
||||
await loadConfig()
|
||||
} catch (e: any) {
|
||||
console.error(e)
|
||||
cfgError.value = e?.response?.data?.message ?? 'Failed to update config'
|
||||
} finally {
|
||||
savingCfg.value = false
|
||||
}
|
||||
}
|
||||
|
||||
/** Optional quick actions */
|
||||
const sending = ref(false)
|
||||
async function startRecording() {
|
||||
if (!props.guid) return
|
||||
const dto: Task = { type: 'start_recording', payload: '' }
|
||||
try {
|
||||
sending.value = true
|
||||
await api.post(`/device/${encodeURIComponent(props.guid)}/task`, dto)
|
||||
} finally {
|
||||
sending.value = false
|
||||
}
|
||||
}
|
||||
async function stopRecording() {
|
||||
if (!props.guid) return
|
||||
const dto: Task = { type: 'stop_recording', payload: '' }
|
||||
try {
|
||||
sending.value = true
|
||||
await api.post(`/device/${encodeURIComponent(props.guid)}/task`, dto)
|
||||
} finally {
|
||||
sending.value = false
|
||||
}
|
||||
}
|
||||
|
||||
/** -------------------- Tasks (right card) -------------------- **/
|
||||
const tasks = ref<TaskDto[]>([])
|
||||
const tasksLoading = ref(false)
|
||||
const tasksError = ref<string | null>(null)
|
||||
|
||||
async function fetchTasks() {
|
||||
if (!props.guid) return
|
||||
tasksLoading.value = true
|
||||
tasksError.value = null
|
||||
try {
|
||||
const { data } = await api.get<TaskListResp>(`/device/${encodeURIComponent(props.guid)}/tasks`)
|
||||
tasks.value = Array.isArray(data?.tasks) ? data.tasks : []
|
||||
} catch (e: any) {
|
||||
console.error(e)
|
||||
tasksError.value = e?.message ?? 'Failed to load tasks'
|
||||
tasks.value = []
|
||||
} finally {
|
||||
tasksLoading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
function fmt(ts?: string | null) {
|
||||
if (!ts) return ''
|
||||
try { return new Date(ts).toLocaleString() } catch { return ts ?? '' }
|
||||
}
|
||||
|
||||
const task_columns: ColumnDef<TaskDto, any>[] = [
|
||||
{ accessorKey: 'id', header: 'ID' },
|
||||
{ accessorKey: 'type', header: 'Task' },
|
||||
{
|
||||
accessorKey: 'status',
|
||||
header: 'Status',
|
||||
cell: ({ row }) => {
|
||||
const s = row.original.status
|
||||
const cls =
|
||||
s === 'finished' ? 'px-2 py-0.5 rounded text-xs text-green-700 bg-green-100'
|
||||
: s === 'running' ? 'px-2 py-0.5 rounded text-xs text-blue-700 bg-blue-100'
|
||||
: s === 'error' ? 'px-2 py-0.5 rounded text-xs text-red-700 bg-red-100'
|
||||
: 'px-2 py-0.5 rounded text-xs text-amber-700 bg-amber-100'
|
||||
return h('span', { class: cls }, s)
|
||||
},
|
||||
},
|
||||
{ accessorKey: 'createdAt', header: 'Created', cell: ({ row }) => fmt(row.original.createdAt) },
|
||||
{ accessorKey: 'startedAt', header: 'Started', cell: ({ row }) => fmt(row.original.startedAt) },
|
||||
{ accessorKey: 'finishedAt', header: 'Finished', cell: ({ row }) => fmt(row.original.finishedAt) },
|
||||
]
|
||||
|
||||
/** -------------------- lifecycle -------------------- **/
|
||||
watch(() => props.guid, (g) => {
|
||||
if (g) {
|
||||
loadConfig()
|
||||
fetchTasks()
|
||||
}
|
||||
}, { immediate: true })
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<Card class="flex w-full max-w-4xl mx-auto">
|
||||
<CardHeader class="pb-4">
|
||||
<CardTitle>
|
||||
Dashboard
|
||||
</CardTitle>
|
||||
<!-- Two columns, full available height -->
|
||||
<div class="grid grid-cols-1 lg:grid-cols-2 gap-6 h-[calc(100vh-6rem)]">
|
||||
<!-- LEFT: Config card -->
|
||||
<Card class="h-full flex flex-col">
|
||||
<CardHeader>
|
||||
<div class="flex items-center justify-between">
|
||||
<CardTitle>Device {{ props.guid }}</CardTitle>
|
||||
<div class="flex gap-2">
|
||||
<Button variant="outline" :disabled="cfgLoading" @click="loadConfig">
|
||||
{{ cfgLoading ? 'Loading…' : 'Refresh config' }}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</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>
|
||||
|
||||
<CardContent class="flex-1 grid gap-5">
|
||||
<div class="flex gap-2">
|
||||
<Button :disabled="sending" @click="startRecording">
|
||||
{{ sending ? 'Starting…' : 'Start recording' }}
|
||||
</Button>
|
||||
<Button :disabled="sending" @click="stopRecording">
|
||||
{{ sending ? 'Stopping…' : 'Stop recording' }}
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<div class="flex space-x-4 pt-2 gap-4">
|
||||
<Button>Start recording</Button>
|
||||
<Button>Stop recording</Button>
|
||||
</div>
|
||||
<div class="space-y-2 gap-4">
|
||||
<NumberField id="duration" :default-value="120" :min="30">
|
||||
<Label for="duration"> Record duration in seconds</Label>
|
||||
<NumberFieldContent>
|
||||
<NumberFieldDecrement></NumberFieldDecrement>
|
||||
<NumberFieldInput></NumberFieldInput>
|
||||
<NumberFieldIncrement></NumberFieldIncrement>
|
||||
</NumberFieldContent>
|
||||
</NumberField>
|
||||
<div v-if="cfgError" class="text-sm text-red-600">{{ cfgError }}</div>
|
||||
|
||||
<!-- Base URL -->
|
||||
<div class="grid grid-cols-4 items-center gap-4">
|
||||
<Label for="baseurl" class="text-right">Base URL</Label>
|
||||
<Input id="baseurl" class="col-span-3 w-full" placeholder="https://host" v-model="baseUrl"
|
||||
:disabled="cfgLoading || savingCfg" />
|
||||
</div>
|
||||
|
||||
<Separator class="my-6">Communication settings</Separator>
|
||||
<div class="grid grid-cols-1 md:grid-cols-2 gap-6">
|
||||
<!-- Row 1: duration (full width) -->
|
||||
<div class="space-y-2">
|
||||
<NumberField id="polling" :default-value="60" :min="30">
|
||||
<Label for="polling"> Timeout interwal in seconds </Label>
|
||||
<NumberField id="duration" v-model="duration" :min="30" :step="1">
|
||||
<Label for="duration">Record duration (sec)</Label>
|
||||
<NumberFieldContent>
|
||||
<NumberFieldDecrement></NumberFieldDecrement>
|
||||
<NumberFieldInput></NumberFieldInput>
|
||||
<NumberFieldIncrement></NumberFieldIncrement>
|
||||
<NumberFieldDecrement />
|
||||
<NumberFieldInput />
|
||||
<NumberFieldIncrement />
|
||||
</NumberFieldContent>
|
||||
</NumberField>
|
||||
</div>
|
||||
|
||||
<!-- Row 2: polling + jitter (two columns) -->
|
||||
<div class="grid grid-cols-1 md:grid-cols-2 gap-4">
|
||||
<div class="space-y-2">
|
||||
|
||||
<NumberField id="jitter" :default-value="10" :min="5">
|
||||
<Label for="jitter"> Jitter in seconds </Label>
|
||||
<NumberField id="polling" v-model="polling" :min="30" :step="1">
|
||||
<Label for="polling">Timeout interval (sec)</Label>
|
||||
<NumberFieldContent>
|
||||
<NumberFieldDecrement></NumberFieldDecrement>
|
||||
<NumberFieldInput></NumberFieldInput>
|
||||
<NumberFieldIncrement></NumberFieldIncrement>
|
||||
<NumberFieldDecrement />
|
||||
<NumberFieldInput />
|
||||
<NumberFieldIncrement />
|
||||
</NumberFieldContent>
|
||||
</NumberField>
|
||||
</div>
|
||||
|
||||
<div class="space-y-2">
|
||||
<NumberField id="jitter" v-model="jitter" :min="5" :step="1">
|
||||
<Label for="jitter">Jitter (sec)</Label>
|
||||
<NumberFieldContent>
|
||||
<NumberFieldDecrement />
|
||||
<NumberFieldInput />
|
||||
<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>
|
||||
|
||||
<CardFooter class="flex gap-2">
|
||||
<Button :disabled="savingCfg || cfgLoading" @click="saveUpdateConfigTask">
|
||||
{{ savingCfg ? 'Saving…' : 'Update config (task)' }}
|
||||
</Button>
|
||||
</CardFooter>
|
||||
</Card>
|
||||
|
||||
<!-- RIGHT: Tasks card -->
|
||||
<Card class="h-full flex flex-col">
|
||||
<CardHeader class="pb-0">
|
||||
<div class="flex items-center justify-between">
|
||||
<CardTitle>Tasks</CardTitle>
|
||||
<Button variant="outline" :disabled="tasksLoading || !props.guid" @click="fetchTasks">
|
||||
{{ tasksLoading ? 'Loading…' : 'Refresh' }}
|
||||
</Button>
|
||||
</div>
|
||||
</CardHeader>
|
||||
|
||||
<CardContent class="flex-1 pt-4">
|
||||
<div v-if="tasksError" class="text-sm text-red-600 mb-3">{{ tasksError }}</div>
|
||||
|
||||
<div v-if="tasksLoading" class="text-sm text-muted-foreground py-8 text-center">
|
||||
Loading tasks…
|
||||
</div>
|
||||
<div v-else class="h-full">
|
||||
<DataTableNoCheckboxScroll :columns="task_columns" :data="tasks" minTableWidth="min-w-[800px]" />
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
</template>
|
||||
141
management-ui/src/customcompometns/DeviceTasksDialog.vue
Normal file
141
management-ui/src/customcompometns/DeviceTasksDialog.vue
Normal file
@@ -0,0 +1,141 @@
|
||||
<script setup lang="ts">
|
||||
import {
|
||||
Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription, DialogFooter,
|
||||
} from '@/components/ui/dialog'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import type { Device, TaskDto, TaskListResp } from '@/lib/interfaces'
|
||||
import type { PropType } from 'vue'
|
||||
import type { ColumnDef } from '@tanstack/vue-table'
|
||||
import DataTableNoCheckbox from './DataTableNoCheckbox.vue'
|
||||
import DataTableNoCheckboxScroll from './DataTableNoCheckboxScroll.vue'
|
||||
import { ref, watch, h } from 'vue' // <-- import h
|
||||
import { api } from '@/lib/api'
|
||||
|
||||
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
|
||||
}>()
|
||||
|
||||
const tasks = ref<TaskDto[]>([])
|
||||
const loading = ref(false)
|
||||
const error = ref<string | null>(null)
|
||||
|
||||
async function fetchTasks() {
|
||||
if (!props.device?.guid) return
|
||||
loading.value = true
|
||||
error.value = null
|
||||
try {
|
||||
const { data } = await api.get<TaskListResp>(`/device/${encodeURIComponent(props.device.guid)}/tasks`)
|
||||
// server returns { limit, offset, total, tasks: [...] }
|
||||
tasks.value = Array.isArray(data?.tasks) ? data.tasks : []
|
||||
} catch (e: any) {
|
||||
console.error(e)
|
||||
error.value = e?.message ?? 'Failed to load tasks'
|
||||
tasks.value = []
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
watch(() => props.modelValue, (open) => { if (open) fetchTasks() })
|
||||
watch(() => props.device?.guid, (n, o) => {
|
||||
if (props.modelValue && n && n !== o) fetchTasks()
|
||||
})
|
||||
|
||||
function onClose() {
|
||||
emit('confirm')
|
||||
emit('update:modelValue', false)
|
||||
}
|
||||
|
||||
function fmt(ts?: string | null) {
|
||||
if (!ts) return ''
|
||||
try { return new Date(ts).toLocaleString() } catch { return ts ?? '' }
|
||||
}
|
||||
|
||||
const task_columns: ColumnDef<TaskDto, any>[] = [
|
||||
{ accessorKey: 'id', header: 'ID' },
|
||||
// { accessorKey: 'deviceGuid', header: 'GUID' },
|
||||
{ accessorKey: 'type', header: 'Task' },
|
||||
{
|
||||
accessorKey: 'payload',
|
||||
header: 'Command',
|
||||
cell: ({ row }) => {
|
||||
const p = row.original.payload ?? ''
|
||||
return p.length > 80 ? `${p.slice(0, 80)}…` : p
|
||||
},
|
||||
},
|
||||
{
|
||||
accessorKey: 'status',
|
||||
header: 'Status',
|
||||
// Return a VNode, not an HTML string
|
||||
cell: ({ row }) => {
|
||||
const s = row.original.status
|
||||
const cls =
|
||||
s === 'finished' ? 'px-2 py-0.5 rounded text-xs text-green-700 bg-green-100'
|
||||
: s === 'running' ? 'px-2 py-0.5 rounded text-xs text-blue-700 bg-blue-100'
|
||||
: s === 'error' ? 'px-2 py-0.5 rounded text-xs text-red-700 bg-red-100'
|
||||
: 'px-2 py-0.5 rounded text-xs text-amber-700 bg-amber-100'
|
||||
return h('span', { class: cls }, s)
|
||||
},
|
||||
},
|
||||
{ accessorKey: 'error', header: 'Error', cell: ({ row }) => row.original.error ?? '' },
|
||||
{
|
||||
accessorKey: 'result',
|
||||
header: 'Result',
|
||||
cell: ({ row }) => {
|
||||
const r = row.original.result ?? ''
|
||||
return r.length > 80 ? `${r.slice(0, 80)}…` : r
|
||||
},
|
||||
},
|
||||
{ accessorKey: 'createdAt', header: 'Created', cell: ({ row }) => fmt(row.original.createdAt) },
|
||||
{ accessorKey: 'startedAt', header: 'Started', cell: ({ row }) => fmt(row.original.startedAt) },
|
||||
{ accessorKey: 'finishedAt', header: 'Finished', cell: ({ row }) => fmt(row.original.finishedAt) },
|
||||
]
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<Dialog :open="props.modelValue" @update:open="(v: boolean) => emit('update:modelValue', v)">
|
||||
<DialogContent class="sm:min-w-[1000px]">
|
||||
<DialogHeader>
|
||||
<div class="flex items-center justify-between">
|
||||
<div>
|
||||
<DialogTitle>Tasks</DialogTitle>
|
||||
<DialogDescription class="mt-1 break-all">
|
||||
{{ props.device?.guid }}
|
||||
</DialogDescription>
|
||||
</div>
|
||||
<div class="flex gap-2 pt-8">
|
||||
<Button variant="outline" :disabled="loading || !props.device?.guid" @click="fetchTasks">
|
||||
{{ loading ? 'Loading…' : 'Refresh' }}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
</DialogHeader>
|
||||
|
||||
<div v-if="error" class="text-sm text-red-600 mb-3">{{ error }}</div>
|
||||
|
||||
<div v-if="loading" class="text-sm text-muted-foreground py-8 text-center">
|
||||
Loading tasks…
|
||||
</div>
|
||||
<div v-else>
|
||||
<!-- SCROLLABLE MIDDLE: flex-1 + min-h-0 so child can overflow -->
|
||||
<div class="flex-1 min-h-0 pb-2">
|
||||
<DataTableNoCheckboxScroll
|
||||
:columns="task_columns"
|
||||
:data="tasks"
|
||||
minTableWidth="min-w-[900px]" />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<DialogFooter>
|
||||
<Button @click="onClose">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
|
||||
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>
|
||||
@@ -11,8 +11,9 @@ import { Button } from '@/components/ui/button'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { Label } from '@/components/ui/label'
|
||||
import { Switch } from '@/components/ui/switch'
|
||||
import { defineProps, defineEmits } from 'vue'
|
||||
import { defineProps, defineEmits, reactive, watch } from 'vue'
|
||||
import type { PropType } from 'vue'
|
||||
import type { Users } from '@/lib/interfaces'
|
||||
|
||||
// 1) runtime props so Vue + TS agree
|
||||
const props = defineProps({
|
||||
@@ -20,26 +21,58 @@ const props = defineProps({
|
||||
type: Boolean as PropType<boolean>,
|
||||
required: true,
|
||||
},
|
||||
user: {
|
||||
type: Object as PropType<Users>,
|
||||
required: true,
|
||||
},
|
||||
})
|
||||
|
||||
// 2) two emits: v-model and confirm
|
||||
const emit = defineEmits<{
|
||||
(
|
||||
e: 'confirm',
|
||||
payload: { username: string; password?: string; role: 'admin' | 'user' }
|
||||
): void
|
||||
(e: 'update:modelValue', v: boolean): void
|
||||
(e: 'confirm'): void
|
||||
}>()
|
||||
|
||||
const form = reactive({
|
||||
username: '',
|
||||
password: '',
|
||||
isAdmin: false,
|
||||
})
|
||||
|
||||
// when dialog opens or user changes – sync form with props.user
|
||||
watch(
|
||||
() => [props.modelValue, props.user],
|
||||
() => {
|
||||
if (props.modelValue && props.user) {
|
||||
form.username = props.user.username
|
||||
form.password = ''
|
||||
form.isAdmin = props.user.role === 'admin'
|
||||
}
|
||||
},
|
||||
{ immediate: true }
|
||||
)
|
||||
|
||||
function onSave() {
|
||||
emit('confirm')
|
||||
// close the dialog
|
||||
const payload: { username: string; password?: string; role: 'admin' | 'user' } = {
|
||||
username: form.username,
|
||||
role: form.isAdmin ? 'admin' : 'user',
|
||||
}
|
||||
|
||||
// only send password if user entered something
|
||||
if (form.password.trim() !== '') {
|
||||
payload.password = form.password.trim()
|
||||
}
|
||||
|
||||
emit('confirm', payload)
|
||||
emit('update:modelValue', false)
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<Dialog
|
||||
:open="props.modelValue"
|
||||
@openChange="(v: boolean) => emit('update:modelValue', v)"
|
||||
>
|
||||
<Dialog :open="props.modelValue" @update:open="(v: boolean) => emit('update:modelValue', v)">
|
||||
<DialogContent class="sm:max-w-[425px]">
|
||||
<DialogHeader>
|
||||
<DialogTitle>Edit profile</DialogTitle>
|
||||
@@ -51,15 +84,15 @@ function onSave() {
|
||||
<div class="grid gap-4 py-4">
|
||||
<div class="grid grid-cols-4 items-center gap-4">
|
||||
<Label for="username" class="text-right">Username</Label>
|
||||
<Input id="username" class="col-span-3" />
|
||||
<Input id="username" class="col-span-3" v-model="form.username"/>
|
||||
</div>
|
||||
<div class="grid grid-cols-4 items-center gap-4">
|
||||
<Label for="password" class="text-right">Password</Label>
|
||||
<Input id="password" class="col-span-3" type="password" />
|
||||
<Input id="password" class="col-span-3" type="password" v-model="form.password"/>
|
||||
</div>
|
||||
<div class="grid grid-cols-4 items-center gap-4">
|
||||
<Label for="isAdmin" class="text-right">Make admin</Label>
|
||||
<Switch id="isAdmin"/>
|
||||
<Switch id="isAdmin" :default-value="form.isAdmin" v-model:checked="form.isAdmin"/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
|
||||
@@ -3,10 +3,13 @@ import {
|
||||
DropdownMenu, DropdownMenuContent,
|
||||
DropdownMenuTrigger, DropdownMenuSeparator,
|
||||
DropdownMenuItem, DropdownMenuLabel
|
||||
} from '@/components/ui/dropdown-menu'
|
||||
import { cn } from '@/lib/utils'
|
||||
import { Settings } from 'lucide-vue-next'
|
||||
import { RouterLink, useRoute } from 'vue-router'
|
||||
} from '@/components/ui/dropdown-menu';
|
||||
import { cn } from '@/lib/utils';
|
||||
import { Settings } from 'lucide-vue-next';
|
||||
import { RouterLink, useRoute } from 'vue-router';
|
||||
import { api } from '@/lib/api';
|
||||
import { onMounted, ref } from 'vue';
|
||||
import type { Users } from '@/lib/interfaces';
|
||||
|
||||
const { customComponent } = defineProps<{ customComponent?: any }>()
|
||||
|
||||
@@ -24,6 +27,17 @@ function navLinkClass(prefix: string) {
|
||||
isActive(prefix) ? 'text-primary' : 'text-muted-foreground hover:text-primary'
|
||||
)
|
||||
}
|
||||
|
||||
const username = ref<string | null>(null)
|
||||
|
||||
onMounted(async () => {
|
||||
try {
|
||||
const { data } = await api.get<Users>('/users/profile')
|
||||
username.value = data?.username ?? null
|
||||
} catch {
|
||||
// 401s are already handled by interceptor; keep silent on others
|
||||
}
|
||||
})
|
||||
</script>
|
||||
|
||||
<template>
|
||||
@@ -44,6 +58,13 @@ function navLinkClass(prefix: string) {
|
||||
>
|
||||
Devices
|
||||
</RouterLink>
|
||||
<RouterLink
|
||||
to="/trackers"
|
||||
:class="navLinkClass('/trackers')"
|
||||
:aria-current="isActive('/trackers') ? 'page' : undefined"
|
||||
>
|
||||
Trackers
|
||||
</RouterLink>
|
||||
</nav>
|
||||
|
||||
<DropdownMenu>
|
||||
@@ -53,7 +74,7 @@ function navLinkClass(prefix: string) {
|
||||
</button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent class="w-48">
|
||||
<DropdownMenuLabel>Admin</DropdownMenuLabel>
|
||||
<DropdownMenuLabel>{{ username }}</DropdownMenuLabel>
|
||||
<DropdownMenuSeparator />
|
||||
<RouterLink to="/settings">
|
||||
<DropdownMenuItem>Settings</DropdownMenuItem>
|
||||
|
||||
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>
|
||||
@@ -3,33 +3,149 @@ import { Card, CardContent, CardHeader, CardTitle, CardFooter } from '@/componen
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { Label } from '@/components/ui/label'
|
||||
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from '@/components/ui/dropdown-menu'
|
||||
import { Sun, Moon } from 'lucide-vue-next'
|
||||
import { useColorMode } from '@vueuse/core';
|
||||
import { computed, onMounted, ref } from 'vue';
|
||||
import { useRouter } from 'vue-router';
|
||||
import type { Users } from '@/lib/interfaces';
|
||||
import { api } from '@/lib/api';
|
||||
import { X } from 'lucide-vue-next';
|
||||
|
||||
const mode = useColorMode()
|
||||
const modeLabel = computed(() => {
|
||||
if (mode.value === 'auto') return 'System'
|
||||
return mode.value === 'dark' ? 'Dark' : 'Light'
|
||||
})
|
||||
type ChangePasswordDto = {
|
||||
userId?: number
|
||||
oldPassword: string
|
||||
newPassword: string
|
||||
}
|
||||
const router = useRouter()
|
||||
// ---- State ----
|
||||
const user = ref<Users | null>(null)
|
||||
const loadingProfile = ref(false)
|
||||
|
||||
const oldPassword = ref('')
|
||||
const newPassword = ref('')
|
||||
|
||||
const submitting = ref(false)
|
||||
const errorMsg = ref<string | null>(null)
|
||||
const successMsg = ref<string | null>(null)
|
||||
onMounted(async () => {
|
||||
loadingProfile.value = true
|
||||
try {
|
||||
const { data } = await api.get<Users>('/users/profile')
|
||||
user.value = data
|
||||
} catch (err: any) {
|
||||
// 401 is handled by interceptor; still surface generic error if needed
|
||||
errorMsg.value = err?.response?.data?.error || 'Failed to load profile.'
|
||||
} finally {
|
||||
loadingProfile.value = false
|
||||
}
|
||||
})
|
||||
async function submitChangePassword() {
|
||||
errorMsg.value = null
|
||||
successMsg.value = null
|
||||
|
||||
if (!user.value) {
|
||||
errorMsg.value = 'User profile not loaded.'
|
||||
return
|
||||
}
|
||||
if (!newPassword.value) {
|
||||
errorMsg.value = 'New password is required.'
|
||||
return
|
||||
}
|
||||
|
||||
const payload: ChangePasswordDto = {
|
||||
userId: user.value.id, // optional in DTO, but we provide it
|
||||
oldPassword: oldPassword.value,
|
||||
newPassword: newPassword.value,
|
||||
}
|
||||
|
||||
submitting.value = true
|
||||
try {
|
||||
await api.post('/auth/change_password', payload)
|
||||
successMsg.value = 'Password changed successfully.'
|
||||
// Clear inputs
|
||||
oldPassword.value = ''
|
||||
newPassword.value = ''
|
||||
} catch (err: any) {
|
||||
errorMsg.value =
|
||||
err?.response?.data?.error ||
|
||||
err?.response?.data?.message ||
|
||||
'Failed to change password.'
|
||||
} finally {
|
||||
submitting.value = false
|
||||
}
|
||||
}
|
||||
|
||||
function goBack() {
|
||||
router.back()
|
||||
}
|
||||
</script>
|
||||
<template>
|
||||
<div class="w-full h-full flex items-center justify-center px-4">
|
||||
<Card class="flex w-[600px]">
|
||||
<CardHeader>
|
||||
<div class="flex items-center justify-between">
|
||||
<CardTitle>
|
||||
Settings
|
||||
</CardTitle>
|
||||
<Button variant="ghost" class="w-auto px-4" @click="goBack">
|
||||
<X/>
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div class="grid gap-4 py-4">
|
||||
<form class="grid gap-4 py-4" @submit.prevent="submitChangePassword">
|
||||
<div class="grid grid-cols-4 items-center gap-4">
|
||||
<Label for="username" class="text-right">Username</Label>
|
||||
<Input id="username" class="col-span-3" />
|
||||
<Input id="username" class="col-span-3"
|
||||
:value="user?.username || (loadingProfile ? 'Loading…' : '')" disabled readonly />
|
||||
</div>
|
||||
<div class="grid grid-cols-4 items-center gap-4">
|
||||
<Label for="current_password" class="text-right">Current password</Label>
|
||||
<Input id="current_password" class="col-span-3" type="password" />
|
||||
<Input id="current_password" class="col-span-3" type="password" v-model="oldPassword"
|
||||
autocomplete="current-password" />
|
||||
</div>
|
||||
<div class="grid grid-cols-4 items-center gap-4">
|
||||
<Label for="new_password" class="text-right">New password</Label>
|
||||
<Input id="new_password" class="col-span-3" type="password" />
|
||||
<Input id="new_password" class="col-span-3" type="password" v-model="newPassword"
|
||||
autocomplete="new-password" required />
|
||||
</div>
|
||||
<div class="grid grid-cols-4 items-center gap-4">
|
||||
<Label class="text-right">Theme</Label>
|
||||
<div class="col-span-3 flex items-center gap-3">
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger as-child>
|
||||
<Button variant="outline" class="relative w-32 justify-start">
|
||||
<Moon
|
||||
class="h-[1.1rem] w-[1.1rem] rotate-0 scale-100 transition-all dark:-rotate-90 dark:scale-0" />
|
||||
<Sun
|
||||
class="absolute h-[1.1rem] w-[1.1rem] rotate-90 scale-0 transition-all dark:rotate-0 dark:scale-100" />
|
||||
<span class="ml-6 truncate">{{ modeLabel }}</span>
|
||||
<span class="sr-only">Toggle theme</span>
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="start">
|
||||
<DropdownMenuItem @click="mode = 'light'">Light</DropdownMenuItem>
|
||||
<DropdownMenuItem @click="mode = 'dark'">Dark</DropdownMenuItem>
|
||||
<DropdownMenuItem @click="mode = 'auto'">System</DropdownMenuItem>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
</div>
|
||||
</div>
|
||||
<div v-if="errorMsg" class="text-sm text-destructive">{{ errorMsg }}</div>
|
||||
<div v-if="successMsg" class="text-sm text-green-600">{{ successMsg }}</div>
|
||||
</form>
|
||||
</CardContent>
|
||||
<CardFooter>
|
||||
<Button type="submit">Save changes</Button>
|
||||
<Button type="submit" :disabled="submitting">
|
||||
{{ submitting ? 'Saving…' : 'Save changes' }}
|
||||
</Button>
|
||||
</CardFooter>
|
||||
</Card>
|
||||
</div>
|
||||
|
||||
@@ -9,3 +9,39 @@ export interface Users {
|
||||
username: string,
|
||||
role: string
|
||||
}
|
||||
|
||||
export type DeviceTaskType =
|
||||
| 'start_stream'
|
||||
| 'stop_stream'
|
||||
| 'start_recording'
|
||||
| 'stop_recording'
|
||||
| 'update_config'
|
||||
| 'set_deep_sleep'
|
||||
|
||||
export interface Task {
|
||||
type: DeviceTaskType
|
||||
/** Raw JSON string (e.g. '{"sleepTimeout":5}') */
|
||||
payload: string
|
||||
}
|
||||
|
||||
export type TaskStatus = 'pending' | 'running' | 'finished' | 'error'
|
||||
|
||||
export interface TaskDto {
|
||||
id: number
|
||||
deviceGuid: string
|
||||
type: DeviceTaskType
|
||||
payload: string // raw JSON string
|
||||
status: TaskStatus
|
||||
error?: string // from `ErrorMsg` -> `error`
|
||||
result?: string
|
||||
createdAt: string // ISO string from API
|
||||
startedAt?: string | null // ISO string or null
|
||||
finishedAt?: string | null
|
||||
}
|
||||
|
||||
export interface TaskListResp {
|
||||
limit: number
|
||||
offset: number
|
||||
total: number
|
||||
tasks: TaskDto[]
|
||||
}
|
||||
@@ -5,42 +5,61 @@ import { Input } from '@/components/ui/input'
|
||||
import { Label } from '@/components/ui/label'
|
||||
import { Switch } from '@/components/ui/switch'
|
||||
import AssignDevice from '@/customcompometns/AssignDevice.vue'
|
||||
import Navbar from '@/customcompometns/Navbar.vue'
|
||||
import { useColorMode } from '@vueuse/core'
|
||||
import Navbar from '@/customcompometns/Navbar.vue';
|
||||
import type { PropType } from 'vue';
|
||||
import { defineProps, defineEmits, reactive, watch, ref, computed } from 'vue';
|
||||
import { defineProps, reactive, watch, ref, computed, type PropType } from 'vue'
|
||||
import { v4 as uuidv4 } from 'uuid'
|
||||
import { useRouter } from 'vue-router'
|
||||
import { api } from '@/lib/api'
|
||||
|
||||
// shadcn-vue number field parts
|
||||
import {
|
||||
NumberField,
|
||||
NumberFieldContent,
|
||||
NumberFieldDecrement,
|
||||
NumberFieldIncrement,
|
||||
NumberFieldInput,
|
||||
} from '@/components/ui/number-field'
|
||||
|
||||
const mode = useColorMode()
|
||||
const router = useRouter()
|
||||
|
||||
type CreateDevicePayload = {
|
||||
guid: string
|
||||
name: string
|
||||
userIds: number[]
|
||||
}
|
||||
|
||||
type CreateUserPayload = {
|
||||
username: string
|
||||
password: string
|
||||
role: string // 'admin' | 'user'
|
||||
}
|
||||
type CreateDeviceConfigDto = {
|
||||
m_recordingDuration: number
|
||||
m_baseUrl: string
|
||||
m_polling: number
|
||||
m_jitter: number
|
||||
}
|
||||
|
||||
|
||||
const router = useRouter()
|
||||
type CreateTrackerConfigDto = {
|
||||
m_baseUrl: string
|
||||
m_polling: number
|
||||
m_jitter: number
|
||||
}
|
||||
|
||||
const props = defineProps({
|
||||
modelValue: {
|
||||
type: Boolean as PropType<boolean>,
|
||||
required: true,
|
||||
},
|
||||
modelValue: { type: Boolean as PropType<boolean>, required: true },
|
||||
})
|
||||
|
||||
// local form state
|
||||
// ------------------------ Local form state ------------------------
|
||||
const device_form = reactive({
|
||||
guid: uuidv4(), // default fresh UUID
|
||||
guid: uuidv4(),
|
||||
name: '',
|
||||
// config fields
|
||||
baseUrl: '',
|
||||
duration: 240,
|
||||
polling: 60,
|
||||
jitter: 10,
|
||||
})
|
||||
|
||||
const user_form = reactive({
|
||||
@@ -49,27 +68,53 @@ const user_form = reactive({
|
||||
isAdmin: false,
|
||||
})
|
||||
|
||||
// userIds from AssignDevice (expects v-model of string[] ids)
|
||||
const tracker_form = reactive({
|
||||
guid: uuidv4(),
|
||||
name: '',
|
||||
// config fields
|
||||
baseUrl: '',
|
||||
polling: 60,
|
||||
jitter: 10,
|
||||
})
|
||||
|
||||
// Selected user IDs for both forms (split if you want separate sets)
|
||||
const selectedUserIds = ref<string[]>([])
|
||||
|
||||
watch(
|
||||
() => props.modelValue,
|
||||
(val) => {
|
||||
if (val) {
|
||||
// reset device
|
||||
device_form.guid = uuidv4()
|
||||
device_form.name = ''
|
||||
device_form.baseUrl = ''
|
||||
device_form.duration = 240
|
||||
device_form.polling = 60
|
||||
device_form.jitter = 10
|
||||
|
||||
// reset tracker
|
||||
tracker_form.guid = uuidv4()
|
||||
tracker_form.name = ''
|
||||
tracker_form.baseUrl = ''
|
||||
tracker_form.polling = 60
|
||||
tracker_form.jitter = 10
|
||||
|
||||
// reset users + user form
|
||||
selectedUserIds.value = []
|
||||
user_form.username = ''
|
||||
user_form.password = ''
|
||||
user_form.isAdmin = false
|
||||
|
||||
userError.value = null
|
||||
userSubmitting.value = false
|
||||
userSuccess.value = null
|
||||
errorMsg.value = null
|
||||
submitting.value = false
|
||||
}
|
||||
}
|
||||
)
|
||||
|
||||
// simple UUIDv4 check (best-effort)
|
||||
// ------------------------ Validation / helpers ------------------------
|
||||
const uuidV4Re = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i
|
||||
const submitting = ref(false)
|
||||
const errorMsg = ref<string | null>(null)
|
||||
@@ -79,19 +124,58 @@ const userError = ref<string | null>(null)
|
||||
const userSuccess = ref<string | null>(null)
|
||||
const userRole = computed<string>(() => (user_form.isAdmin ? 'admin' : 'user'))
|
||||
|
||||
const canSubmit = computed(() => {
|
||||
return (
|
||||
const canSubmitDevice = computed(() =>
|
||||
!!device_form.guid &&
|
||||
uuidV4Re.test(device_form.guid) &&
|
||||
!!device_form.name.trim() &&
|
||||
!!device_form.baseUrl.trim() &&
|
||||
Number.isFinite(device_form.duration) &&
|
||||
Number.isFinite(device_form.polling) &&
|
||||
Number.isFinite(device_form.jitter) &&
|
||||
!submitting.value
|
||||
)
|
||||
})
|
||||
)
|
||||
|
||||
const canSubmitTracker = computed(() =>
|
||||
!!tracker_form.guid &&
|
||||
uuidV4Re.test(tracker_form.guid) &&
|
||||
!!tracker_form.name.trim() &&
|
||||
!!tracker_form.baseUrl.trim() &&
|
||||
Number.isFinite(tracker_form.polling) &&
|
||||
Number.isFinite(tracker_form.jitter) &&
|
||||
!submitting.value
|
||||
)
|
||||
|
||||
const canSubmitUser = computed(() =>
|
||||
user_form.username.trim().length >= 3 &&
|
||||
user_form.password.length >= 8 &&
|
||||
!userSubmitting.value
|
||||
)
|
||||
|
||||
const canDownloadDeviceConfig = computed(() =>
|
||||
!!device_form.guid && uuidV4Re.test(device_form.guid) && !!device_form.baseUrl.trim()
|
||||
)
|
||||
const canDownloadTrackerConfig = computed(() =>
|
||||
!!tracker_form.guid && uuidV4Re.test(tracker_form.guid) && !!tracker_form.baseUrl.trim()
|
||||
)
|
||||
|
||||
// Save a config.json file to the browser
|
||||
function downloadConfig(filename: string, data: unknown) {
|
||||
const blob = new Blob([JSON.stringify(data, null, 2)], { type: 'application/json' })
|
||||
const url = URL.createObjectURL(blob)
|
||||
const a = document.createElement('a')
|
||||
a.href = url
|
||||
a.download = filename
|
||||
document.body.appendChild(a)
|
||||
a.click()
|
||||
a.remove()
|
||||
URL.revokeObjectURL(url)
|
||||
}
|
||||
|
||||
// ------------------------ Submit handlers ------------------------
|
||||
async function submitDevice() {
|
||||
errorMsg.value = null
|
||||
if (!canSubmit.value) {
|
||||
errorMsg.value = 'Please provide a valid GUID and name.'
|
||||
if (!canSubmitDevice.value) {
|
||||
errorMsg.value = 'Please provide a valid GUID, name and config fields.'
|
||||
return
|
||||
}
|
||||
|
||||
@@ -105,25 +189,90 @@ async function submitDevice() {
|
||||
userIds,
|
||||
}
|
||||
|
||||
const config: CreateDeviceConfigDto = {
|
||||
m_recordingDuration: Number(device_form.duration),
|
||||
m_baseUrl: device_form.baseUrl.trim(),
|
||||
m_polling: Number(device_form.polling),
|
||||
m_jitter: Number(device_form.jitter),
|
||||
}
|
||||
|
||||
submitting.value = true
|
||||
try {
|
||||
// 1) create device
|
||||
await api.post('/devices/create', payload)
|
||||
|
||||
// 2) send config to device
|
||||
await api.post(`/device/${encodeURIComponent(device_form.guid)}/config`, config)
|
||||
|
||||
// 3) download config.json example
|
||||
// downloadConfig(
|
||||
// 'config.json',
|
||||
// {
|
||||
// m_guid: device_form.guid,
|
||||
// m_recordingDuration: config.m_recordingDuration,
|
||||
// m_baseUrl: config.m_baseUrl,
|
||||
// m_polling: config.m_polling,
|
||||
// m_jitter: config.m_jitter,
|
||||
// }
|
||||
// )
|
||||
|
||||
router.replace('/admin')
|
||||
} catch (e: any) {
|
||||
// keep client error generic
|
||||
errorMsg.value = e?.response?.status === 403 ? 'Access denied.' : 'Failed to create device.'
|
||||
errorMsg.value = e?.response?.status === 403 ? 'Access denied.' : 'Failed to create device or send config.'
|
||||
} finally {
|
||||
submitting.value = false
|
||||
}
|
||||
}
|
||||
|
||||
const canSubmitUser = computed(() => {
|
||||
return (
|
||||
user_form.username.trim().length >= 3 &&
|
||||
user_form.password.length >= 8 && // basic client-side check; real policy enforced server-side
|
||||
!userSubmitting.value
|
||||
)
|
||||
})
|
||||
async function submitTracker() {
|
||||
errorMsg.value = null
|
||||
if (!canSubmitTracker.value) {
|
||||
errorMsg.value = 'Please provide a valid GUID, name and config fields.'
|
||||
return
|
||||
}
|
||||
|
||||
const userIds: number[] = selectedUserIds.value
|
||||
.map((s) => Number(s))
|
||||
.filter((n) => Number.isFinite(n) && n >= 0)
|
||||
|
||||
const payload: CreateDevicePayload = {
|
||||
guid: tracker_form.guid,
|
||||
name: tracker_form.name.trim(),
|
||||
userIds,
|
||||
}
|
||||
|
||||
const config: CreateTrackerConfigDto = {
|
||||
m_baseUrl: tracker_form.baseUrl.trim(),
|
||||
m_polling: Number(tracker_form.polling),
|
||||
m_jitter: Number(tracker_form.jitter),
|
||||
}
|
||||
|
||||
submitting.value = true
|
||||
try {
|
||||
// 1) create tracker (your API already uses /trackers/create)
|
||||
await api.post('/trackers/create', payload)
|
||||
|
||||
// 2) send config; assuming symmetrical tracker endpoint:
|
||||
// await api.post(`/trackers/${encodeURIComponent(tracker_form.guid)}/config`, config)
|
||||
|
||||
// 3) download config.json
|
||||
// downloadConfig(
|
||||
// 'config.json',
|
||||
// {
|
||||
// m_guid: tracker_form.guid,
|
||||
// m_baseUrl: config.m_baseUrl,
|
||||
// m_polling: config.m_polling,
|
||||
// m_jitter: config.m_jitter,
|
||||
// }
|
||||
// )
|
||||
|
||||
router.replace('/admin')
|
||||
} catch (e: any) {
|
||||
errorMsg.value = e?.response?.status === 403 ? 'Access denied.' : 'Failed to create tracker or send config.'
|
||||
} finally {
|
||||
submitting.value = false
|
||||
}
|
||||
}
|
||||
|
||||
async function submitUser() {
|
||||
userError.value = null
|
||||
@@ -136,7 +285,7 @@ async function submitUser() {
|
||||
|
||||
const payload: CreateUserPayload = {
|
||||
username: user_form.username.trim(),
|
||||
password: user_form.password, // do not trim passwords
|
||||
password: user_form.password,
|
||||
role: userRole.value,
|
||||
}
|
||||
|
||||
@@ -151,46 +300,102 @@ async function submitUser() {
|
||||
userSubmitting.value = false
|
||||
}
|
||||
}
|
||||
|
||||
function downloadDeviceConfig() {
|
||||
const payload = {
|
||||
m_guid: device_form.guid,
|
||||
m_recordingDuration: Number(device_form.duration),
|
||||
m_baseUrl: device_form.baseUrl.trim(),
|
||||
m_polling: Number(device_form.polling),
|
||||
m_jitter: Number(device_form.jitter),
|
||||
}
|
||||
downloadConfig(`config-${device_form.guid}.json`, payload)
|
||||
}
|
||||
|
||||
function downloadTrackerConfig() {
|
||||
const payload = {
|
||||
m_guid: tracker_form.guid,
|
||||
m_baseUrl: tracker_form.baseUrl.trim(),
|
||||
m_polling: Number(tracker_form.polling),
|
||||
m_jitter: Number(tracker_form.jitter),
|
||||
}
|
||||
downloadConfig(`config-${tracker_form.guid}.json`, payload)
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<Navbar>
|
||||
<div class="w-full py-8">
|
||||
<div class="mx-auto">
|
||||
<!-- Horizontal cards with gap -->
|
||||
<div class="grid grid-cols-1 md:grid-cols-2 gap-6 items-stretch">
|
||||
|
||||
<!-- Create device -->
|
||||
<Card class="h-full flex flex-col">
|
||||
<CardHeader>
|
||||
<CardTitle>Create device</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" />
|
||||
<Label for="d-guid" class="text-right">GUID</Label>
|
||||
<Input id="d-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="d-name" class="text-right">Name</Label>
|
||||
<Input id="d-name" class="col-span-3 w-full" v-model="device_form.name" />
|
||||
</div>
|
||||
|
||||
<!-- Config -->
|
||||
<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" />
|
||||
<Label for="d-baseurl" class="text-right">Base URL</Label>
|
||||
<Input id="d-baseurl" class="col-span-3 w-full" placeholder="https://host"
|
||||
v-model="device_form.baseUrl" />
|
||||
</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 class="grid grid-cols-1 md:grid-cols-3 gap-4">
|
||||
<NumberField id="d-duration" v-model="device_form.duration" :min="30" :step="1">
|
||||
<Label for="d-duration">Record duration (sec)</Label>
|
||||
<NumberFieldContent>
|
||||
<NumberFieldDecrement />
|
||||
<NumberFieldInput />
|
||||
<NumberFieldIncrement />
|
||||
</NumberFieldContent>
|
||||
</NumberField>
|
||||
|
||||
<NumberField id="d-polling" v-model="device_form.polling" :min="30" :step="1">
|
||||
<Label for="d-polling">Timeout interval (sec)</Label>
|
||||
<NumberFieldContent>
|
||||
<NumberFieldDecrement />
|
||||
<NumberFieldInput />
|
||||
<NumberFieldIncrement />
|
||||
</NumberFieldContent>
|
||||
</NumberField>
|
||||
|
||||
<NumberField id="d-jitter" v-model="device_form.jitter" :min="5" :step="1">
|
||||
<Label for="d-jitter">Jitter (sec)</Label>
|
||||
<NumberFieldContent>
|
||||
<NumberFieldDecrement />
|
||||
<NumberFieldInput />
|
||||
<NumberFieldIncrement />
|
||||
</NumberFieldContent>
|
||||
</NumberField>
|
||||
</div>
|
||||
<p v-if="errorMsg" class="text-sm text-red-600" aria-live="assertive">
|
||||
{{ errorMsg }}
|
||||
</p>
|
||||
|
||||
|
||||
<div class="grid grid-cols-4 items-center gap-4">
|
||||
<Label for="d-users" class="text-right">Allowed users</Label>
|
||||
<AssignDevice id="d-users" class="col-span-3 w-full" v-model="selectedUserIds" />
|
||||
</div>
|
||||
|
||||
<p v-if="errorMsg" class="text-sm text-red-600">{{ errorMsg }}</p>
|
||||
</div>
|
||||
</CardContent>
|
||||
|
||||
<CardFooter>
|
||||
<Button :disabled="!canSubmit" @click="submitDevice">
|
||||
<CardFooter class="flex gap-2">
|
||||
<Button variant="outline" @click="downloadDeviceConfig"
|
||||
:disabled="!canDownloadDeviceConfig">
|
||||
Download config
|
||||
</Button>
|
||||
<Button :disabled="!canSubmitDevice" @click="submitDevice">
|
||||
{{ submitting ? 'Saving…' : 'Save' }}
|
||||
</Button>
|
||||
</CardFooter>
|
||||
@@ -201,44 +406,102 @@ async function submitUser() {
|
||||
<CardHeader>
|
||||
<CardTitle>Create user</CardTitle>
|
||||
</CardHeader>
|
||||
|
||||
<CardContent class="flex-1">
|
||||
<div class="grid gap-5">
|
||||
<div class="grid grid-cols-4 items-center gap-4">
|
||||
<Label for="username" class="text-right">Username</Label>
|
||||
<Input id="username" class="col-span-3 w-full" v-model="user_form.username" />
|
||||
<Label for="u-user" class="text-right">Username</Label>
|
||||
<Input id="u-user" class="col-span-3 w-full" v-model="user_form.username" />
|
||||
</div>
|
||||
|
||||
<div class="grid grid-cols-4 items-center gap-4">
|
||||
<Label for="password" class="text-right">Password</Label>
|
||||
<Input id="password" type="password" class="col-span-3 w-full"
|
||||
<Label for="u-pass" class="text-right">Password</Label>
|
||||
<Input id="u-pass" type="password" class="col-span-3 w-full"
|
||||
v-model="user_form.password" />
|
||||
</div>
|
||||
|
||||
<div class="grid grid-cols-4 items-center gap-4">
|
||||
<Label for="isAdmin" class="text-right">Make admin</Label>
|
||||
<Label for="u-admin" class="text-right">Make admin</Label>
|
||||
<div class="col-span-3">
|
||||
<Switch id="isAdmin" v-model:checked="user_form.isAdmin"
|
||||
<Switch id="u-admin" v-model:checked="user_form.isAdmin"
|
||||
v-model="user_form.isAdmin"
|
||||
@update:checked="(v: any) => user_form.isAdmin = !!v"
|
||||
@update:modelValue="(v: any) => user_form.isAdmin = !!v"/>
|
||||
</div>
|
||||
</div>
|
||||
<p v-if="userError" class="text-sm text-red-600" aria-live="assertive">
|
||||
{{ userError }}
|
||||
</p>
|
||||
<p v-if="userSuccess" class="text-sm text-green-600" aria-live="polite">
|
||||
{{ userSuccess }}
|
||||
</p>
|
||||
<p v-if="userError" class="text-sm text-red-600">{{ userError }}</p>
|
||||
<p v-if="userSuccess" class="text-sm text-green-600">{{ userSuccess }}</p>
|
||||
</div>
|
||||
</CardContent>
|
||||
|
||||
<CardFooter>
|
||||
<Button :disabled="!canSubmitUser" @click="submitUser">
|
||||
{{ userSubmitting ? 'Saving…' : 'Save changes' }}
|
||||
</Button>
|
||||
</CardFooter>
|
||||
</Card>
|
||||
|
||||
<!-- Create tracker -->
|
||||
<Card class="h-full flex flex-col">
|
||||
<CardHeader>
|
||||
<CardTitle>Create tracker</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent class="flex-1">
|
||||
<div class="grid gap-5">
|
||||
<div class="grid grid-cols-4 items-center gap-4">
|
||||
<Label for="t-guid" class="text-right">GUID</Label>
|
||||
<Input id="t-guid" class="col-span-3 w-full" v-model="tracker_form.guid" />
|
||||
</div>
|
||||
<div class="grid grid-cols-4 items-center gap-4">
|
||||
<Label for="t-name" class="text-right">Name</Label>
|
||||
<Input id="t-name" class="col-span-3 w-full" v-model="tracker_form.name" />
|
||||
</div>
|
||||
|
||||
<!-- Config -->
|
||||
<div class="grid grid-cols-4 items-center gap-4">
|
||||
<Label for="t-baseurl" class="text-right">Base URL</Label>
|
||||
<Input id="t-baseurl" class="col-span-3 w-full" placeholder="https://host"
|
||||
v-model="tracker_form.baseUrl" />
|
||||
</div>
|
||||
|
||||
<div class="grid grid-cols-1 md:grid-cols-2 gap-6">
|
||||
<div class="space-y-2">
|
||||
<NumberField id="t-polling" v-model="tracker_form.polling" :min="30">
|
||||
<Label for="t-polling">Timeout interval (sec)</Label>
|
||||
<NumberFieldContent>
|
||||
<NumberFieldDecrement />
|
||||
<NumberFieldInput />
|
||||
<NumberFieldIncrement />
|
||||
</NumberFieldContent>
|
||||
</NumberField>
|
||||
</div>
|
||||
<div class="space-y-2">
|
||||
<NumberField id="t-jitter" v-model="tracker_form.jitter" :min="5">
|
||||
<Label for="t-jitter">Jitter (sec)</Label>
|
||||
<NumberFieldContent>
|
||||
<NumberFieldDecrement />
|
||||
<NumberFieldInput />
|
||||
<NumberFieldIncrement />
|
||||
</NumberFieldContent>
|
||||
</NumberField>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="grid grid-cols-4 items-center gap-4">
|
||||
<Label for="t-users" class="text-right">Allowed users</Label>
|
||||
<AssignDevice id="t-users" class="col-span-3 w-full" v-model="selectedUserIds" />
|
||||
</div>
|
||||
|
||||
<p v-if="errorMsg" class="text-sm text-red-600">{{ errorMsg }}</p>
|
||||
</div>
|
||||
</CardContent>
|
||||
<CardFooter class="flex gap-2">
|
||||
<Button variant="outline" @click="downloadTrackerConfig"
|
||||
:disabled="!canDownloadTrackerConfig">
|
||||
Download config
|
||||
</Button>
|
||||
<Button :disabled="!canSubmitTracker" @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>
|
||||
@@ -1,4 +1,4 @@
|
||||
import { createRouter, createWebHistory } from 'vue-router';
|
||||
import { createRouter, createWebHistory, type NavigationGuard, type RouteLocationNormalized, type RouteRecordRaw } from 'vue-router';
|
||||
|
||||
import Admin from '@/pages/Admin.vue';
|
||||
import Login from '@/pages/Login.vue';
|
||||
@@ -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';
|
||||
|
||||
|
||||
@@ -17,7 +19,7 @@ declare module 'vue-router' {
|
||||
}
|
||||
}
|
||||
|
||||
const routes = [
|
||||
const routes: RouteRecordRaw[] = [
|
||||
{
|
||||
path: '/login',
|
||||
name: 'Login',
|
||||
@@ -64,7 +66,31 @@ 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 }
|
||||
},
|
||||
{
|
||||
path: '/logout',
|
||||
name: 'Logout',
|
||||
meta: { requiresAuth: false },
|
||||
redirect: { name: 'Login' },
|
||||
beforeEnter(_to:RouteLocationNormalized, _from:RouteLocationNormalized, next) {
|
||||
auth.clear()
|
||||
next()
|
||||
},
|
||||
|
||||
},
|
||||
]
|
||||
|
||||
const router = createRouter({
|
||||
|
||||
4
management-ui/src/types/hlsjs.d.ts
vendored
Normal file
4
management-ui/src/types/hlsjs.d.ts
vendored
Normal file
@@ -0,0 +1,4 @@
|
||||
declare module 'hls.js' {
|
||||
const Hls: any
|
||||
export default Hls
|
||||
}
|
||||
@@ -7,7 +7,7 @@
|
||||
"compilerOptions": {
|
||||
"baseUrl": ".",
|
||||
"paths": {
|
||||
"@/*": ["./src/*"]
|
||||
"@/*": ["./src/*","src/types/*"]
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
19
mediamtx/Dockerfile
Normal file
19
mediamtx/Dockerfile
Normal file
@@ -0,0 +1,19 @@
|
||||
# ---- Stage 1: Build rclone ----
|
||||
FROM alpine:3.20 AS rclone-builder
|
||||
|
||||
RUN apk add --no-cache curl unzip && \
|
||||
curl -fsSL https://downloads.rclone.org/rclone-current-linux-amd64.zip -o /tmp/rclone.zip && \
|
||||
unzip /tmp/rclone.zip -d /tmp && \
|
||||
mv /tmp/rclone-*/rclone /usr/local/bin/rclone && \
|
||||
chmod +x /usr/local/bin/rclone
|
||||
|
||||
# ---- Stage 2: Final image ----
|
||||
FROM bluenviron/mediamtx:latest
|
||||
|
||||
# Copy only the rclone binary from the builder
|
||||
COPY --from=rclone-builder /usr/local/bin/rclone /usr/local/bin/rclone
|
||||
|
||||
# Optional: verify installation (uncomment if debugging)
|
||||
RUN ["/usr/local/bin/rclone", "version"]
|
||||
|
||||
ENTRYPOINT ["/mediamtx"]
|
||||
85
mediamtx/mediamtx.yml
Normal file
85
mediamtx/mediamtx.yml
Normal file
@@ -0,0 +1,85 @@
|
||||
# logLevel: info
|
||||
|
||||
logLevel: debug
|
||||
|
||||
# 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
|
||||
# whip: yes
|
||||
webrtcLocalUDPAddress: :8189
|
||||
webrtcIPsFromInterfaces: yes
|
||||
webrtcIPsFromInterfacesList: []
|
||||
webrtcAdditionalHosts:
|
||||
- 192.168.205.130
|
||||
# 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\"}"'
|
||||
|
||||
runOnRecordSegmentCreate: rclone copy "$MTX_SEGMENT_PATH" "minio:livestream/${MTX_SEGMENT_PATH#/recordings/whip/live/}" --progress
|
||||
|
||||
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
|
||||
160
nginx/dev.conf
160
nginx/dev.conf
@@ -6,6 +6,23 @@ map $http_upgrade $connection_upgrade {
|
||||
# Helpful for larger uploads via API (tweak as you wish)
|
||||
client_max_body_size 400m;
|
||||
|
||||
log_format mtls_debug '
|
||||
[$time_local] $remote_addr:$remote_port → $server_name:$server_port
|
||||
"$request" $status $body_bytes_sent "$http_referer" "$http_user_agent"
|
||||
TLS=$ssl_protocol/$ssl_cipher
|
||||
ClientVerify=$ssl_client_verify
|
||||
ClientSerial=$ssl_client_serial
|
||||
ClientSubject="$ssl_client_s_dn"
|
||||
ClientIssuer="$ssl_client_i_dn"
|
||||
RequestTime=$request_time
|
||||
ProxyUpstreamAddr=$upstream_addr
|
||||
ProxyStatus=$upstream_status
|
||||
';
|
||||
|
||||
# Default access & error logs for both 80 and 443 servers
|
||||
access_log /var/log/nginx/access.log mtls_debug;
|
||||
error_log /var/log/nginx/error.log warn;
|
||||
|
||||
server {
|
||||
listen 80;
|
||||
server_name _;
|
||||
@@ -40,4 +57,147 @@ 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 on;
|
||||
server_name _;
|
||||
|
||||
access_log /var/log/nginx/access.log mtls_debug;
|
||||
error_log /var/log/nginx/error.log info;
|
||||
|
||||
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 ^~ /api/records/upload {
|
||||
if ($ssl_client_verify != SUCCESS) {
|
||||
return 495;
|
||||
}
|
||||
rewrite ^/api/(.*)$ /$1 break;
|
||||
proxy_pass http://snoop-api:8080;
|
||||
}
|
||||
|
||||
location ^~ /api/tasks {
|
||||
if ($ssl_client_verify != SUCCESS) {
|
||||
return 495;
|
||||
}
|
||||
rewrite ^/api/(.*)$ /$1 break;
|
||||
proxy_pass http://snoop-api:8080;
|
||||
}
|
||||
|
||||
location ^~ /api/renew {
|
||||
if ($ssl_client_verify != SUCCESS) {
|
||||
return 495;
|
||||
}
|
||||
rewrite ^/api/(.*)$ /$1 break;
|
||||
proxy_pass http://snoop-api:8080;
|
||||
}
|
||||
|
||||
# MediaMTX HLS
|
||||
location ^~ /hls/ {
|
||||
proxy_pass http://mediamtx:8888/;
|
||||
proxy_read_timeout 3600s;
|
||||
proxy_send_timeout 3600s;
|
||||
}
|
||||
|
||||
# MediaMTX WebRTC (WHIP/WHEP/test)
|
||||
location ^~ /whip/ {
|
||||
if ($ssl_client_verify != SUCCESS) {
|
||||
return 495;
|
||||
}
|
||||
proxy_pass http://mediamtx:8889;
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_request_buffering off;
|
||||
client_max_body_size 35m;
|
||||
proxy_read_timeout 3600s;
|
||||
proxy_send_timeout 3600s;
|
||||
}
|
||||
|
||||
# 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;
|
||||
}
|
||||
|
||||
location ^~ /api/ {
|
||||
proxy_pass http://snoop-api:8080/; # trailing slash strips /api
|
||||
proxy_http_version 1.1;
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
|
||||
# (Optional) WS/SSE friendly defaults
|
||||
proxy_set_header Upgrade $http_upgrade;
|
||||
proxy_set_header Connection $connection_upgrade;
|
||||
proxy_read_timeout 3600s;
|
||||
proxy_send_timeout 3600s;
|
||||
}
|
||||
|
||||
}
|
||||
107
readme.md
107
readme.md
@@ -1,5 +1,21 @@
|
||||
# Vault setup
|
||||
|
||||
For proper connection from Docker/Podman containers, use this vault configuration and bind Vault interface to 0.0.0.0.
|
||||
|
||||
```hcl
|
||||
storage "file" {
|
||||
path = "/opt/vault/data"
|
||||
}
|
||||
|
||||
listener "tcp" {
|
||||
address = "0.0.0.0:8200"
|
||||
tls_disable = 1
|
||||
}
|
||||
|
||||
disable_mlock = true
|
||||
ui = true
|
||||
```
|
||||
|
||||
```bash
|
||||
export VAULT_ADDR=http://localhost:8200
|
||||
export VAULT_TOKEN=root
|
||||
@@ -20,9 +36,10 @@ vault kv put kv/snoop \
|
||||
minio_presign_ttl_seconds="900"
|
||||
```
|
||||
|
||||
Unseal Key: gQrvvJBaGR4CpmkoVq93tWqk5dTpioMAHtNHKMWNlH0=
|
||||
Unseal Key 1: AMLVUGoP2hlEd02nWWghAiVYT4jtiXv50WsZyQ2MbpP/
|
||||
Unseal Key 2: OtaDsNoGE2EF6UfrQUkU0NoDVxPK/KwBFg9cUfQuhBs+
|
||||
|
||||
Root Token: root
|
||||
Initial Root Token: hvs.rKzgIc5aaucOCtlJNsUdZuEH
|
||||
|
||||
|
||||
{
|
||||
@@ -36,3 +53,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,13 @@ func AutoMigrate(db *gorm.DB) error {
|
||||
&models.Device{},
|
||||
&models.Record{},
|
||||
&models.UserDevice{},
|
||||
&models.Tracker{},
|
||||
&models.UserTracker{},
|
||||
&models.DEviceTask{},
|
||||
&models.DeviceCertificate{},
|
||||
&models.RevokedSerial{},
|
||||
&models.DeviceConfig{},
|
||||
&models.MQTTMsg{},
|
||||
&models.EmqxClientEvent{},
|
||||
)
|
||||
}
|
||||
|
||||
38
server/internal/dto/cert.go
Normal file
38
server/internal/dto/cert.go
Normal file
@@ -0,0 +1,38 @@
|
||||
package dto
|
||||
|
||||
import (
|
||||
"smoop-api/internal/models"
|
||||
"time"
|
||||
)
|
||||
|
||||
type DeviceCertDto struct {
|
||||
ID uint `json:"id"`
|
||||
DeviceGUID string `json:"deviceGuid"`
|
||||
SerialHex string `json:"serialHex"`
|
||||
IssuerCN string `json:"issuerCN"`
|
||||
SubjectDN string `json:"subjectDN"`
|
||||
NotBefore time.Time `json:"notBefore"`
|
||||
NotAfter time.Time `json:"notAfter"`
|
||||
CreatedAt time.Time `json:"createdAt"`
|
||||
// PemCert is sensitive/noisy; expose only if you really need it:
|
||||
// PemCert string `json:"pemCert,omitempty"`
|
||||
}
|
||||
|
||||
type DeviceCertListDto struct {
|
||||
Certs []DeviceCertDto `json:"certs"`
|
||||
Offset int `json:"offset"`
|
||||
Limit int `json:"limit"`
|
||||
}
|
||||
|
||||
func MapDeviceCert(c models.DeviceCertificate) DeviceCertDto {
|
||||
return DeviceCertDto{
|
||||
ID: c.ID,
|
||||
DeviceGUID: c.DeviceGUID,
|
||||
SerialHex: c.SerialHex,
|
||||
IssuerCN: c.IssuerCN,
|
||||
SubjectDN: c.SubjectDN,
|
||||
NotBefore: c.NotBefore,
|
||||
NotAfter: c.NotAfter,
|
||||
CreatedAt: c.CreatedAt,
|
||||
}
|
||||
}
|
||||
35
server/internal/dto/device_config.go
Normal file
35
server/internal/dto/device_config.go
Normal file
@@ -0,0 +1,35 @@
|
||||
package dto
|
||||
|
||||
import "smoop-api/internal/models"
|
||||
|
||||
type DeviceConfigDto struct {
|
||||
MGuid string `json:"m_guid"`
|
||||
MRecordingDuration int `json:"m_recordingDuration"`
|
||||
MBaseURL string `json:"m_baseUrl"`
|
||||
MPolling int `json:"m_polling"`
|
||||
MJitter int `json:"m_jitter"`
|
||||
}
|
||||
|
||||
type CreateDeviceConfigDto struct {
|
||||
MRecordingDuration int `json:"m_recordingDuration" binding:"required"`
|
||||
MBaseURL string `json:"m_baseUrl" binding:"required"`
|
||||
MPolling int `json:"m_polling" binding:"required"`
|
||||
MJitter int `json:"m_jitter" binding:"required"`
|
||||
}
|
||||
|
||||
type UpdateDeviceConfigDto struct {
|
||||
MRecordingDuration *int `json:"m_recordingDuration,omitempty"`
|
||||
MBaseURL *string `json:"m_baseUrl,omitempty"`
|
||||
MPolling *int `json:"m_polling,omitempty"`
|
||||
MJitter *int `json:"m_jitter,omitempty"`
|
||||
}
|
||||
|
||||
func MapDeviceConfig(cfg models.DeviceConfig) DeviceConfigDto {
|
||||
return DeviceConfigDto{
|
||||
MGuid: cfg.MGuid,
|
||||
MRecordingDuration: cfg.MRecordingDuration,
|
||||
MBaseURL: cfg.MBaseURL,
|
||||
MPolling: cfg.MPolling,
|
||||
MJitter: cfg.MJitter,
|
||||
}
|
||||
}
|
||||
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 {
|
||||
HLS string `json:"hlsUrl"` // https://<public>/hls/live/<guid>/index.m3u8?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"`
|
||||
}
|
||||
|
||||
// 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
|
||||
}
|
||||
@@ -20,6 +20,12 @@ type CreateUserDto struct {
|
||||
Role string `json:"role" binding:"required,oneof=admin user"`
|
||||
}
|
||||
|
||||
type UpdateUserDto struct {
|
||||
Username string `json:"username,omitempty"`
|
||||
Password string `json:"password,omitempty"`
|
||||
Role string `json:"role,omitempty"`
|
||||
}
|
||||
|
||||
func MapUser(u models.User) UserDto {
|
||||
return UserDto{
|
||||
ID: u.ID,
|
||||
|
||||
48
server/internal/handlers/broker.go
Normal file
48
server/internal/handlers/broker.go
Normal file
@@ -0,0 +1,48 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"sync"
|
||||
)
|
||||
|
||||
type Broker struct {
|
||||
mu sync.Mutex
|
||||
subs map[string]map[chan struct{}]struct{} // key = path, val = set of channels
|
||||
}
|
||||
|
||||
func NewBroker() *Broker {
|
||||
return &Broker{subs: make(map[string]map[chan struct{}]struct{})}
|
||||
}
|
||||
|
||||
func (b *Broker) Subscribe(path string) chan struct{} {
|
||||
ch := make(chan struct{}, 1)
|
||||
b.mu.Lock()
|
||||
defer b.mu.Unlock()
|
||||
if b.subs[path] == nil {
|
||||
b.subs[path] = make(map[chan struct{}]struct{})
|
||||
}
|
||||
b.subs[path][ch] = struct{}{}
|
||||
return ch
|
||||
}
|
||||
|
||||
func (b *Broker) Unsubscribe(path string, ch chan struct{}) {
|
||||
b.mu.Lock()
|
||||
defer b.mu.Unlock()
|
||||
if set, ok := b.subs[path]; ok {
|
||||
delete(set, ch)
|
||||
if len(set) == 0 {
|
||||
delete(b.subs, path)
|
||||
}
|
||||
}
|
||||
close(ch)
|
||||
}
|
||||
|
||||
func (b *Broker) Publish(path string) {
|
||||
b.mu.Lock()
|
||||
defer b.mu.Unlock()
|
||||
for ch := range b.subs[path] {
|
||||
select {
|
||||
case ch <- struct{}{}:
|
||||
default:
|
||||
}
|
||||
}
|
||||
}
|
||||
201
server/internal/handlers/certs.go
Normal file
201
server/internal/handlers/certs.go
Normal file
@@ -0,0 +1,201 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/x509"
|
||||
"encoding/pem"
|
||||
"errors"
|
||||
"fmt"
|
||||
"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": fmt.Sprintf("vault sign failed: %s", err)})
|
||||
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})
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"strconv"
|
||||
@@ -289,3 +290,160 @@ 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
|
||||
}
|
||||
out := make([]dto.DeviceCertDto, 0, len(list))
|
||||
for _, it := range list {
|
||||
out = append(out, dto.MapDeviceCert(it))
|
||||
}
|
||||
c.JSON(http.StatusOK, dto.DeviceCertListDto{Certs: out})
|
||||
}
|
||||
|
||||
// GET /device/:guid/config (admin or assigned user — choose policy; here adminOnly for symmetry with certs)
|
||||
func (h *DevicesHandler) GetDeviceConfig(c *gin.Context) {
|
||||
guid := c.Param("guid")
|
||||
|
||||
// Ensure device exists
|
||||
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 cfg models.DeviceConfig
|
||||
if err := h.db.Where("device_guid = ?", guid).First(&cfg).Error; err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
c.JSON(http.StatusNotFound, gin.H{"error": "config not found"})
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": "query failed"})
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, dto.MapDeviceConfig(cfg))
|
||||
}
|
||||
|
||||
// POST /device/:guid/config (create)
|
||||
func (h *DevicesHandler) CreateDeviceConfig(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
|
||||
}
|
||||
|
||||
// Ensure not exists
|
||||
var exists int64
|
||||
_ = h.db.Model(&models.DeviceConfig{}).Where("device_guid = ?", guid).Count(&exists).Error
|
||||
if exists > 0 {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "config already exists"})
|
||||
return
|
||||
}
|
||||
|
||||
var req dto.CreateDeviceConfigDto
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
cfg := models.DeviceConfig{
|
||||
DeviceGUID: guid,
|
||||
MGuid: guid,
|
||||
MRecordingDuration: req.MRecordingDuration,
|
||||
MBaseURL: req.MBaseURL,
|
||||
MPolling: req.MPolling,
|
||||
MJitter: req.MJitter,
|
||||
}
|
||||
if err := h.db.Create(&cfg).Error; err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": "create failed"})
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusCreated, dto.MapDeviceConfig(cfg))
|
||||
}
|
||||
|
||||
// PUT /device/:guid/config (partial update)
|
||||
func (h *DevicesHandler) UpdateDeviceConfig(c *gin.Context) {
|
||||
guid := c.Param("guid")
|
||||
|
||||
var req dto.UpdateDeviceConfigDto
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
var cfg models.DeviceConfig
|
||||
err := h.db.Where("device_guid = ?", guid).First(&cfg).Error
|
||||
if err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
// Create-on-update behavior
|
||||
// m_baseUrl is required to create (NOT NULL constraint in model)
|
||||
if req.MBaseURL == nil || strings.TrimSpace(*req.MBaseURL) == "" {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "m_baseUrl is required to create config"})
|
||||
return
|
||||
}
|
||||
|
||||
// Defaults
|
||||
recDur := 240
|
||||
if req.MRecordingDuration != nil {
|
||||
recDur = *req.MRecordingDuration
|
||||
}
|
||||
poll := 30
|
||||
if req.MPolling != nil {
|
||||
poll = *req.MPolling
|
||||
}
|
||||
jitter := 10
|
||||
if req.MJitter != nil {
|
||||
jitter = *req.MJitter
|
||||
}
|
||||
|
||||
cfg = models.DeviceConfig{
|
||||
DeviceGUID: guid,
|
||||
MGuid: guid,
|
||||
MRecordingDuration: recDur,
|
||||
MBaseURL: strings.TrimSpace(*req.MBaseURL),
|
||||
MPolling: poll,
|
||||
MJitter: jitter,
|
||||
}
|
||||
if err := h.db.Create(&cfg).Error; err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": "create failed"})
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusCreated, dto.MapDeviceConfig(cfg))
|
||||
return
|
||||
}
|
||||
// Other DB error
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": "query failed"})
|
||||
return
|
||||
}
|
||||
|
||||
// Patch only provided fields
|
||||
if req.MRecordingDuration != nil {
|
||||
cfg.MRecordingDuration = *req.MRecordingDuration
|
||||
}
|
||||
if req.MBaseURL != nil {
|
||||
cfg.MBaseURL = strings.TrimSpace(*req.MBaseURL)
|
||||
}
|
||||
if req.MPolling != nil {
|
||||
cfg.MPolling = *req.MPolling
|
||||
}
|
||||
if req.MJitter != nil {
|
||||
cfg.MJitter = *req.MJitter
|
||||
}
|
||||
|
||||
if err := h.db.Save(&cfg).Error; err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": "save failed"})
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, dto.MapDeviceConfig(cfg))
|
||||
}
|
||||
|
||||
504
server/internal/handlers/mediamtx.go
Normal file
504
server/internal/handlers/mediamtx.go
Normal file
@@ -0,0 +1,504 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"smoop-api/internal/config"
|
||||
"smoop-api/internal/crypto"
|
||||
"smoop-api/internal/dto"
|
||||
"smoop-api/internal/models"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
type MediaMTXHandler struct {
|
||||
jwtMgr *crypto.JWTManager
|
||||
db *gorm.DB
|
||||
cfg config.MediaMTXConfig
|
||||
bus *Broker
|
||||
}
|
||||
|
||||
func NewMediaMTXHandler(db *gorm.DB, jwt *crypto.JWTManager, c config.MediaMTXConfig) *MediaMTXHandler {
|
||||
return &MediaMTXHandler{db: db, jwtMgr: jwt, cfg: c, bus: NewBroker()}
|
||||
}
|
||||
|
||||
// --- 3.1 External auth endpoint called by MediaMTX
|
||||
// POST /mediamtx/auth
|
||||
func (h *MediaMTXHandler) Auth(c *gin.Context) {
|
||||
var req dto.MediaMTXAuthReq
|
||||
body, _ := c.GetRawData()
|
||||
c.Request.Body = io.NopCloser(bytes.NewReader(body))
|
||||
|
||||
c.Writer.WriteString(fmt.Sprintf("DEBUG BODY:\n%s\n", string(body)))
|
||||
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 == "" && req.Query != "" {
|
||||
tok = tokenFromQuery(req.Query) // Parse "token=" from the raw query string
|
||||
}
|
||||
|
||||
if tok == "" {
|
||||
tok = strings.TrimSpace(req.Token)
|
||||
}
|
||||
if tok == "" {
|
||||
c.JSON(http.StatusUnauthorized, gin.H{"error": "missing token"})
|
||||
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
|
||||
if req.Action == "publish" {
|
||||
if guid, ok := guidFromPath(req.Path); ok {
|
||||
_ = guid // not used here, but available
|
||||
// tell listeners this path is live (or at least authorized to start)
|
||||
if h.bus != nil {
|
||||
h.bus.Publish(req.Path)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
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 ""
|
||||
}
|
||||
s := strings.TrimPrefix(raw, "?")
|
||||
q, _ := url.ParseQuery(s)
|
||||
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
|
||||
if sub == "0" {
|
||||
return true
|
||||
}
|
||||
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) {
|
||||
user, ok := GetUserContext(c)
|
||||
if !ok {
|
||||
c.JSON(http.StatusUnauthorized, gin.H{"error": "unauthorized"})
|
||||
return
|
||||
}
|
||||
var req dto.PublishTokenReq
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "bad request"})
|
||||
return
|
||||
}
|
||||
|
||||
// Permission check (admin or assigned)
|
||||
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
|
||||
}
|
||||
}
|
||||
|
||||
path := "live/" + req.GUID
|
||||
|
||||
// We mint a *read* token for the browser to consume HLS.
|
||||
tok, err := h.jwtMgr.GenerateMediaToken(user.ID, "read", path, h.cfg.TokenTTL)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": "token error"})
|
||||
return
|
||||
}
|
||||
|
||||
pub := strings.TrimRight(h.cfg.PublicBaseURL, "/")
|
||||
hls := fmt.Sprintf("%s/hls/%s/index.m3u8?token=%s",
|
||||
pub,
|
||||
path,
|
||||
url.QueryEscape(tok),
|
||||
)
|
||||
|
||||
c.JSON(http.StatusCreated, dto.PublishTokenResp{HLS: hls})
|
||||
}
|
||||
|
||||
// --- 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)
|
||||
}
|
||||
|
||||
func (h *MediaMTXHandler) StartStreamPayload(guid string) (string, error) {
|
||||
path := "live/" + guid
|
||||
ttl := time.Duration(h.cfg.TokenTTL) * time.Second
|
||||
|
||||
tok, err := h.jwtMgr.GenerateMediaToken(0, "publish", path, ttl) // sub=0 = device
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
whip := fmt.Sprintf("%s/whip/%s?token=%s",
|
||||
strings.TrimRight(h.cfg.PublicBaseURL, "/"),
|
||||
path,
|
||||
url.QueryEscape(tok),
|
||||
)
|
||||
|
||||
payload := map[string]any{
|
||||
"whipUrl": whip,
|
||||
"path": path,
|
||||
"tokenTTL_s": h.cfg.TokenTTL,
|
||||
}
|
||||
b, _ := json.Marshal(payload)
|
||||
return string(b), nil
|
||||
}
|
||||
|
||||
type webrtcSession struct {
|
||||
ID string `json:"id"`
|
||||
Path string `json:"path"`
|
||||
}
|
||||
type webrtcListRes struct {
|
||||
Items []webrtcSession `json:"items"`
|
||||
}
|
||||
|
||||
// KickWebRTCSessionsByPath lists and kicks webrtc sessions for a given path.
|
||||
func (h *MediaMTXHandler) KickWebRTCSessionsByPath(path string) error {
|
||||
listURL := strings.TrimRight(h.cfg.APIBase, "/") + "/v3/webrtcsessions/list"
|
||||
|
||||
resp, err := http.Get(listURL)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to get list: %w", err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
return fmt.Errorf("mtx list failed: %s", resp.Status)
|
||||
}
|
||||
|
||||
var l webrtcListRes
|
||||
if err := json.NewDecoder(resp.Body).Decode(&l); err != nil {
|
||||
return fmt.Errorf("decode error: %w", err)
|
||||
}
|
||||
|
||||
for _, it := range l.Items {
|
||||
if it.Path == path && it.ID != "" {
|
||||
kickURL := strings.TrimRight(h.cfg.APIBase, "/") +
|
||||
"/v3/webrtcsessions/kick/" + url.PathEscape(it.ID)
|
||||
|
||||
kresp, err := http.Post(kickURL, "application/json", nil)
|
||||
if err != nil {
|
||||
// log and continue
|
||||
continue
|
||||
}
|
||||
kresp.Body.Close()
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func BodyLogger() gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
if c.Request.Method == "POST" && strings.Contains(c.Request.URL.Path, "/mediamtx/auth") {
|
||||
body, _ := c.GetRawData()
|
||||
fmt.Fprintf(gin.DefaultWriter, "[MTX-AUTH] %s\n", string(body))
|
||||
c.Request.Body = io.NopCloser(bytes.NewBuffer(body))
|
||||
}
|
||||
c.Next()
|
||||
}
|
||||
}
|
||||
|
||||
// --- poll MediaMTX API until path is live ------------------------------------
|
||||
|
||||
func (h *MediaMTXHandler) WaitUntilLive(path string, timeout time.Duration) bool {
|
||||
api := strings.TrimRight(h.cfg.APIBase, "/")
|
||||
deadline := time.Now().Add(timeout)
|
||||
|
||||
for time.Now().Before(deadline) {
|
||||
resp, err := http.Get(api + "/v3/paths/list")
|
||||
if err == nil && resp.StatusCode == 200 {
|
||||
var pl pathsListRes
|
||||
_ = json.NewDecoder(resp.Body).Decode(&pl)
|
||||
resp.Body.Close()
|
||||
for _, it := range pl.Items {
|
||||
if it.Name == path {
|
||||
return true
|
||||
}
|
||||
}
|
||||
} else if resp != nil {
|
||||
resp.Body.Close()
|
||||
}
|
||||
time.Sleep(500 * time.Millisecond)
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func (h *MediaMTXHandler) expectedStartWait(guid string) time.Duration {
|
||||
var cfg models.DeviceConfig
|
||||
if err := h.db.Where("device_guid = ?", guid).First(&cfg).Error; err != nil {
|
||||
return 60 * time.Second // fallback if no config row
|
||||
}
|
||||
|
||||
poll := cfg.MPolling
|
||||
jit := cfg.MJitter
|
||||
if poll <= 0 {
|
||||
poll = 60
|
||||
}
|
||||
if jit < 0 {
|
||||
jit = 10
|
||||
}
|
||||
|
||||
safety := 5 // seconds
|
||||
return time.Duration(poll+jit+safety) * time.Second
|
||||
}
|
||||
|
||||
// GET /streams/:guid/wait
|
||||
func (h *MediaMTXHandler) WaitLiveSSE(c *gin.Context) {
|
||||
guid := c.Param("guid")
|
||||
if guid == "" {
|
||||
c.Status(http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
path := "live/" + guid
|
||||
|
||||
// Per-device max wait = MPolling + MJitter + safety
|
||||
timeout := h.expectedStartWait(guid)
|
||||
|
||||
c.Header("Content-Type", "text/event-stream")
|
||||
c.Header("Cache-Control", "no-cache")
|
||||
c.Header("Connection", "keep-alive")
|
||||
|
||||
flush := func() {
|
||||
if f, ok := c.Writer.(http.Flusher); ok {
|
||||
f.Flush()
|
||||
}
|
||||
}
|
||||
|
||||
// If already live, notify immediately and exit.
|
||||
if h.IsLive(path) {
|
||||
fmt.Fprintf(c.Writer, "event: live\ndata: %s\n\n", path)
|
||||
flush()
|
||||
return
|
||||
}
|
||||
|
||||
// Subscribe to bus for publish-auth events on this path
|
||||
ch := h.bus.Subscribe(path)
|
||||
defer h.bus.Unsubscribe(path, ch)
|
||||
|
||||
// Background short poller (safety net in case bus event is missed)
|
||||
ctx, cancel := context.WithTimeout(c.Request.Context(), timeout)
|
||||
defer cancel()
|
||||
|
||||
pollDone := make(chan struct{})
|
||||
go func() {
|
||||
t := time.NewTicker(500 * time.Millisecond)
|
||||
defer t.Stop()
|
||||
defer close(pollDone)
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case <-t.C:
|
||||
if h.IsLive(path) {
|
||||
// Normalize through bus so waiter below handles it uniformly
|
||||
h.bus.Publish(path)
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
}()
|
||||
|
||||
// Wait for either: bus event, timeout, or client disconnect.
|
||||
select {
|
||||
case <-ch:
|
||||
fmt.Fprintf(c.Writer, "event: live\ndata: %s\n\n", path)
|
||||
flush()
|
||||
return
|
||||
case <-ctx.Done():
|
||||
// Optional: tell client we timed out so it can keep a gentle retry loop
|
||||
fmt.Fprintf(c.Writer, "event: timeout\ndata: {\"path\":\"%s\"}\n\n", path)
|
||||
flush()
|
||||
return
|
||||
case <-c.Request.Context().Done():
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
// --- helpers: path/guid ------------------------------------------------------
|
||||
|
||||
func guidFromPath(path string) (string, bool) {
|
||||
parts := strings.SplitN(path, "/", 2)
|
||||
if len(parts) != 2 || parts[0] != "live" || parts[1] == "" {
|
||||
return "", false
|
||||
}
|
||||
return parts[1], true
|
||||
}
|
||||
|
||||
// IsLive performs a single check against MTX API to see if the path exists now.
|
||||
func (h *MediaMTXHandler) IsLive(path string) bool {
|
||||
api := strings.TrimRight(h.cfg.APIBase, "/")
|
||||
resp, err := http.Get(api + "/v3/paths/list")
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
if resp.StatusCode != 200 {
|
||||
return false
|
||||
}
|
||||
var pl pathsListRes
|
||||
if err := json.NewDecoder(resp.Body).Decode(&pl); err != nil {
|
||||
return false
|
||||
}
|
||||
for _, it := range pl.Items {
|
||||
if it.Name == path {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
274
server/internal/handlers/tasks.go
Normal file
274
server/internal/handlers/tasks.go
Normal file
@@ -0,0 +1,274 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"gorm.io/gorm"
|
||||
|
||||
"smoop-api/internal/dto"
|
||||
"smoop-api/internal/models"
|
||||
)
|
||||
|
||||
type TasksHandler struct {
|
||||
db *gorm.DB
|
||||
mtxH *MediaMTXHandler
|
||||
}
|
||||
|
||||
func NewTasksHandler(db *gorm.DB, mtxH *MediaMTXHandler) *TasksHandler {
|
||||
return &TasksHandler{
|
||||
db: db,
|
||||
mtxH: mtxH,
|
||||
}
|
||||
}
|
||||
|
||||
// -----------------------------------------------------------------------------
|
||||
// 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
|
||||
}
|
||||
switch req.Type {
|
||||
case models.TaskTypeStartStream:
|
||||
payload, err := h.mtxH.StartStreamPayload(guid)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusBadGateway, gin.H{"error": "failed to build whip url"})
|
||||
return
|
||||
}
|
||||
req.Payload = payload
|
||||
|
||||
case models.TaskTypeStopStream:
|
||||
// best-effort server-side stop (kick publishers/readers on that path)
|
||||
_ = h.mtxH.KickWebRTCSessionsByPath("live/" + guid)
|
||||
if strings.TrimSpace(req.Payload) == "" {
|
||||
req.Payload = `{"reason":"server_stop"}`
|
||||
}
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
@@ -121,3 +121,98 @@ func (h *UsersHandler) Delete(c *gin.Context) {
|
||||
}
|
||||
c.Status(http.StatusNoContent)
|
||||
}
|
||||
|
||||
// GET /users/:id — fetch any user's profile by id
|
||||
func (h *UsersHandler) GetProfile(c *gin.Context) {
|
||||
idStr := c.Param("id")
|
||||
id, _ := strconv.Atoi(idStr)
|
||||
if id <= 0 {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid id"})
|
||||
return
|
||||
}
|
||||
var u models.User
|
||||
if err := h.db.First(&u, id).Error; err != nil {
|
||||
c.JSON(http.StatusNotFound, gin.H{"error": "user not found"})
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, dto.MapUser(u))
|
||||
}
|
||||
|
||||
// PUT /users/:id (admin) — update username, password and/or role
|
||||
func (h *UsersHandler) Update(c *gin.Context) {
|
||||
idStr := c.Param("id")
|
||||
id, _ := strconv.Atoi(idStr)
|
||||
if id <= 0 {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid id"})
|
||||
return
|
||||
}
|
||||
|
||||
var u models.User
|
||||
if err := h.db.First(&u, id).Error; err != nil {
|
||||
c.JSON(http.StatusNotFound, gin.H{"error": "user not found"})
|
||||
return
|
||||
}
|
||||
|
||||
var req dto.UpdateUserDto
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
updated := false
|
||||
|
||||
// --- Update username ---
|
||||
if strings.TrimSpace(req.Username) != "" {
|
||||
name := strings.TrimSpace(req.Username)
|
||||
if name == "" {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "username cannot be empty"})
|
||||
return
|
||||
}
|
||||
u.Username = name
|
||||
updated = true
|
||||
}
|
||||
|
||||
// --- Update password ---
|
||||
if req.Password != "" {
|
||||
if len(req.Password) < 4 {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "password too short"})
|
||||
return
|
||||
}
|
||||
hash, err := crypto.Hash(req.Password, crypto.DefaultArgon2)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": "hash error"})
|
||||
return
|
||||
}
|
||||
u.Password = hash
|
||||
updated = true
|
||||
}
|
||||
|
||||
// --- Update role ---
|
||||
if strings.TrimSpace(req.Role) != "" {
|
||||
role := strings.ToLower(strings.TrimSpace(req.Role))
|
||||
if role != "admin" && role != "user" {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid role"})
|
||||
return
|
||||
}
|
||||
u.Role = models.Role(role)
|
||||
updated = true
|
||||
}
|
||||
|
||||
if !updated {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "nothing to update"})
|
||||
return
|
||||
}
|
||||
|
||||
if err := h.db.Save(&u).Error; err != nil {
|
||||
// detect duplicate username
|
||||
e := strings.ToLower(err.Error())
|
||||
if strings.Contains(e, "duplicate") || strings.Contains(e, "unique") || strings.Contains(e, "exists") {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "username already exists"})
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": "update failed"})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, dto.MapUser(u))
|
||||
}
|
||||
|
||||
@@ -1,10 +1,13 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"smoop-api/internal/handlers"
|
||||
"smoop-api/internal/models"
|
||||
"strconv"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/golang-jwt/jwt"
|
||||
)
|
||||
|
||||
// DeviceAccessFilter middleware sets filtering context for device access
|
||||
@@ -35,3 +38,77 @@ 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()
|
||||
}
|
||||
}
|
||||
|
||||
// UserSelfOrAdmin allows access to /users/:id for admins or the user itself.
|
||||
// Works whether context has only "claims" (router.Auth) or both "user" and "claims" (handlers.Auth).
|
||||
func UserSelfOrAdmin() gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
idStr := c.Param("id")
|
||||
targetID, _ := strconv.Atoi(idStr)
|
||||
if targetID <= 0 {
|
||||
c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "invalid id"})
|
||||
return
|
||||
}
|
||||
|
||||
// 1) Prefer JWT claims (compatible with router.Auth)
|
||||
if v, ok := c.Get("claims"); ok {
|
||||
if m, ok := v.(jwt.MapClaims); ok {
|
||||
role, _ := m["role"].(string)
|
||||
uid := 0
|
||||
switch t := m["sub"].(type) {
|
||||
case float64:
|
||||
uid = int(t)
|
||||
case int:
|
||||
uid = t
|
||||
case int64:
|
||||
uid = int(t)
|
||||
}
|
||||
if role == "admin" || uid == targetID {
|
||||
c.Next()
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 2) Fallback to user context (compatible with handlers.Auth)
|
||||
if v, ok := c.Get("user"); ok {
|
||||
if u, ok := v.(handlers.UserContext); ok {
|
||||
if u.Role == models.RoleAdmin || int(u.ID) == targetID {
|
||||
c.Next()
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
c.AbortWithStatusJSON(http.StatusForbidden, gin.H{"error": "forbidden"})
|
||||
}
|
||||
}
|
||||
|
||||
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()
|
||||
}
|
||||
}
|
||||
25
server/internal/models/cert.go
Normal file
25
server/internal/models/cert.go
Normal file
@@ -0,0 +1,25 @@
|
||||
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
|
||||
Device Device `gorm:"constraint:OnDelete:CASCADE;foreignKey:DeviceGUID;references:GUID"`
|
||||
}
|
||||
|
||||
// “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
|
||||
}
|
||||
@@ -7,6 +7,10 @@ type Device struct {
|
||||
Name string `gorm:"size:255;not null"`
|
||||
Users []User `gorm:"many2many:user_devices;constraint:OnDelete:CASCADE;"`
|
||||
Records []Record `gorm:"foreignKey:DeviceGUID;references:GUID;constraint:OnDelete:CASCADE"`
|
||||
Tasks []DEviceTask `gorm:"foreignKey:DeviceGUID;references:GUID;constraint:OnDelete:CASCADE"`
|
||||
Certs []DeviceCertificate `gorm:"foreignKey:DeviceGUID;references:GUID;constraint:OnDelete:CASCADE"`
|
||||
CreatedAt time.Time
|
||||
UpdatedAt time.Time
|
||||
|
||||
Config *DeviceConfig `gorm:"foreignKey:DeviceGUID;references:GUID;constraint:OnDelete:CASCADE"`
|
||||
}
|
||||
|
||||
19
server/internal/models/device_config.go
Normal file
19
server/internal/models/device_config.go
Normal file
@@ -0,0 +1,19 @@
|
||||
package models
|
||||
|
||||
import "time"
|
||||
|
||||
// One-to-one config bound to a device GUID.
|
||||
type DeviceConfig struct {
|
||||
DeviceGUID string `gorm:"primaryKey;size:64"` // 1:1 with Device.GUID
|
||||
// Fields reflect your device JSON keys (m_*)
|
||||
MGuid string `gorm:"size:64;not null"` // duplicate for device FW convenience
|
||||
MRecordingDuration int `gorm:"not null;default:240"`
|
||||
MBaseURL string `gorm:"size:512;not null"`
|
||||
MPolling int `gorm:"not null;default:30"`
|
||||
MJitter int `gorm:"not null;default:10"`
|
||||
|
||||
CreatedAt time.Time
|
||||
UpdatedAt time.Time
|
||||
|
||||
Device Device `gorm:"constraint:OnDelete:CASCADE;foreignKey:DeviceGUID;references:GUID"`
|
||||
}
|
||||
31
server/internal/models/emqx.go
Normal file
31
server/internal/models/emqx.go
Normal file
@@ -0,0 +1,31 @@
|
||||
package models
|
||||
|
||||
import "time"
|
||||
|
||||
// MQTTMsg maps to table t_mqtt_msg in emqx_data
|
||||
type MQTTMsg struct {
|
||||
ID uint `gorm:"primaryKey;column:id"`
|
||||
MsgID string `gorm:"column:msgid;type:varchar(64)"`
|
||||
Sender string `gorm:"column:sender;type:varchar(64)"`
|
||||
Topic string `gorm:"column:topic;type:varchar(255)"`
|
||||
QoS int `gorm:"column:qos"`
|
||||
Retain int `gorm:"column:retain"`
|
||||
Payload string `gorm:"column:payload;type:text"`
|
||||
Arrived time.Time `gorm:"column:arrived"`
|
||||
}
|
||||
|
||||
func (MQTTMsg) TableName() string {
|
||||
return "t_mqtt_msg"
|
||||
}
|
||||
|
||||
// EmqxClientEvent maps to table emqx_client_events in emqx_data
|
||||
type EmqxClientEvent struct {
|
||||
ID uint `gorm:"primaryKey;column:id"`
|
||||
ClientID string `gorm:"column:clientid;type:varchar(255)"`
|
||||
Event string `gorm:"column:event;type:varchar(255)"`
|
||||
CreatedAt time.Time `gorm:"column:created_at;autoCreateTime"`
|
||||
}
|
||||
|
||||
func (EmqxClientEvent) TableName() string {
|
||||
return "emqx_client_events"
|
||||
}
|
||||
52
server/internal/models/task.go
Normal file
52
server/internal/models/task.go
Normal file
@@ -0,0 +1,52 @@
|
||||
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"`
|
||||
Device Device `gorm:"constraint:OnDelete:CASCADE;foreignKey:DeviceGUID;references:GUID"`
|
||||
}
|
||||
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
|
||||
}
|
||||
@@ -15,6 +15,7 @@ type User struct {
|
||||
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"`
|
||||
}
|
||||
@@ -15,7 +15,10 @@ import (
|
||||
)
|
||||
|
||||
func Build(db *gorm.DB, minio *minio.Client, cfg *config.Config) *gin.Engine {
|
||||
r := gin.Default()
|
||||
// r := gin.Default()
|
||||
|
||||
r := gin.New()
|
||||
r.Use(handlers.BodyLogger(), gin.Logger(), gin.Recovery())
|
||||
|
||||
jwtMgr := crypto.NewJWT(cfg.JWTSecret)
|
||||
|
||||
@@ -26,6 +29,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, mediamtxH)
|
||||
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)
|
||||
@@ -38,19 +50,27 @@ func Build(db *gorm.DB, minio *minio.Client, cfg *config.Config) *gin.Engine {
|
||||
r.POST("/auth/change_password", authMW, authH.ChangePassword)
|
||||
|
||||
r.GET("/users/profile", authMW, usersH.Profile)
|
||||
r.POST("/users/:id/set_role", authMW, adminOnly, usersH.SetRole)
|
||||
r.PUT("/users/:id", authMW, adminOnly, usersH.Update)
|
||||
r.GET("/users", authMW, adminOnly, usersH.List)
|
||||
r.POST("/users/create", authMW, adminOnly, usersH.Create)
|
||||
r.DELETE("/users/:id", authMW, adminOnly, usersH.Delete)
|
||||
r.GET("/users/:id", authMW, middleware.UserSelfOrAdmin(), usersH.GetProfile)
|
||||
|
||||
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.GET("/device/:guid/config", authMW, middleware.DeviceAccessFilter(), devH.GetDeviceConfig)
|
||||
r.POST("/device/:guid/config", authMW, adminOnly, devH.CreateDeviceConfig)
|
||||
r.PUT("/device/:guid/config", authMW, middleware.DeviceAccessFilter(), devH.UpdateDeviceConfig)
|
||||
|
||||
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 +80,29 @@ 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, middleware.DeviceAccessFilter(), mediamtxH.MintRead)
|
||||
// Admin controls
|
||||
r.GET("/mediamtx/paths", authMW, adminOnly, mediamtxH.ListPaths)
|
||||
r.POST("/mediamtx/webrtc/kick/:id", authMW, adminOnly, mediamtxH.KickWebRTC)
|
||||
// SSE endpoint for audio stream UI
|
||||
r.GET("/mediamtx/:guid/wait", authMW, middleware.DeviceAccessFilter(), mediamtxH.WaitLiveSSE)
|
||||
|
||||
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