- Implemented a bash script to test n8n API and retrieve credential schemas. - Added types for API responses, Google Calendar, and WhatsApp instances. - Configured Vitest for testing with React and added setup for testing-library.
171 lines
5.2 KiB
Markdown
171 lines
5.2 KiB
Markdown
# Setup Google OAuth - Guia Rápido
|
|
|
|
## 1. Variáveis de Ambiente (.env.local)
|
|
|
|
```bash
|
|
# Google OAuth (copie do n8n)
|
|
NEXT_PUBLIC_GOOGLE_CLIENT_ID=your-client-id.apps.googleusercontent.com
|
|
GOOGLE_CLIENT_SECRET=your-client-secret
|
|
|
|
# n8n
|
|
N8N_BASE_URL=https://n8n.automatizase.com.br
|
|
N8N_OAUTH_URL_WEBHOOK=https://n8n.automatizase.com.br/webhook/google-calendar-oauth-url
|
|
NEXT_PUBLIC_N8N_CREDENTIAL_ID=ccTThTS9TKsejR7W
|
|
|
|
# Site (localhost em dev, domínio em prod)
|
|
NEXT_PUBLIC_SITE_URL=http://localhost:3000
|
|
|
|
# Supabase
|
|
NEXT_PUBLIC_SUPABASE_URL=your-supabase-url
|
|
NEXT_PUBLIC_SUPABASE_ANON_KEY=your-anon-key
|
|
```
|
|
|
|
## 2. Google Cloud Console - Redirect URIs
|
|
|
|
### Desenvolvimento
|
|
```
|
|
http://localhost:3000/api/google-calendar/callback
|
|
https://n8n.automatizase.com.br/rest/oauth2-credential/callback
|
|
```
|
|
|
|
### Produção
|
|
```
|
|
https://dashboard.automatizase.com.br/api/google-calendar/callback
|
|
https://n8n.automatizase.com.br/rest/oauth2-credential/callback
|
|
```
|
|
|
|
## 3. Onde Encontrar as Credenciais
|
|
|
|
### Client ID e Client Secret (Google)
|
|
1. Acesse n8n → Credentials
|
|
2. Abra a credencial "Google Calendar OAuth2"
|
|
3. Copie `Client ID` e `Client Secret`
|
|
|
|
### N8N Webhook (OAuth URL Generator)
|
|
|
|
Você precisa criar um workflow no n8n que gera a `oauth_url`.
|
|
|
|
**Documentação completa:** [docs/n8n-webhook-oauth-url.md](./docs/n8n-webhook-oauth-url.md)
|
|
|
|
**Resumo rápido:**
|
|
1. Crie um workflow no n8n
|
|
2. Adicione um Webhook trigger com path `/webhook/google-calendar-oauth-url`
|
|
3. Adicione um Code node que gera o state + oauth_url (veja doc)
|
|
4. Adicione um Respond to Webhook que retorna `{ oauthUrl: "..." }`
|
|
5. Ative o workflow
|
|
|
|
### Credential ID (n8n)
|
|
**Via URL:**
|
|
1. No n8n, abra a credencial Google Calendar OAuth2
|
|
2. URL será: `https://n8n.automatizase.com.br/credentials/ccTThTS9TKsejR7W`
|
|
3. O ID é: `ccTThTS9TKsejR7W`
|
|
|
|
**Via curl:**
|
|
```bash
|
|
# Listar credenciais usando API Key
|
|
curl https://n8n.automatizase.com.br/api/v1/credentials \
|
|
-H "X-N8N-API-KEY: n8n_api_xxxxx"
|
|
|
|
# Procurar pelo type: "googleCalendarOAuth2Api"
|
|
# Copiar o "id" da credencial
|
|
```
|
|
|
|
## 4. Tabela Supabase
|
|
|
|
```sql
|
|
-- Criar schema (se não existir)
|
|
CREATE SCHEMA IF NOT EXISTS portal;
|
|
|
|
-- Criar tabela
|
|
CREATE TABLE IF NOT EXISTS portal.integrations (
|
|
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
|
user_id UUID NOT NULL REFERENCES auth.users(id) ON DELETE CASCADE,
|
|
provider VARCHAR(50) NOT NULL,
|
|
status VARCHAR(20) NOT NULL,
|
|
connected_at TIMESTAMPTZ,
|
|
updated_at TIMESTAMPTZ DEFAULT NOW(),
|
|
metadata JSONB,
|
|
UNIQUE(user_id, provider)
|
|
);
|
|
|
|
-- Criar índice
|
|
CREATE INDEX IF NOT EXISTS idx_integrations_user_provider
|
|
ON portal.integrations(user_id, provider);
|
|
```
|
|
|
|
## 5. Testar o Fluxo
|
|
|
|
1. Inicie o servidor: `npm run dev`
|
|
2. Acesse: `http://localhost:3000/dashboard`
|
|
3. Clique em "Conectar Google Calendar"
|
|
4. Autorize no Google
|
|
5. Verifique no Supabase:
|
|
```sql
|
|
SELECT * FROM portal.integrations
|
|
WHERE provider = 'google_calendar';
|
|
```
|
|
|
|
## 6. Troubleshooting
|
|
|
|
### Erro: redirect_uri_mismatch
|
|
- Verifique se adicionou **AMBAS** as URIs no Google Cloud Console
|
|
- Use `http` (não https) para localhost
|
|
|
|
### Erro: Invalid state format
|
|
- Certifique-se que o `NEXT_PUBLIC_N8N_CREDENTIAL_ID` está correto
|
|
- Verifique os logs no console do navegador
|
|
|
|
### Erro: Missing environment variables
|
|
- Verifique se todas as variáveis do `.env.local` estão configuradas
|
|
- Reinicie o servidor após alterar `.env.local`
|
|
|
|
### Erro: Unauthorized ou Failed to generate OAuth URL (n8n)
|
|
- Verifique se o workflow do n8n está ativo
|
|
- Teste o webhook manualmente: `curl https://n8n.automatizase.com.br/webhook/google-calendar-oauth-url?callbackUrl=http://localhost:3000/api/google-calendar/callback`
|
|
- Veja: [docs/n8n-webhook-oauth-url.md](./docs/n8n-webhook-oauth-url.md)
|
|
|
|
### Erro: Failed to save in Supabase
|
|
- Verifique se a tabela `portal.integrations` existe
|
|
- Verifique as permissões do usuário no Supabase
|
|
|
|
## 7. Fluxo Completo
|
|
|
|
```
|
|
Dashboard → GET /api/google-calendar/auth
|
|
↓
|
|
n8n gera oauth_url com state criptografado
|
|
↓
|
|
Dashboard modifica redirect_uri e redireciona
|
|
↓
|
|
Usuário autoriza no Google
|
|
↓
|
|
Google → http://localhost:3000/api/google-calendar/callback
|
|
↓
|
|
Dashboard salva no Supabase
|
|
↓
|
|
Dashboard → https://n8n.automatizase.com.br/rest/oauth2-credential/callback
|
|
↓
|
|
n8n processa OAuth e salva tokens
|
|
↓
|
|
Sucesso! ✅
|
|
```
|
|
|
|
## 8. Documentação Completa
|
|
|
|
- **Fluxo detalhado:** [docs/qa/fluxo-final-google-oauth.md](./docs/qa/fluxo-final-google-oauth.md)
|
|
- **Configuração redirect URIs:** [docs/qa/google-oauth-redirect-uris.md](./docs/qa/google-oauth-redirect-uris.md)
|
|
- **Erro Invalid state format:** [docs/qa/erro-invalid-state-format.md](./docs/qa/erro-invalid-state-format.md)
|
|
|
|
## 9. Checklist
|
|
|
|
- [ ] **Criar workflow no n8n** para gerar oauth_url (veja [docs/n8n-webhook-oauth-url.md](./docs/n8n-webhook-oauth-url.md))
|
|
- [ ] **Ativar workflow** no n8n
|
|
- [ ] **Testar webhook**: `curl https://n8n.automatizase.com.br/webhook/google-calendar-oauth-url?callbackUrl=test`
|
|
- [ ] Configurar `.env.local` com todas as variáveis (incluindo `N8N_OAUTH_URL_WEBHOOK`)
|
|
- [ ] Adicionar redirect URIs no Google Cloud Console
|
|
- [ ] Criar tabela `portal.integrations` no Supabase
|
|
- [ ] Reiniciar servidor Next.js (`npm run dev`)
|
|
- [ ] Testar fluxo OAuth completo
|
|
- [ ] Verificar se dados são salvos no Supabase
|
|
- [ ] Verificar se credencial é atualizada no n8n
|