veza/veza-backend-api/internal/handlers/role_handler.go

232 lines
7.2 KiB
Go
Raw Normal View History

2025-12-03 19:29:37 +00:00
package handlers
import (
"context"
2025-12-03 19:29:37 +00:00
"net/http"
"time"
apperrors "veza-backend-api/internal/errors"
2025-12-03 19:29:37 +00:00
"veza-backend-api/internal/models"
"veza-backend-api/internal/services"
"github.com/gin-gonic/gin"
"github.com/google/uuid"
"go.uber.org/zap"
2025-12-03 19:29:37 +00:00
)
// RoleServiceInterface defines the interface for role operations
// This allows for easier testing with mocks
type RoleServiceInterface interface {
GetRoles(ctx context.Context) ([]models.Role, error)
GetRole(ctx context.Context, roleID uuid.UUID) (*models.Role, error)
CreateRole(ctx context.Context, role *models.Role) error
UpdateRole(ctx context.Context, roleID uuid.UUID, updates *models.Role) error
DeleteRole(ctx context.Context, roleID uuid.UUID) error
AssignRoleToUser(ctx context.Context, userID uuid.UUID, roleID uuid.UUID, assignedBy uuid.UUID, expiresAt *time.Time) error
RevokeRoleFromUser(ctx context.Context, userID uuid.UUID, roleID uuid.UUID) error
GetUserRoles(ctx context.Context, userID uuid.UUID) ([]models.Role, error)
}
2025-12-03 19:29:37 +00:00
// RoleHandler gère les endpoints de gestion des rôles
type RoleHandler struct {
roleService RoleServiceInterface
P0: stabilisation backend/chat/stream + nouvelle base migrations v1 Backend Go: - Remplacement complet des anciennes migrations par la base V1 alignée sur ORIGIN. - Durcissement global du parsing JSON (BindAndValidateJSON + RespondWithAppError). - Sécurisation de config.go, CORS, statuts de santé et monitoring. - Implémentation des transactions P0 (RBAC, duplication de playlists, social toggles). - Ajout d’un job worker structuré (emails, analytics, thumbnails) + tests associés. - Nouvelle doc backend : AUDIT_CONFIG, BACKEND_CONFIG, AUTH_PASSWORD_RESET, JOB_WORKER_*. Chat server (Rust): - Refonte du pipeline JWT + sécurité, audit et rate limiting avancé. - Implémentation complète du cycle de message (read receipts, delivered, edit/delete, typing). - Nettoyage des panics, gestion d’erreurs robuste, logs structurés. - Migrations chat alignées sur le schéma UUID et nouvelles features. Stream server (Rust): - Refonte du moteur de streaming (encoding pipeline + HLS) et des modules core. - Transactions P0 pour les jobs et segments, garanties d’atomicité. - Documentation détaillée de la pipeline (AUDIT_STREAM_*, DESIGN_STREAM_PIPELINE, TRANSACTIONS_P0_IMPLEMENTATION). Documentation & audits: - TRIAGE.md et AUDIT_STABILITY.md à jour avec l’état réel des 3 services. - Cartographie complète des migrations et des transactions (DB_MIGRATIONS_*, DB_TRANSACTION_PLAN, AUDIT_DB_TRANSACTIONS, TRANSACTION_TESTS_PHASE3). - Scripts de reset et de cleanup pour la lab DB et la V1. Ce commit fige l’ensemble du travail de stabilisation P0 (UUID, backend, chat et stream) avant les phases suivantes (Coherence Guardian, WS hardening, etc.).
2025-12-06 10:14:38 +00:00
commonHandler *CommonHandler
2025-12-03 19:29:37 +00:00
}
// NewRoleHandler crée un nouveau RoleHandler
P0: stabilisation backend/chat/stream + nouvelle base migrations v1 Backend Go: - Remplacement complet des anciennes migrations par la base V1 alignée sur ORIGIN. - Durcissement global du parsing JSON (BindAndValidateJSON + RespondWithAppError). - Sécurisation de config.go, CORS, statuts de santé et monitoring. - Implémentation des transactions P0 (RBAC, duplication de playlists, social toggles). - Ajout d’un job worker structuré (emails, analytics, thumbnails) + tests associés. - Nouvelle doc backend : AUDIT_CONFIG, BACKEND_CONFIG, AUTH_PASSWORD_RESET, JOB_WORKER_*. Chat server (Rust): - Refonte du pipeline JWT + sécurité, audit et rate limiting avancé. - Implémentation complète du cycle de message (read receipts, delivered, edit/delete, typing). - Nettoyage des panics, gestion d’erreurs robuste, logs structurés. - Migrations chat alignées sur le schéma UUID et nouvelles features. Stream server (Rust): - Refonte du moteur de streaming (encoding pipeline + HLS) et des modules core. - Transactions P0 pour les jobs et segments, garanties d’atomicité. - Documentation détaillée de la pipeline (AUDIT_STREAM_*, DESIGN_STREAM_PIPELINE, TRANSACTIONS_P0_IMPLEMENTATION). Documentation & audits: - TRIAGE.md et AUDIT_STABILITY.md à jour avec l’état réel des 3 services. - Cartographie complète des migrations et des transactions (DB_MIGRATIONS_*, DB_TRANSACTION_PLAN, AUDIT_DB_TRANSACTIONS, TRANSACTION_TESTS_PHASE3). - Scripts de reset et de cleanup pour la lab DB et la V1. Ce commit fige l’ensemble du travail de stabilisation P0 (UUID, backend, chat et stream) avant les phases suivantes (Coherence Guardian, WS hardening, etc.).
2025-12-06 10:14:38 +00:00
func NewRoleHandler(roleService *services.RoleService, logger *zap.Logger) *RoleHandler {
return &RoleHandler{
roleService: roleService,
commonHandler: NewCommonHandler(logger),
}
2025-12-03 19:29:37 +00:00
}
// NewRoleHandlerWithInterface crée un nouveau RoleHandler avec une interface (pour les tests)
func NewRoleHandlerWithInterface(roleService RoleServiceInterface, logger *zap.Logger) *RoleHandler {
return &RoleHandler{
roleService: roleService,
commonHandler: NewCommonHandler(logger),
}
}
2025-12-03 19:29:37 +00:00
// GetRoles récupère tous les rôles
// BE-API-007: Implement roles management endpoints
2025-12-03 19:29:37 +00:00
func (h *RoleHandler) GetRoles(c *gin.Context) {
roles, err := h.roleService.GetRoles(c.Request.Context())
if err != nil {
RespondWithAppError(c, apperrors.Wrap(apperrors.ErrCodeInternal, "Failed to get roles", err))
2025-12-03 19:29:37 +00:00
return
}
RespondSuccess(c, http.StatusOK, roles)
2025-12-03 19:29:37 +00:00
}
// GetRole récupère un rôle par ID
// BE-API-007: Implement roles management endpoints
2025-12-03 19:29:37 +00:00
func (h *RoleHandler) GetRole(c *gin.Context) {
roleIDStr := c.Param("id")
roleID, err := uuid.Parse(roleIDStr)
if err != nil {
RespondWithAppError(c, apperrors.NewValidationError("invalid role id"))
2025-12-03 19:29:37 +00:00
return
}
role, err := h.roleService.GetRole(c.Request.Context(), roleID)
if err != nil {
if err.Error() == "role not found" {
RespondWithAppError(c, apperrors.NewNotFoundError("role"))
2025-12-03 19:29:37 +00:00
} else {
RespondWithAppError(c, apperrors.Wrap(apperrors.ErrCodeInternal, "Failed to get role", err))
2025-12-03 19:29:37 +00:00
}
return
}
RespondSuccess(c, http.StatusOK, role)
2025-12-03 19:29:37 +00:00
}
// CreateRole crée un nouveau rôle
func (h *RoleHandler) CreateRole(c *gin.Context) {
var role models.Role
P0: stabilisation backend/chat/stream + nouvelle base migrations v1 Backend Go: - Remplacement complet des anciennes migrations par la base V1 alignée sur ORIGIN. - Durcissement global du parsing JSON (BindAndValidateJSON + RespondWithAppError). - Sécurisation de config.go, CORS, statuts de santé et monitoring. - Implémentation des transactions P0 (RBAC, duplication de playlists, social toggles). - Ajout d’un job worker structuré (emails, analytics, thumbnails) + tests associés. - Nouvelle doc backend : AUDIT_CONFIG, BACKEND_CONFIG, AUTH_PASSWORD_RESET, JOB_WORKER_*. Chat server (Rust): - Refonte du pipeline JWT + sécurité, audit et rate limiting avancé. - Implémentation complète du cycle de message (read receipts, delivered, edit/delete, typing). - Nettoyage des panics, gestion d’erreurs robuste, logs structurés. - Migrations chat alignées sur le schéma UUID et nouvelles features. Stream server (Rust): - Refonte du moteur de streaming (encoding pipeline + HLS) et des modules core. - Transactions P0 pour les jobs et segments, garanties d’atomicité. - Documentation détaillée de la pipeline (AUDIT_STREAM_*, DESIGN_STREAM_PIPELINE, TRANSACTIONS_P0_IMPLEMENTATION). Documentation & audits: - TRIAGE.md et AUDIT_STABILITY.md à jour avec l’état réel des 3 services. - Cartographie complète des migrations et des transactions (DB_MIGRATIONS_*, DB_TRANSACTION_PLAN, AUDIT_DB_TRANSACTIONS, TRANSACTION_TESTS_PHASE3). - Scripts de reset et de cleanup pour la lab DB et la V1. Ce commit fige l’ensemble du travail de stabilisation P0 (UUID, backend, chat et stream) avant les phases suivantes (Coherence Guardian, WS hardening, etc.).
2025-12-06 10:14:38 +00:00
if appErr := h.commonHandler.BindAndValidateJSON(c, &role); appErr != nil {
RespondWithAppError(c, appErr)
2025-12-03 19:29:37 +00:00
return
}
if err := h.roleService.CreateRole(c.Request.Context(), &role); err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
c.JSON(http.StatusCreated, gin.H{"role": role})
}
// UpdateRole met à jour un rôle
func (h *RoleHandler) UpdateRole(c *gin.Context) {
roleIDStr := c.Param("id")
roleID, err := uuid.Parse(roleIDStr)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid role id"})
return
}
var updates models.Role
P0: stabilisation backend/chat/stream + nouvelle base migrations v1 Backend Go: - Remplacement complet des anciennes migrations par la base V1 alignée sur ORIGIN. - Durcissement global du parsing JSON (BindAndValidateJSON + RespondWithAppError). - Sécurisation de config.go, CORS, statuts de santé et monitoring. - Implémentation des transactions P0 (RBAC, duplication de playlists, social toggles). - Ajout d’un job worker structuré (emails, analytics, thumbnails) + tests associés. - Nouvelle doc backend : AUDIT_CONFIG, BACKEND_CONFIG, AUTH_PASSWORD_RESET, JOB_WORKER_*. Chat server (Rust): - Refonte du pipeline JWT + sécurité, audit et rate limiting avancé. - Implémentation complète du cycle de message (read receipts, delivered, edit/delete, typing). - Nettoyage des panics, gestion d’erreurs robuste, logs structurés. - Migrations chat alignées sur le schéma UUID et nouvelles features. Stream server (Rust): - Refonte du moteur de streaming (encoding pipeline + HLS) et des modules core. - Transactions P0 pour les jobs et segments, garanties d’atomicité. - Documentation détaillée de la pipeline (AUDIT_STREAM_*, DESIGN_STREAM_PIPELINE, TRANSACTIONS_P0_IMPLEMENTATION). Documentation & audits: - TRIAGE.md et AUDIT_STABILITY.md à jour avec l’état réel des 3 services. - Cartographie complète des migrations et des transactions (DB_MIGRATIONS_*, DB_TRANSACTION_PLAN, AUDIT_DB_TRANSACTIONS, TRANSACTION_TESTS_PHASE3). - Scripts de reset et de cleanup pour la lab DB et la V1. Ce commit fige l’ensemble du travail de stabilisation P0 (UUID, backend, chat et stream) avant les phases suivantes (Coherence Guardian, WS hardening, etc.).
2025-12-06 10:14:38 +00:00
if appErr := h.commonHandler.BindAndValidateJSON(c, &updates); appErr != nil {
RespondWithAppError(c, appErr)
2025-12-03 19:29:37 +00:00
return
}
if err := h.roleService.UpdateRole(c.Request.Context(), roleID, &updates); err != nil {
if err.Error() == "role not found or is system role" {
c.JSON(http.StatusNotFound, gin.H{"error": err.Error()})
} else {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
}
return
}
c.JSON(http.StatusOK, gin.H{"message": "role updated"})
}
// DeleteRole supprime un rôle
func (h *RoleHandler) DeleteRole(c *gin.Context) {
roleIDStr := c.Param("id")
roleID, err := uuid.Parse(roleIDStr)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid role id"})
return
}
if err := h.roleService.DeleteRole(c.Request.Context(), roleID); err != nil {
if err.Error() == "role not found" || err.Error() == "cannot delete system role" {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
} else {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
}
return
}
c.JSON(http.StatusOK, gin.H{"message": "role deleted"})
}
// AssignRole assigne un rôle à un utilisateur
// BE-API-007: Implement roles management endpoints
// Supports both :id and :userId parameters for flexibility
2025-12-03 19:29:37 +00:00
func (h *RoleHandler) AssignRole(c *gin.Context) {
// Try :userId first (from /users/:userId/roles), fallback to :id
userIDStr := c.Param("userId")
if userIDStr == "" {
userIDStr = c.Param("id")
}
2025-12-03 19:29:37 +00:00
userID, err := uuid.Parse(userIDStr)
if err != nil {
RespondWithAppError(c, apperrors.NewValidationError("invalid user id"))
2025-12-03 19:29:37 +00:00
return
}
var req struct {
RoleID uuid.UUID `json:"role_id" binding:"required"`
ExpiresAt *time.Time `json:"expires_at"`
}
P0: stabilisation backend/chat/stream + nouvelle base migrations v1 Backend Go: - Remplacement complet des anciennes migrations par la base V1 alignée sur ORIGIN. - Durcissement global du parsing JSON (BindAndValidateJSON + RespondWithAppError). - Sécurisation de config.go, CORS, statuts de santé et monitoring. - Implémentation des transactions P0 (RBAC, duplication de playlists, social toggles). - Ajout d’un job worker structuré (emails, analytics, thumbnails) + tests associés. - Nouvelle doc backend : AUDIT_CONFIG, BACKEND_CONFIG, AUTH_PASSWORD_RESET, JOB_WORKER_*. Chat server (Rust): - Refonte du pipeline JWT + sécurité, audit et rate limiting avancé. - Implémentation complète du cycle de message (read receipts, delivered, edit/delete, typing). - Nettoyage des panics, gestion d’erreurs robuste, logs structurés. - Migrations chat alignées sur le schéma UUID et nouvelles features. Stream server (Rust): - Refonte du moteur de streaming (encoding pipeline + HLS) et des modules core. - Transactions P0 pour les jobs et segments, garanties d’atomicité. - Documentation détaillée de la pipeline (AUDIT_STREAM_*, DESIGN_STREAM_PIPELINE, TRANSACTIONS_P0_IMPLEMENTATION). Documentation & audits: - TRIAGE.md et AUDIT_STABILITY.md à jour avec l’état réel des 3 services. - Cartographie complète des migrations et des transactions (DB_MIGRATIONS_*, DB_TRANSACTION_PLAN, AUDIT_DB_TRANSACTIONS, TRANSACTION_TESTS_PHASE3). - Scripts de reset et de cleanup pour la lab DB et la V1. Ce commit fige l’ensemble du travail de stabilisation P0 (UUID, backend, chat et stream) avant les phases suivantes (Coherence Guardian, WS hardening, etc.).
2025-12-06 10:14:38 +00:00
if appErr := h.commonHandler.BindAndValidateJSON(c, &req); appErr != nil {
RespondWithAppError(c, appErr)
2025-12-03 19:29:37 +00:00
return
}
// Récupérer l'ID de l'utilisateur qui assigne depuis le contexte
assignedBy, ok := GetUserIDUUID(c)
2025-12-03 19:29:37 +00:00
if !ok {
return // Erreur déjà envoyée par GetUserIDUUID
2025-12-03 19:29:37 +00:00
}
if err := h.roleService.AssignRoleToUser(c.Request.Context(), userID, req.RoleID, assignedBy, req.ExpiresAt); err != nil {
RespondWithAppError(c, apperrors.Wrap(apperrors.ErrCodeInternal, "Failed to assign role", err))
2025-12-03 19:29:37 +00:00
return
}
RespondSuccess(c, http.StatusOK, gin.H{"message": "role assigned"})
2025-12-03 19:29:37 +00:00
}
// RevokeRole révoque un rôle d'un utilisateur
// BE-API-007: Implement roles management endpoints
// Supports both :id and :userId parameters for flexibility
2025-12-03 19:29:37 +00:00
func (h *RoleHandler) RevokeRole(c *gin.Context) {
// Try :userId first (from /users/:userId/roles/:roleId), fallback to :id
userIDStr := c.Param("userId")
if userIDStr == "" {
userIDStr = c.Param("id")
}
2025-12-03 19:29:37 +00:00
userID, err := uuid.Parse(userIDStr)
if err != nil {
RespondWithAppError(c, apperrors.NewValidationError("invalid user id"))
2025-12-03 19:29:37 +00:00
return
}
roleIDStr := c.Param("roleId")
roleID, err := uuid.Parse(roleIDStr)
if err != nil {
RespondWithAppError(c, apperrors.NewValidationError("invalid role id"))
2025-12-03 19:29:37 +00:00
return
}
if err := h.roleService.RevokeRoleFromUser(c.Request.Context(), userID, roleID); err != nil {
if err.Error() == "role assignment not found" {
RespondWithAppError(c, apperrors.NewNotFoundError("role assignment"))
2025-12-03 19:29:37 +00:00
} else {
RespondWithAppError(c, apperrors.Wrap(apperrors.ErrCodeInternal, "Failed to revoke role", err))
2025-12-03 19:29:37 +00:00
}
return
}
RespondSuccess(c, http.StatusOK, gin.H{"message": "role revoked"})
2025-12-03 19:29:37 +00:00
}
// GetUserRoles récupère tous les rôles d'un utilisateur
func (h *RoleHandler) GetUserRoles(c *gin.Context) {
userIDStr := c.Param("id")
userID, err := uuid.Parse(userIDStr)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid user id"})
return
}
roles, err := h.roleService.GetUserRoles(c.Request.Context(), userID)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
c.JSON(http.StatusOK, gin.H{"roles": roles})
}