changes in api routes, ihave created almost functional settings form

This commit is contained in:
tdv
2025-11-07 18:07:23 +02:00
parent d0cece3001
commit 2ba75d0e87
8 changed files with 219 additions and 13 deletions

View File

@@ -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"})
}
}