281 lines
8.9 KiB
Markdown
Executable file
281 lines
8.9 KiB
Markdown
Executable file
# Backend - GoHorse Jobs API
|
|
|
|
[](https://golang.org/)
|
|
[](https://postgresql.org/)
|
|
|
|
API REST desenvolvida em Go seguindo princípios de **Clean Architecture** e **DDD**.
|
|
|
|
---
|
|
|
|
## 🏗️ Arquitetura
|
|
|
|
```
|
|
backend/
|
|
├── cmd/
|
|
│ ├── api/ # Entrypoint principal
|
|
│ └── manual_migrate/ # Migration runner
|
|
│
|
|
├── internal/
|
|
│ ├── api/ # Clean Architecture Layer
|
|
│ │ ├── handlers/ # HTTP Handlers (Admin, Auth, Settings, Storage)
|
|
│ │ └── middleware/ # Auth, CORS, Rate Limiting, Sanitize
|
|
│ │
|
|
│ ├── core/ # Domain Layer (DDD)
|
|
│ │ ├── domain/entity/ # Entidades (User, Company, Email)
|
|
│ │ ├── ports/ # Interfaces (Repositories)
|
|
│ │ └── usecases/ # Casos de uso (Auth, Register)
|
|
│ │
|
|
│ ├── infrastructure/ # Infrastructure Layer
|
|
│ │ ├── auth/ # JWT Service implementation
|
|
│ │ └── persistence/ # Repository implementations (Postgres)
|
|
│ │
|
|
│ ├── dto/ # Data Transfer Objects
|
|
│ ├── handlers/ # Legacy controllers (Job, Application)
|
|
│ ├── middleware/ # Security middlewares
|
|
│ ├── models/ # GORM models
|
|
│ ├── router/ # Route configuration
|
|
│ ├── services/ # Business logic services
|
|
│ └── utils/ # Helpers (JWT, Sanitizer)
|
|
│
|
|
├── migrations/ # SQL Migrations (30+)
|
|
├── tests/ # E2E and Integration tests
|
|
└── docs/ # Swagger documentation
|
|
```
|
|
|
|
---
|
|
|
|
## 🔧 Services
|
|
|
|
| Service | Arquivo | Descrição |
|
|
|---------|---------|-----------|
|
|
| **AdminService** | `admin_service.go` | CRUD de empresas, usuários, candidatos, tags, email templates |
|
|
| **JobService** | `job_service.go` | CRUD de vagas com filtros avançados |
|
|
| **ApplicationService** | `application_service.go` | Gestão de candidaturas |
|
|
| **TicketService** | `ticket_service.go` | Sistema de tickets de suporte |
|
|
| **ChatService** | `chat_service.go` | Mensagens e conversas (Appwrite) |
|
|
| **NotificationService** | `notification_service.go` | Notificações push |
|
|
| **EmailService** | `email_service.go` | Produtor de emails via LavinMQ |
|
|
| **FCMService** | `fcm_service.go` | Firebase Cloud Messaging |
|
|
| **StorageService** | `storage_service.go` | Pre-signed URLs (S3/R2) |
|
|
| **CredentialsService** | `credentials_service.go` | Gestão de credenciais criptografadas |
|
|
| **CloudflareService** | `cloudflare_service.go` | Cache purge via API |
|
|
| **SettingsService** | `settings_service.go` | System settings |
|
|
| **AppwriteService** | `appwrite_service.go` | Integração Appwrite Realtime |
|
|
| **AuditService** | `audit_service.go` | Logs de auditoria |
|
|
|
|
---
|
|
|
|
## 🔒 Segurança
|
|
|
|
### Middlewares Implementados
|
|
|
|
| Middleware | Arquivo | Descrição |
|
|
|------------|---------|-----------|
|
|
| **Auth** | `middleware/auth.go` | Validação JWT + RBAC |
|
|
| **CORS** | `middleware/cors.go` | Whitelist de origens via `CORS_ORIGINS` |
|
|
| **Rate Limiting** | `middleware/rate_limit.go` | 100 req/min por IP |
|
|
| **Security Headers** | `middleware/security_headers.go` | OWASP headers (XSS, CSP, etc.) |
|
|
| **Sanitize** | `middleware/sanitize.go` | XSS sanitization em JSON bodies |
|
|
|
|
### Autenticação
|
|
|
|
- **JWT** com expiração configurável
|
|
- **Password Pepper** via `PASSWORD_PEPPER` env var
|
|
- **HttpOnly Cookies** para refresh tokens
|
|
- **RSA Encryption** para credenciais sensíveis
|
|
|
|
---
|
|
|
|
## 📡 Endpoints
|
|
|
|
### Públicos
|
|
|
|
| Método | Endpoint | Descrição |
|
|
|--------|----------|-----------|
|
|
| `GET` | `/` | Root check |
|
|
| `GET` | `/health` | Health check |
|
|
| `GET` | `/docs/*` | Swagger UI |
|
|
| `POST` | `/api/v1/auth/login` | Login |
|
|
| `POST` | `/api/v1/auth/register/candidate` | Registro de candidato |
|
|
| `POST` | `/api/v1/auth/register/company` | Registro de empresa |
|
|
| `GET` | `/api/v1/jobs` | Listar vagas (filtros, paginação) |
|
|
| `GET` | `/api/v1/jobs/{id}` | Detalhes da vaga |
|
|
| `GET` | `/api/v1/companies/{id}` | Detalhes da empresa |
|
|
|
|
### Protegidos (JWT Required)
|
|
|
|
| Método | Endpoint | Roles | Descrição |
|
|
|--------|----------|-------|-----------|
|
|
| `GET` | `/api/v1/users/me` | `any` | Perfil do usuário |
|
|
| `PATCH` | `/api/v1/users/me/profile` | `any` | Atualizar perfil |
|
|
| `GET` | `/api/v1/users` | `admin`, `superadmin` | Listar usuários |
|
|
| `POST` | `/api/v1/users` | `admin`, `superadmin` | Criar usuário |
|
|
| `DELETE` | `/api/v1/users/{id}` | `superadmin` | Deletar usuário |
|
|
|
|
### Vagas (Autenticado)
|
|
|
|
| Método | Endpoint | Roles | Descrição |
|
|
|--------|----------|-------|-----------|
|
|
| `POST` | `/api/v1/jobs` | `admin`, `recruiter` | Criar vaga |
|
|
| `PUT` | `/api/v1/jobs/{id}` | `admin`, `recruiter` | Atualizar vaga |
|
|
| `DELETE` | `/api/v1/jobs/{id}` | `admin` | Deletar vaga |
|
|
|
|
### Admin
|
|
|
|
| Método | Endpoint | Descrição |
|
|
|--------|----------|-----------|
|
|
| `GET` | `/api/v1/admin/companies` | Listar empresas |
|
|
| `PATCH` | `/api/v1/admin/companies/{id}/status` | Aprovar/Suspender empresa |
|
|
| `GET` | `/api/v1/admin/email-templates` | Listar templates de email |
|
|
| `POST` | `/api/v1/admin/email-templates` | Criar template |
|
|
| `PUT` | `/api/v1/admin/email-templates/{slug}` | Atualizar template |
|
|
| `DELETE` | `/api/v1/admin/email-templates/{slug}` | Deletar template |
|
|
| `GET` | `/api/v1/admin/email-settings` | Obter configurações SMTP |
|
|
| `PUT` | `/api/v1/admin/email-settings` | Atualizar configurações SMTP |
|
|
|
|
### Outros
|
|
|
|
| Método | Endpoint | Descrição |
|
|
|--------|----------|-----------|
|
|
| `GET` | `/api/v1/storage/upload-url` | Pre-signed URL para upload |
|
|
| `GET` | `/api/v1/notifications` | Listar notificações |
|
|
| `POST` | `/api/v1/tokens` | Salvar FCM token |
|
|
| `GET` | `/api/v1/support/tickets` | Listar tickets |
|
|
| `POST` | `/api/v1/support/tickets` | Criar ticket |
|
|
| `GET` | `/api/v1/conversations` | Listar conversas |
|
|
| `POST` | `/api/v1/conversations/{id}/messages` | Enviar mensagem |
|
|
|
|
---
|
|
|
|
## 🗄️ Migrations
|
|
|
|
O projeto usa um sistema de migrations manuais via `cmd/manual_migrate`.
|
|
|
|
### Principais Migrations
|
|
|
|
| # | Arquivo | Descrição |
|
|
|---|---------|-----------|
|
|
| 000 | `000_init_uuid_v7.sql` | Função UUID v7 |
|
|
| 001 | `001_create_users_table.sql` | Tabela de usuários |
|
|
| 002 | `002_create_companies_table.sql` | Tabela de empresas |
|
|
| 005 | `005_create_jobs_table.sql` | Tabela de vagas |
|
|
| 006 | `006_create_applications_table.sql` | Tabela de candidaturas |
|
|
| 016 | `016_create_notifications_table.sql` | Notificações |
|
|
| 017 | `017_create_tickets_table.sql` | Tickets de suporte |
|
|
| 021 | `021_location_hierarchy.sql` | Países, regiões, cidades |
|
|
| 024 | `024_create_external_services_credentials.sql` | Credenciais criptografadas |
|
|
| 025 | `025_create_chat_tables.sql` | Conversas e mensagens |
|
|
| 026 | `026_create_system_settings.sql` | Configurações do sistema |
|
|
| 027 | `027_create_email_system.sql` | Templates e configurações de email |
|
|
| 028 | `028_add_avatar_url_to_users.sql` | Avatar de usuário |
|
|
|
|
### Executar Migrations
|
|
|
|
```bash
|
|
go run ./cmd/manual_migrate
|
|
```
|
|
|
|
---
|
|
|
|
## 🔧 Environment Variables
|
|
|
|
```bash
|
|
# Database
|
|
DATABASE_URL=postgres://user:pass@host:5432/dbname
|
|
|
|
# Auth
|
|
JWT_SECRET=your-secret-key-min-32-chars
|
|
PASSWORD_PEPPER=your-pepper-key
|
|
|
|
# CORS
|
|
CORS_ORIGINS=https://frontend.com,https://admin.com
|
|
|
|
# External Services
|
|
RSA_PRIVATE_KEY_BASE64=base64-encoded-private-key
|
|
|
|
# Optional
|
|
PORT=8080
|
|
ENV=production
|
|
```
|
|
|
|
---
|
|
|
|
## 🚀 Desenvolvimento
|
|
|
|
### Executar
|
|
|
|
```bash
|
|
# Copiar .env
|
|
cp .env.example .env
|
|
|
|
# Executar migrations
|
|
go run ./cmd/manual_migrate
|
|
|
|
# Iniciar servidor
|
|
go run ./cmd/api
|
|
```
|
|
|
|
### Testes
|
|
|
|
```bash
|
|
# Todos os testes
|
|
go test ./...
|
|
|
|
# Com cobertura
|
|
go test -cover ./...
|
|
|
|
# Verbose
|
|
go test -v ./internal/services/...
|
|
```
|
|
|
|
### Build
|
|
|
|
```bash
|
|
go build -o api ./cmd/api
|
|
```
|
|
|
|
### Regenerar Swagger
|
|
|
|
```bash
|
|
swag init -g cmd/api/main.go --parseDependency --parseInternal
|
|
```
|
|
|
|
---
|
|
|
|
## 🐳 Docker
|
|
|
|
```bash
|
|
# Build
|
|
docker build -t gohorse-backend .
|
|
|
|
# Run
|
|
docker run -p 8080:8080 --env-file .env gohorse-backend
|
|
```
|
|
|
|
**Imagem otimizada:** ~73MB (Alpine + non-root user)
|
|
|
|
---
|
|
|
|
## 📁 Arquivos Importantes
|
|
|
|
| Arquivo | Descrição |
|
|
|---------|-----------|
|
|
| `cmd/api/main.go` | Entrypoint da aplicação |
|
|
| `cmd/manual_migrate/main.go` | Migration runner |
|
|
| `internal/router/router.go` | Configuração de todas as rotas |
|
|
| `internal/database/database.go` | Conexão GORM com PostgreSQL |
|
|
| `migrations/*.sql` | Migrations do banco de dados |
|
|
| `docs/swagger.json` | Documentação OpenAPI gerada |
|
|
|
|
---
|
|
|
|
## 🔗 Integrações
|
|
|
|
| Serviço | Uso |
|
|
|---------|-----|
|
|
| **LavinMQ** | Fila de emails assíncronos |
|
|
| **Appwrite** | Chat realtime |
|
|
| **Firebase** | Push notifications (FCM) |
|
|
| **Cloudflare** | CDN com cache purge |
|
|
| **S3/R2** | Storage com pre-signed URLs |
|
|
| **Stripe** | Pagamentos (via Backoffice) |
|