feat: versão 1.5 - CRM Beta com leads, funis, campanhas e portal do cliente

This commit is contained in:
Erik Silva
2025-12-24 17:36:52 -03:00
parent 99d828869a
commit dfb91c8ba5
98 changed files with 18255 additions and 1465 deletions

View File

@@ -65,6 +65,16 @@ func Auth(cfg *config.Config) func(http.Handler) http.Handler {
tenantIDFromJWT, _ = tenantIDClaim.(string)
}
// VALIDAÇÃO DE SEGURANÇA: Verificar user_type para impedir clientes de acessarem rotas de agência
if userTypeClaim, ok := claims["user_type"]; ok && userTypeClaim != nil {
userType, _ := userTypeClaim.(string)
if userType == "customer" {
log.Printf("❌ CUSTOMER ACCESS BLOCKED: Customer %s tried to access agency route %s", userID, r.RequestURI)
http.Error(w, "Forbidden: Customers cannot access agency routes", http.StatusForbidden)
return
}
}
// VALIDAÇÃO DE SEGURANÇA: Verificar se o tenant_id do JWT corresponde ao subdomínio acessado
// Pegar o tenant_id do contexto (detectado pelo TenantDetector middleware ANTES deste)
tenantIDFromContext := ""

View File

@@ -0,0 +1,44 @@
package middleware
import (
"log"
"net/http"
"strings"
)
// CheckCollaboratorReadOnly verifica se um colaborador está tentando fazer operações de escrita
// Se sim, bloqueia com 403
func CheckCollaboratorReadOnly(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// Verificar agency_role do contexto
agencyRole, ok := r.Context().Value("agency_role").(string)
if !ok {
// Se não houver agency_role no contexto, é um customer, deixa passar
next.ServeHTTP(w, r)
return
}
// Apenas colaboradores têm restrição de read-only
if agencyRole != "collaborator" {
next.ServeHTTP(w, r)
return
}
// Verificar se é uma operação de escrita
method := r.Method
if method == http.MethodPost || method == http.MethodPut || method == http.MethodDelete {
// Verificar a rota
path := r.URL.Path
// Bloquear operações de escrita em CRM
if strings.Contains(path, "/api/crm/") {
userID, _ := r.Context().Value(UserIDKey).(string)
log.Printf("❌ COLLABORATOR WRITE BLOCKED: User %s (collaborator) tried %s %s", userID, method, path)
http.Error(w, "Colaboradores têm acesso somente leitura", http.StatusForbidden)
return
}
}
next.ServeHTTP(w, r)
})
}

View File

@@ -0,0 +1,85 @@
package middleware
import (
"aggios-app/backend/internal/config"
"context"
"log"
"net/http"
"strings"
"github.com/golang-jwt/jwt/v5"
)
const (
CustomerIDKey contextKey = "customer_id"
)
// CustomerAuthMiddleware valida tokens JWT de clientes do portal
func CustomerAuthMiddleware(cfg *config.Config) func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// Extrair token do header Authorization
authHeader := r.Header.Get("Authorization")
if authHeader == "" {
http.Error(w, "Authorization header required", http.StatusUnauthorized)
return
}
// Remover "Bearer " prefix
tokenString := strings.TrimPrefix(authHeader, "Bearer ")
if tokenString == authHeader {
http.Error(w, "Invalid authorization format", http.StatusUnauthorized)
return
}
// Parse e validar token
token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
// Verificar método de assinatura
if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
return nil, jwt.ErrSignatureInvalid
}
return []byte(cfg.JWT.Secret), nil
})
if err != nil || !token.Valid {
log.Printf("Invalid token: %v", err)
http.Error(w, "Invalid or expired token", http.StatusUnauthorized)
return
}
// Extrair claims
claims, ok := token.Claims.(jwt.MapClaims)
if !ok {
http.Error(w, "Invalid token claims", http.StatusUnauthorized)
return
}
// Verificar se é token de customer
tokenType, _ := claims["type"].(string)
if tokenType != "customer_portal" {
http.Error(w, "Invalid token type", http.StatusUnauthorized)
return
}
// Extrair customer_id e tenant_id
customerID, ok := claims["customer_id"].(string)
if !ok {
http.Error(w, "Invalid customer_id in token", http.StatusUnauthorized)
return
}
tenantID, ok := claims["tenant_id"].(string)
if !ok {
http.Error(w, "Invalid tenant_id in token", http.StatusUnauthorized)
return
}
// Adicionar ao contexto
ctx := context.WithValue(r.Context(), CustomerIDKey, customerID)
ctx = context.WithValue(ctx, TenantIDKey, tenantID)
// Prosseguir com a requisição
next.ServeHTTP(w, r.WithContext(ctx))
})
}
}

View File

@@ -0,0 +1,104 @@
package middleware
import (
"aggios-app/backend/internal/config"
"aggios-app/backend/internal/domain"
"context"
"log"
"net/http"
"strings"
"github.com/golang-jwt/jwt/v5"
)
// UnifiedAuthMiddleware valida JWT unificado e permite múltiplos tipos de usuários
func UnifiedAuthMiddleware(cfg *config.Config, allowedTypes ...domain.UserType) func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// Extrair token do header Authorization
authHeader := r.Header.Get("Authorization")
if authHeader == "" {
log.Printf("🚫 UnifiedAuth: Missing Authorization header")
http.Error(w, "Unauthorized: Missing token", http.StatusUnauthorized)
return
}
// Formato esperado: "Bearer <token>"
parts := strings.Split(authHeader, " ")
if len(parts) != 2 || parts[0] != "Bearer" {
log.Printf("🚫 UnifiedAuth: Invalid Authorization format")
http.Error(w, "Unauthorized: Invalid token format", http.StatusUnauthorized)
return
}
tokenString := parts[1]
// Parsear e validar token
token, err := jwt.ParseWithClaims(tokenString, &domain.UnifiedClaims{}, func(token *jwt.Token) (interface{}, error) {
return []byte(cfg.JWT.Secret), nil
})
if err != nil {
log.Printf("🚫 UnifiedAuth: Token parse error: %v", err)
http.Error(w, "Unauthorized: Invalid token", http.StatusUnauthorized)
return
}
claims, ok := token.Claims.(*domain.UnifiedClaims)
if !ok || !token.Valid {
log.Printf("🚫 UnifiedAuth: Invalid token claims")
http.Error(w, "Unauthorized: Invalid token", http.StatusUnauthorized)
return
}
// Verificar se o tipo de usuário é permitido
if len(allowedTypes) > 0 {
allowed := false
for _, allowedType := range allowedTypes {
if claims.UserType == allowedType {
allowed = true
break
}
}
if !allowed {
log.Printf("🚫 UnifiedAuth: User type %s not allowed (allowed: %v)", claims.UserType, allowedTypes)
http.Error(w, "Forbidden: Insufficient permissions", http.StatusForbidden)
return
}
}
// Adicionar informações ao contexto
ctx := r.Context()
ctx = context.WithValue(ctx, UserIDKey, claims.UserID)
ctx = context.WithValue(ctx, TenantIDKey, claims.TenantID)
ctx = context.WithValue(ctx, "email", claims.Email)
ctx = context.WithValue(ctx, "user_type", string(claims.UserType))
ctx = context.WithValue(ctx, "role", claims.Role)
// Para compatibilidade com handlers de portal que esperam CustomerIDKey
if claims.UserType == domain.UserTypeCustomer {
ctx = context.WithValue(ctx, CustomerIDKey, claims.UserID)
}
log.Printf("✅ UnifiedAuth: Authenticated user_id=%s, type=%s, role=%s, tenant=%s",
claims.UserID, claims.UserType, claims.Role, claims.TenantID)
next.ServeHTTP(w, r.WithContext(ctx))
})
}
}
// RequireAgencyUser middleware que permite apenas usuários de agência (admin, colaborador)
func RequireAgencyUser(cfg *config.Config) func(http.Handler) http.Handler {
return UnifiedAuthMiddleware(cfg, domain.UserTypeAgency)
}
// RequireCustomer middleware que permite apenas clientes
func RequireCustomer(cfg *config.Config) func(http.Handler) http.Handler {
return UnifiedAuthMiddleware(cfg, domain.UserTypeCustomer)
}
// RequireAnyAuthenticated middleware que permite qualquer usuário autenticado
func RequireAnyAuthenticated(cfg *config.Config) func(http.Handler) http.Handler {
return UnifiedAuthMiddleware(cfg) // Sem filtro de tipo
}