189 lines
4.6 KiB
Markdown
189 lines
4.6 KiB
Markdown
# Arquitetura Backend + Traefik - Aggios
|
|
|
|
## 📋 Estrutura do Projeto
|
|
|
|
```
|
|
backend/
|
|
├── cmd/server/
|
|
│ └── main.go # Entry point da aplicação
|
|
├── internal/
|
|
│ ├── api/
|
|
│ │ ├── handlers/ # Handlers HTTP
|
|
│ │ ├── middleware/ # Middlewares (JWT, CORS, etc)
|
|
│ │ └── routes.go # Definição das rotas
|
|
│ ├── auth/ # Lógica de autenticação (JWT, OAuth2)
|
|
│ ├── config/ # Configuração da aplicação
|
|
│ ├── database/ # Conexão e migrations do DB
|
|
│ ├── models/ # Estruturas de dados
|
|
│ ├── services/ # Lógica de negócio
|
|
│ └── storage/ # Redis e MinIO
|
|
├── migrations/ # SQL migrations
|
|
├── go.mod
|
|
├── go.sum
|
|
├── Dockerfile
|
|
└── .env.example
|
|
```
|
|
|
|
## 🔐 Segurança & Autenticação
|
|
|
|
### JWT (JSON Web Tokens)
|
|
- **Access Token**: 24 horas de expiração
|
|
- **Refresh Token**: 7 dias de expiração
|
|
- **Algoritmo**: HS256
|
|
- **Payload**: `user_id`, `email`, `tenant_id`
|
|
|
|
### Password Security
|
|
- Hash com Argon2 (mais seguro que bcrypt)
|
|
- Salt aleatório por senha
|
|
- Pepper no servidor (JWT_SECRET)
|
|
|
|
### Multi-Tenant
|
|
- Isolamento por `tenant_id` no JWT
|
|
- Validação de tenant em cada requisição
|
|
- Subdomain routing automático via Traefik
|
|
|
|
## 🔄 Fluxo de Autenticação
|
|
|
|
```
|
|
1. POST /api/auth/login
|
|
└── Validar email/password
|
|
└── Gerar Access Token (24h) + Refresh Token (7d)
|
|
└── Salvar hash do refresh token no Redis/DB
|
|
|
|
2. API Requests
|
|
└── Header: Authorization: Bearer {access_token}
|
|
└── Middleware JWT valida token
|
|
└── user_id e tenant_id adicionados ao contexto
|
|
|
|
3. Token Expirado
|
|
└── POST /api/auth/refresh com refresh_token
|
|
└── Novo access token gerado
|
|
└── Refresh token pode rotacionar (opcional)
|
|
|
|
4. Logout
|
|
└── POST /api/logout
|
|
└── Invalidar refresh token no Redis
|
|
└── Client descarta access token
|
|
```
|
|
|
|
## 🌍 Multi-Tenant com Traefik
|
|
|
|
### Routing automático:
|
|
- `api.aggios.app` → Backend geral
|
|
- `{subdomain}.aggios.app` → Tenant específico (ex: acme.aggios.app)
|
|
- Traefik resolve hostname → passa para backend
|
|
- Backend extrai `tenant_id` do JWT
|
|
|
|
### Exemplo:
|
|
```
|
|
Cliente acme.aggios.app → Traefik
|
|
↓
|
|
Extrai subdomain: "acme"
|
|
↓
|
|
Backend recebe request com tenant_id
|
|
JWT validado para tenant "acme"
|
|
↓
|
|
Acesso apenas aos dados do "acme"
|
|
```
|
|
|
|
## 📦 Serviços Docker
|
|
|
|
### PostgreSQL 16
|
|
- Multi-tenant database
|
|
- Conexão: `postgres:5432`
|
|
- Migrations automáticas no startup
|
|
|
|
### Redis 7
|
|
- Cache de sessões
|
|
- Invalidação de refresh tokens
|
|
- Conexão: `redis:6379`
|
|
|
|
### MinIO
|
|
- S3-compatible storage
|
|
- Para uploads (agências, documentos, etc)
|
|
- Console: `http://minio-console.localhost`
|
|
- API: `http://minio.localhost`
|
|
|
|
### Traefik
|
|
- Reverse proxy com auto-discovery Docker
|
|
- SSL/TLS com Let's Encrypt
|
|
- Dashboard: `http://traefik.localhost`
|
|
- Suporta wildcard subdomains
|
|
|
|
## 🚀 Inicialização
|
|
|
|
```bash
|
|
# 1. Copiar .env
|
|
cp .env.example .env
|
|
|
|
# 2. Editar .env com valores seguros
|
|
nano .env
|
|
|
|
# 3. Build e start
|
|
docker-compose up -d
|
|
|
|
# 4. Logs
|
|
docker-compose logs -f backend
|
|
|
|
# 5. Testar health
|
|
curl http://localhost:8080/api/health
|
|
```
|
|
|
|
## 📱 API Mobile-Ready
|
|
|
|
A API está preparada para:
|
|
- ✅ REST com JSON
|
|
- ✅ CORS habilitado
|
|
- ✅ JWT stateless (não precisa cookies)
|
|
- ✅ Versionamento de API (`/api/v1/*`)
|
|
- ✅ Rate limiting
|
|
- ✅ Error handling padronizado
|
|
|
|
### Exemplo Android/iOS:
|
|
```javascript
|
|
// Login
|
|
POST /api/auth/login
|
|
{
|
|
"email": "user@example.com",
|
|
"password": "senha123"
|
|
}
|
|
|
|
// Response
|
|
{
|
|
"access_token": "eyJ...",
|
|
"refresh_token": "xxx...",
|
|
"token_type": "Bearer",
|
|
"expires_in": 86400
|
|
}
|
|
|
|
// Request autenticado
|
|
GET /api/users/me
|
|
Authorization: Bearer eyJ...
|
|
```
|
|
|
|
## 🔍 Próximos Passos
|
|
|
|
1. Implementar Argon2 para hashing de senhas
|
|
2. Adicionar OAuth2 (Google, GitHub)
|
|
3. Rate limiting por IP/tenant
|
|
4. Audit logging
|
|
5. Metrics (Prometheus)
|
|
6. Health checks avançados
|
|
7. Graceful shutdown
|
|
8. Request validation middleware
|
|
9. API documentation (Swagger)
|
|
10. Tests (unit + integration)
|
|
|
|
## 🛡️ Production Checklist
|
|
|
|
- [ ] Mudar JWT_SECRET
|
|
- [ ] Configurar HTTPS real (Let's Encrypt)
|
|
- [ ] Habilitar SSL no PostgreSQL
|
|
- [ ] Configurar backups automatizados
|
|
- [ ] Monitoramento (Sentry, DataDog)
|
|
- [ ] Logging centralizado
|
|
- [ ] Rate limiting agressivo
|
|
- [ ] WAF (Web Application Firewall)
|
|
- [ ] Secrets em vault (HashiCorp Vault)
|
|
- [ ] CORS restritivo
|