QrRapido/Scripts/README-ADMIN-API.md
Ricardo Carneiro 2edb4e1196
All checks were successful
Deploy QR Rapido / test (push) Successful in 41s
Deploy QR Rapido / build-and-push (push) Successful in 14m6s
Deploy QR Rapido / deploy-staging (push) Has been skipped
Deploy QR Rapido / deploy-production (push) Successful in 1m55s
fix: ajustar para configuração de plano ficam só no mongondb.
2025-10-19 21:48:45 -03:00

273 lines
5.2 KiB
Markdown
Raw Blame History

This file contains invisible Unicode characters

This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# 🔧 Admin API - Gerenciamento de Planos
Este diretório contém ferramentas para gerenciar os planos do Stripe no MongoDB via API local.
## 🔒 Segurança
**IMPORTANTE**: O endpoint `/api/Admin/*` **só funciona quando acessado de localhost** (127.0.0.1). Qualquer acesso externo retornará `403 Forbidden`.
---
## 📋 Arquivos
- **`plans.json`** - Configuração dos planos com Price IDs do Stripe
- **`update-plans.sh`** - Script bash para atualizar planos via curl
- **`seed-mongodb-plans.js`** - Script MongoDB direto (método alternativo)
---
## 🚀 Método 1: API Endpoint (Recomendado)
### Vantagens
- ✅ Não precisa de credenciais do MongoDB
- ✅ Validação automática
- ✅ Logs no sistema
- ✅ Funciona com app rodando
### Como Usar
#### 1⃣ Edite o `plans.json` com seus Price IDs
```json
{
"pricesByCountry": {
"BR": {
"stripePriceId": "price_SEU_ID_AQUI"
}
}
}
```
#### 2⃣ Inicie a aplicação
```bash
dotnet run
# ou
dotnet watch run
```
#### 3⃣ Execute o script de atualização
```bash
# Linux/Mac/WSL
cd Scripts
./update-plans.sh
# Especificar porta diferente
./update-plans.sh 5000
```
#### 4⃣ Ou use curl diretamente
```bash
# Atualizar planos
curl -k -X POST \
-H "Content-Type: application/json" \
-d @Scripts/plans.json \
https://localhost:52428/api/Admin/SeedPlans
# Listar planos
curl -k https://localhost:52428/api/Admin/Plans
# Deletar todos os planos
curl -k -X DELETE https://localhost:52428/api/Admin/Plans
```
---
## 🗄️ Método 2: Script MongoDB Direto
### Vantagens
- ✅ Funciona sem a app rodando
- ✅ Acesso direto ao MongoDB
### Desvantagens
- ❌ Precisa de credenciais do MongoDB
- ❌ Sem validação automática
### Como Usar
```bash
# Localhost
mongosh "mongodb://localhost:27017/QrRapido" < Scripts/seed-mongodb-plans.js
# Produção
mongosh "mongodb://user:pass@host:27017/QrRapido?replicaSet=rs0&authSource=admin" < Scripts/seed-mongodb-plans.js
```
---
## 📝 Endpoints Disponíveis
### POST `/api/Admin/SeedPlans`
Cria ou atualiza planos no MongoDB
**Request Body:**
```json
[
{
"interval": "month",
"stripePriceId": "price_...",
"pricesByCountry": { ... }
}
]
```
**Response:**
```json
{
"success": true,
"message": "2 plans seeded successfully",
"plans": [ ... ]
}
```
---
### GET `/api/Admin/Plans`
Lista todos os planos do MongoDB
**Response:**
```json
{
"success": true,
"count": 2,
"plans": [ ... ]
}
```
---
### DELETE `/api/Admin/Plans`
Remove todos os planos do MongoDB
**Response:**
```json
{
"success": true,
"deletedCount": 2
}
```
---
## 🛡️ Proteção de Segurança
O código verifica o IP de origem:
```csharp
var remoteIp = HttpContext.Connection.RemoteIpAddress;
var isLocalhost = remoteIp != null &&
(remoteIp.ToString() == "127.0.0.1" ||
remoteIp.ToString() == "::1" ||
remoteIp.ToString() == "localhost");
if (!isLocalhost) {
return Forbid("This endpoint is only accessible from localhost");
}
```
**Tentativas de acesso externo são logadas:**
```
[Warning] Unauthorized admin access attempt from 192.168.1.100
```
---
## 🧪 Testando
```bash
# 1. Listar planos atuais
curl -k https://localhost:52428/api/Admin/Plans | jq '.'
# 2. Deletar planos
curl -k -X DELETE https://localhost:52428/api/Admin/Plans
# 3. Criar novos planos
curl -k -X POST \
-H "Content-Type: application/json" \
-d @Scripts/plans.json \
https://localhost:52428/api/Admin/SeedPlans | jq '.'
# 4. Verificar se foram criados
curl -k https://localhost:52428/api/Admin/Plans | jq '.plans[] | {interval, priceIds: .pricesByCountry}'
```
---
## ⚠️ Troubleshooting
### Erro: "Connection refused"
- ✅ Certifique-se que a app está rodando: `dotnet run`
### Erro: "Forbidden" mesmo em localhost
- ✅ Verifique se está usando `https://localhost` (não `http://`)
- ✅ Verifique se está usando `localhost` ou `127.0.0.1` (não o IP da máquina)
### Erro: "SSL certificate problem"
- ✅ Use o flag `-k` no curl para aceitar certificados auto-assinados
---
## 📊 Estrutura do plans.json
```json
[
{
"name": {
"pt-BR": "Nome em português",
"es-PY": "Nombre en español",
"en": "Name in english"
},
"description": { ... },
"features": { ... },
"interval": "month" ou "year",
"stripePriceId": "price_default",
"pricesByCountry": {
"BR": {
"amount": 9.90,
"currency": "BRL",
"stripePriceId": "price_BR_ID"
},
"PY": {
"amount": 35000,
"currency": "PYG",
"stripePriceId": "price_PY_ID"
}
},
"isActive": true,
"displayOrder": 1,
"badge": { ... } // Opcional
}
]
```
---
## 🎯 Fluxo Recomendado
1. **Desenvolvimento (localhost)**:
```bash
# Editar plans.json com Price IDs de teste
./update-plans.sh
```
2. **Staging**:
```bash
# SSH no servidor staging
ssh user@staging-server
cd /app/qrrapido
./Scripts/update-plans.sh 5000
```
3. **Produção**:
```bash
# Opção 1: Via API (se tiver acesso SSH)
ssh user@prod-server
cd /app/qrrapido
./Scripts/update-plans.sh 5001
# Opção 2: Via MongoDB direto
mongosh "connection_string" < Scripts/seed-mongodb-plans.js
```