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

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

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

View File

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