changes in api routes, ihave created almost functional settings form
This commit is contained in:
@@ -45,7 +45,7 @@ services:
|
||||
APP_DIR: ${API_APP_DIR:-./cmd/api}
|
||||
environment:
|
||||
VAULT_ADDR: "http://host.docker.internal:8200"
|
||||
VAULT_TOKEN: "hvs.tZ4eh9P18sCZ5c1PZIz59EmH"
|
||||
VAULT_TOKEN: "hvs.rKzgIc5aaucOCtlJNsUdZuEH"
|
||||
# VAULT_KV_PATH: "kv/data/snoop"
|
||||
MINIO_ENDPOINT: "http://minio:9000"
|
||||
JWT_SECRET: ${JWT_SECRET}
|
||||
|
||||
@@ -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>
|
||||
@@ -60,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>
|
||||
|
||||
@@ -3,6 +3,86 @@ 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';
|
||||
|
||||
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">
|
||||
@@ -12,24 +92,54 @@ import { Label } from '@/components/ui/label'
|
||||
Settings
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
<Button variant="secondary" @click="goBack">Back</Button>
|
||||
<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>
|
||||
|
||||
@@ -74,7 +74,8 @@ server {
|
||||
# HTTPS :443 — mTLS enforced only on listed paths
|
||||
# ==============================================
|
||||
server {
|
||||
listen 443 ssl http2;
|
||||
listen 443 ssl;
|
||||
http2 on;
|
||||
server_name _;
|
||||
|
||||
access_log /var/log/nginx/access.log mtls_debug;
|
||||
|
||||
16
readme.md
16
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
|
||||
|
||||
@@ -121,3 +121,19 @@ 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))
|
||||
}
|
||||
|
||||
@@ -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
|
||||
@@ -64,3 +67,48 @@ func TrackerAccessFilter() gin.HandlerFunc {
|
||||
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"})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -54,6 +54,7 @@ func Build(db *gorm.DB, minio *minio.Client, cfg *config.Config) *gin.Engine {
|
||||
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, adminOnly, devH.Create)
|
||||
|
||||
Reference in New Issue
Block a user