Detalhes das alterações: [Banco de Dados] - Ajuste nas constraints UNIQUE das tabelas de catálogo (cursos, empresas, tipos_eventos, etc.) para incluir a coluna `regiao`, permitindo dados duplicados entre regiões mas únicos por região. - Correção crítica na constraint da tabela `precos_tipos_eventos` para evitar conflitos de UPSERT (ON CONFLICT) durante a inicialização. - Implementação de lógica de Seed para a região 'MG': - Clonagem automática de catálogos base de 'SP' para 'MG' (Tipos de Evento, Serviços, etc.). - Inserção de tabela de preços específica para 'MG' via script de migração. [Backend - Go] - Atualização geral dos Handlers e Services para filtrar dados baseados no cabeçalho `x-regiao`. - Ajuste no Middleware de autenticação para processar e repassar o contexto da região. - Correção de queries SQL (geradas pelo sqlc) para suportar os novos filtros regionais. [Frontend - React] - Implementação do envio global do cabeçalho `x-regiao` nas requisições da API. - Correção no componente [PriceTableEditor](cci:1://file:///c:/Projetos/photum/frontend/components/System/PriceTableEditor.tsx:26:0-217:2) para carregar e salvar preços respeitando a região selecionada (fix de "Preços zerados" em MG). - Refatoração profunda na tela de Importação ([ImportData.tsx](cci:7://file:///c:/Projetos/photum/frontend/pages/ImportData.tsx:0:0-0:0)): - Adição de feedback visual detalhado para registros ignorados. - Categorização explícita de erros: "CPF Inválido", "Região Incompatível", "Linha Vazia/Separador". - Correção na lógica de contagem para considerar linhas vazias explicitamente no relatório final, garantindo que o total bata com o Excel. [Geral] - Correção de diversos erros de lint e tipagem TSX. - Padronização de logs de erro no backend para facilitar debug.
114 lines
3 KiB
Go
114 lines
3 KiB
Go
package auth
|
|
|
|
import (
|
|
"net/http"
|
|
"strings"
|
|
|
|
"photum-backend/internal/config"
|
|
|
|
"github.com/gin-gonic/gin"
|
|
)
|
|
|
|
func AuthMiddleware(cfg *config.Config) gin.HandlerFunc {
|
|
return func(c *gin.Context) {
|
|
authHeader := c.GetHeader("Authorization")
|
|
var tokenString string
|
|
|
|
if authHeader != "" {
|
|
parts := strings.Split(authHeader, " ")
|
|
if len(parts) == 2 && parts[0] == "Bearer" {
|
|
tokenString = parts[1]
|
|
} else if len(parts) == 1 && parts[0] != "" {
|
|
tokenString = parts[0]
|
|
} else {
|
|
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "invalid authorization header format"})
|
|
return
|
|
}
|
|
} else {
|
|
// Try to get from cookie
|
|
cookie, err := c.Cookie("access_token")
|
|
if err == nil && cookie != "" {
|
|
tokenString = cookie
|
|
} else {
|
|
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "authorization header required"})
|
|
return
|
|
}
|
|
}
|
|
claims, err := ValidateToken(tokenString, cfg.JwtAccessSecret)
|
|
if err != nil {
|
|
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "invalid token"})
|
|
return
|
|
}
|
|
|
|
c.Set("userID", claims.UserID.String())
|
|
c.Set("role", claims.Role)
|
|
c.Set("regioes", claims.Regioes)
|
|
|
|
// Region Logic
|
|
requestedRegion := c.GetHeader("x-regiao")
|
|
if requestedRegion == "" {
|
|
// Default to first permitted region (usually SP)
|
|
if len(claims.Regioes) > 0 {
|
|
requestedRegion = claims.Regioes[0]
|
|
} else {
|
|
requestedRegion = "SP" // Fallback
|
|
}
|
|
}
|
|
|
|
// Validate access
|
|
allowed := false
|
|
for _, r := range claims.Regioes {
|
|
if r == requestedRegion {
|
|
allowed = true
|
|
break
|
|
}
|
|
}
|
|
|
|
// If user has no regions (legacy) or empty list, maybe allow SP if not specified?
|
|
// Or strictly enforce. Enforcing strictly is safer.
|
|
if !allowed && len(claims.Regioes) > 0 {
|
|
c.AbortWithStatusJSON(http.StatusForbidden, gin.H{"error": "acesso negado a esta região"})
|
|
return
|
|
}
|
|
if len(claims.Regioes) == 0 {
|
|
// Legacy user handling - allow SP if they have no list?
|
|
// Schema default is ['SP'], so new users/migrated users should have it.
|
|
// Only broken data would fail.
|
|
if requestedRegion == "SP" {
|
|
allowed = true
|
|
}
|
|
}
|
|
|
|
if !allowed {
|
|
c.AbortWithStatusJSON(http.StatusForbidden, gin.H{"error": "acesso negado a esta região"})
|
|
return
|
|
}
|
|
|
|
c.Set("regiao", requestedRegion)
|
|
c.Next()
|
|
}
|
|
}
|
|
|
|
// RequireWriteAccess middleware to prevent AGENDA_VIEWER from modifying data
|
|
func RequireWriteAccess() gin.HandlerFunc {
|
|
return func(c *gin.Context) {
|
|
role := c.GetString("role")
|
|
if role == "AGENDA_VIEWER" {
|
|
c.AbortWithStatusJSON(http.StatusForbidden, gin.H{"error": "você não tem permissão para modificar dados"})
|
|
return
|
|
}
|
|
c.Next()
|
|
}
|
|
}
|
|
|
|
// RequireLogisticsAccess middleware to prevent AGENDA_VIEWER from accessing logistics
|
|
func RequireLogisticsAccess() gin.HandlerFunc {
|
|
return func(c *gin.Context) {
|
|
role := c.GetString("role")
|
|
if role == "AGENDA_VIEWER" {
|
|
c.AbortWithStatusJSON(http.StatusForbidden, gin.H{"error": "você não tem permissão para acessar logística"})
|
|
return
|
|
}
|
|
c.Next()
|
|
}
|
|
}
|