fix(marketplace): ensure auth token is set before initial requests

This commit is contained in:
Tiago Yamamoto 2025-12-26 17:24:57 -03:00
parent e64b3a4855
commit fd305c00a8
5 changed files with 36256 additions and 5 deletions

View file

@ -49,7 +49,7 @@ func New(cfg config.Config) (*Server, error) {
} }
w.Header().Set("Content-Type", "application/json") w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK) w.WriteHeader(http.StatusOK)
response := `{"message":"💊 SaveInMed API is running!","docs":"/docs/index.html","health":"/health","version":"1.0.0"}` response := `{"message":"💊 SaveInMed API is running!","docs":"/swagger/index.html","health":"/health","version":"1.0.0"}`
_, _ = w.Write([]byte(response)) _, _ = w.Write([]byte(response))
}) })
@ -126,7 +126,7 @@ func New(cfg config.Config) (*Server, error) {
mux.Handle("PUT /api/v1/shipping/settings/{vendor_id}", chain(http.HandlerFunc(h.UpsertShippingSettings), middleware.Logger, middleware.Gzip, auth)) mux.Handle("PUT /api/v1/shipping/settings/{vendor_id}", chain(http.HandlerFunc(h.UpsertShippingSettings), middleware.Logger, middleware.Gzip, auth))
mux.Handle("POST /api/v1/shipping/calculate", chain(http.HandlerFunc(h.CalculateShipping), middleware.Logger, middleware.Gzip)) mux.Handle("POST /api/v1/shipping/calculate", chain(http.HandlerFunc(h.CalculateShipping), middleware.Logger, middleware.Gzip))
mux.Handle("GET /docs/", httpSwagger.Handler(httpSwagger.URL("/docs/doc.json"))) mux.Handle("GET /swagger/", httpSwagger.Handler(httpSwagger.URL("/swagger/doc.json")))
return &Server{cfg: cfg, db: db, mux: mux, svc: svc}, nil return &Server{cfg: cfg, db: db, mux: mux, svc: svc}, nil
} }

View file

@ -30,7 +30,11 @@ const AUTH_KEY = 'mp-auth-user'
export function AuthProvider({ children }: { children: ReactNode }) { export function AuthProvider({ children }: { children: ReactNode }) {
const [user, setUser] = useState<AuthUser | null>(() => { const [user, setUser] = useState<AuthUser | null>(() => {
const persisted = localStorage.getItem(AUTH_KEY) const persisted = localStorage.getItem(AUTH_KEY)
return persisted ? (JSON.parse(persisted) as AuthUser) : null const parsed = persisted ? (JSON.parse(persisted) as AuthUser) : null
if (parsed?.token) {
apiClient.setToken(parsed.token)
}
return parsed
}) })
const [loading, setLoading] = useState(true) const [loading, setLoading] = useState(true)
const navigate = useNavigate() const navigate = useNavigate()

View file

@ -107,7 +107,7 @@ export function LoginPage() {
<svg className="h-5 w-5 shrink-0" fill="none" viewBox="0 0 24 24" stroke="currentColor"> <svg className="h-5 w-5 shrink-0" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" /> <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
</svg> </svg>
<span>credenciais inválidas, tente novamente</span> <span>Ops! Não encontramos esse login. Verifique seu e-mail/usuário e senha.</span>
</div> </div>
)} )}

File diff suppressed because it is too large Load diff

View file

@ -142,7 +142,7 @@ start_backend() {
echo -e "${GREEN} ▶ Executando: go run ./cmd/api${NC}" echo -e "${GREEN} ▶ Executando: go run ./cmd/api${NC}"
echo -e "${CYAN} 📍 API disponível em: http://localhost:${PORT:-8214}${NC}" echo -e "${CYAN} 📍 API disponível em: http://localhost:${PORT:-8214}${NC}"
echo -e "${CYAN} 📚 Swagger UI: http://localhost:${PORT:-8214}/docs/index.html${NC}\n" echo -e "${CYAN} 📚 Swagger UI: http://localhost:${PORT:-8214}/swagger/index.html${NC}\n"
go run ./cmd/api go run ./cmd/api
} }
@ -227,6 +227,82 @@ start_website() {
deno task dev deno task dev
} }
# Função para resetar e popular o banco de dados
reset_db() {
echo -e "\n${RED}⚠️ ATENÇÃO: Isso irá apagar todo o banco de dados e recriá-lo!${NC}"
echo -e "${YELLOW} Isso inclui: companies, users, products, orders, etc.${NC}"
# Se não for chamado via flag (automático), pede confirmação
if [ "$1" != "--force" ]; then
read -p " Deseja continuar? (s/n): " confirm
if [[ ! "$confirm" =~ ^[Ss]$ ]]; then
echo -e "${YELLOW}Operação cancelada.${NC}"
return 0
fi
fi
echo -e "\n${BLUE}🚜 Iniciando Seeder API...${NC}"
# Verificar/instalar Go
ensure_dependency "go" "Go" "install_go" || return 1
cd "$PROJECT_ROOT/seeder-api"
# Carregar variáveis de ambiente
if [ -f "../backend/.env" ]; then
set -a
source ../backend/.env
set +a
fi
# Usar porta diferente para evitar conflito se o seeder tiver padrão diferente
# O seeder usa PORT env var. Vamos definir uma temporária se não estiver definida
export PORT=${PORT:-8216}
# Iniciar seeder em background
echo -e "${YELLOW} ⏳ Aguardando Seeder API iniciar na porta $PORT...${NC}"
go run main.go &
SEEDER_PID=$!
# Aguardar serviço estar pronto
max_retries=30
count=0
while ! curl -s "http://localhost:$PORT/swagger.json" > /dev/null; do
sleep 1
count=$((count+1))
if [ $count -ge $max_retries ]; then
echo -e "${RED}❌ Timeout aguardando Seeder API${NC}"
kill $SEEDER_PID 2>/dev/null
return 1
fi
echo -n "."
done
echo ""
echo -e "${GREEN} ✓ Seeder API online!${NC}"
echo -e "${YELLOW} 🌱 Executando seed (mode=lean)...${NC}"
# Executar seed
HTTP_CODE=$(curl -s -o /tmp/seed_output.json -w "%{http_code}" -X POST "http://localhost:$PORT/seed?mode=lean")
if [ "$HTTP_CODE" == "200" ]; then
echo -e "${GREEN} ✅ Banco de dados resetado e populado com sucesso!${NC}"
cat /tmp/seed_output.json
echo ""
else
echo -e "${RED} ❌ Falha ao rodar seed. Código HTTP: $HTTP_CODE${NC}"
cat /tmp/seed_output.json
echo ""
fi
# Matar seeder
echo -e "${BLUE} 🛑 Parando Seeder API...${NC}"
kill $SEEDER_PID 2>/dev/null
wait $SEEDER_PID 2>/dev/null
echo -e "${GREEN}✨ Concluído!${NC}\n"
}
# Função para exibir o menu # Função para exibir o menu
show_menu() { show_menu() {
echo -e "\n${YELLOW}Selecione o serviço para iniciar:${NC}\n" echo -e "\n${YELLOW}Selecione o serviço para iniciar:${NC}\n"
@ -235,6 +311,8 @@ show_menu() {
echo -e " ${BLUE}3)${NC} Marketplace React ${CYAN}(porta 5173)${NC}" echo -e " ${BLUE}3)${NC} Marketplace React ${CYAN}(porta 5173)${NC}"
echo -e " ${BLUE}4)${NC} Website Fresh/Deno ${CYAN}(porta 8000)${NC}" echo -e " ${BLUE}4)${NC} Website Fresh/Deno ${CYAN}(porta 8000)${NC}"
echo -e "" echo -e ""
echo -e " ${PURPLE}6)${NC} Resetar DB (Seed) ${RED}(Destrutivo)${NC}"
echo -e ""
echo -e " ${GREEN}5)${NC} Iniciar Todos os Serviços" echo -e " ${GREEN}5)${NC} Iniciar Todos os Serviços"
echo -e "" echo -e ""
echo -e " ${RED}0)${NC} Sair" echo -e " ${RED}0)${NC} Sair"
@ -282,6 +360,10 @@ if [ $# -gt 0 ]; then
start_website start_website
exit 0 exit 0
;; ;;
--seed|-s|6)
reset_db "--force"
exit 0
;;
--all|-a|5) --all|-a|5)
show_banner show_banner
start_all_services start_all_services
@ -296,6 +378,7 @@ if [ $# -gt 0 ]; then
echo " --backoffice, -o, 2 Iniciar Backoffice NestJS (porta 3000)" echo " --backoffice, -o, 2 Iniciar Backoffice NestJS (porta 3000)"
echo " --marketplace, -m, 3 Iniciar Marketplace React (porta 5173)" echo " --marketplace, -m, 3 Iniciar Marketplace React (porta 5173)"
echo " --website, -w, 4 Iniciar Website Deno (porta 8000)" echo " --website, -w, 4 Iniciar Website Deno (porta 8000)"
echo " --seed, -s, 6 Resetar DB e rodar Seed (com --force)"
echo " --all, -a, 5 Iniciar todos os serviços" echo " --all, -a, 5 Iniciar todos os serviços"
echo " --help, -h Mostrar esta ajuda" echo " --help, -h Mostrar esta ajuda"
echo "" echo ""
@ -343,6 +426,10 @@ while true; do
start_website start_website
break break
;; ;;
6)
reset_db
break
;;
5) 5)
start_all_services start_all_services
break break