@ai-growth/n8n-nodes-wordpress
Version:
n8n node for WordPress integration with AI GROWTH - SEO WP plugin
310 lines • 13.2 kB
JavaScript
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.AuthTester = void 0;
const axios_1 = __importDefault(require("axios"));
const Validator_1 = require("./Validator");
const Logger_1 = require("./Logger");
/**
* Classe para testar a conexão com a API do WordPress
*/
class AuthTester {
/**
* Testa a conexão com a API do WordPress
* @param credentials Credenciais a serem testadas
* @returns Resultado do teste de conexão
*/
static async testConnection(credentials) {
var _a, _b, _c, _d, _e, _f, _g, _h;
this.logger.info('Starting WordPress connection test');
this.logger.debug('Testing credentials:', {
url: credentials.url,
username: credentials.username,
passwordLength: ((_a = credentials.password) === null || _a === void 0 ? void 0 : _a.length) || 0,
});
// Validar credenciais
this.logger.debug('Validating credentials...');
const validationResult = Validator_1.Validator.validateCredentials(credentials);
if (!validationResult.valid) {
this.logger.error('Credential validation failed:', validationResult.error);
return {
success: false,
message: validationResult.error || 'Invalid credentials',
};
}
this.logger.debug('Credentials validation passed');
// Sanitizar URL
const baseUrl = Validator_1.Validator.sanitizeUrl(credentials.url);
this.logger.debug('Sanitized URL:', baseUrl);
// Testar conectividade básica primeiro
const connectivityTest = await this.testBasicConnectivity(baseUrl);
if (!connectivityTest.success) {
return connectivityTest;
}
try {
const apiUrl = `${baseUrl}/wp-json/wp/v2`;
this.logger.connection(apiUrl, 'attempting');
// Tentar fazer uma requisição para a API do WordPress
const requestConfig = {
auth: {
username: credentials.username,
password: credentials.password,
},
timeout: 10000, // 10 segundos de timeout
headers: {
'User-Agent': 'n8n-wordpress-node/1.0',
'Accept': 'application/json',
},
};
this.logger.auth('Basic Auth', 'attempting', {
username: credentials.username,
headers: requestConfig.headers,
});
const response = await axios_1.default.get(apiUrl, requestConfig);
this.logger.connection(apiUrl, 'success', {
status: response.status,
headers: response.headers,
dataKeys: Object.keys(response.data || {}),
});
this.logger.auth('Basic Auth', 'success');
// Verificar se a resposta é válida
if (response.status === 200) {
this.logger.info('WordPress API connection test successful');
this.logger.debug('API response data:', {
name: (_b = response.data) === null || _b === void 0 ? void 0 : _b.name,
description: (_c = response.data) === null || _c === void 0 ? void 0 : _c.description,
url: (_d = response.data) === null || _d === void 0 ? void 0 : _d.url,
home: (_e = response.data) === null || _e === void 0 ? void 0 : _e.home,
routes: Object.keys(((_f = response.data) === null || _f === void 0 ? void 0 : _f.routes) || {}),
});
return {
success: true,
message: 'Connection successful',
data: response.data,
};
}
else {
this.logger.warn(`Unexpected response status: ${response.status}`);
return {
success: false,
message: `Unexpected response status: ${response.status}`,
};
}
}
catch (error) {
const axiosError = error;
this.logger.connection(baseUrl, 'failed', {
error: axiosError.message,
code: axiosError.code,
status: (_g = axiosError.response) === null || _g === void 0 ? void 0 : _g.status,
});
this.logger.auth('Basic Auth', 'failed', {
error: axiosError.message,
status: (_h = axiosError.response) === null || _h === void 0 ? void 0 : _h.status,
});
// Tratar diferentes tipos de erros
if (axiosError.response) {
// A requisição foi feita e o servidor respondeu com um status diferente de 2xx
this.logger.error('Server responded with error:', {
status: axiosError.response.status,
statusText: axiosError.response.statusText,
data: axiosError.response.data,
headers: axiosError.response.headers,
});
if (axiosError.response.status === 401) {
this.logger.error('Authentication failed - 401 Unauthorized');
return {
success: false,
message: 'Authentication failed: Invalid username or application password',
error: axiosError,
};
}
else if (axiosError.response.status === 404) {
this.logger.error('WordPress REST API not found - 404');
return {
success: false,
message: 'WordPress REST API not found. Please ensure the REST API is enabled and the URL is correct.',
error: axiosError,
};
}
else {
this.logger.error(`Server error - ${axiosError.response.status}`);
return {
success: false,
message: `Server error: ${axiosError.response.status} - ${axiosError.response.statusText}`,
error: axiosError,
};
}
}
else if (axiosError.request) {
// A requisição foi feita mas não houve resposta
this.logger.error('No response from server:', {
request: {
method: axiosError.request.method,
url: axiosError.request.url,
headers: axiosError.request.headers,
},
code: axiosError.code,
});
return {
success: false,
message: 'No response from server. Please check the URL and ensure the WordPress site is online.',
error: axiosError,
};
}
else {
// Ocorreu um erro ao configurar a requisição
this.logger.error('Request setup error:', axiosError.message);
return {
success: false,
message: `Error setting up the request: ${axiosError.message}`,
error: axiosError,
};
}
}
}
/**
* Testa conectividade básica antes de tentar autenticação
* @param baseUrl URL base do WordPress
* @returns Resultado do teste de conectividade
*/
static async testBasicConnectivity(baseUrl) {
var _a;
this.logger.debug('Testing basic connectivity...');
try {
// Primeiro, testar se o site responde
const siteUrl = baseUrl;
this.logger.network('DNS Resolution', { url: siteUrl });
const basicResponse = await axios_1.default.get(siteUrl, {
timeout: 5000,
maxRedirects: 5,
headers: {
'User-Agent': 'n8n-wordpress-node/1.0',
},
});
this.logger.network('Site Response', {
status: basicResponse.status,
headers: basicResponse.headers,
contentType: basicResponse.headers['content-type'],
});
// Testar se o endpoint wp-json existe
const wpJsonUrl = `${baseUrl}/wp-json`;
this.logger.network('WP-JSON Test', { url: wpJsonUrl });
const wpJsonResponse = await axios_1.default.get(wpJsonUrl, {
timeout: 5000,
headers: {
'User-Agent': 'n8n-wordpress-node/1.0',
'Accept': 'application/json',
},
});
this.logger.network('WP-JSON Response', {
status: wpJsonResponse.status,
data: wpJsonResponse.data,
});
this.logger.debug('Basic connectivity test passed');
return {
success: true,
message: 'Basic connectivity successful',
};
}
catch (error) {
const axiosError = error;
this.logger.error('Basic connectivity failed:', {
error: axiosError.message,
code: axiosError.code,
status: (_a = axiosError.response) === null || _a === void 0 ? void 0 : _a.status,
});
if (axiosError.code === 'ENOTFOUND') {
return {
success: false,
message: 'Domain not found. Please check the URL.',
error: axiosError,
};
}
else if (axiosError.code === 'ECONNREFUSED') {
return {
success: false,
message: 'Connection refused. The server may be down.',
error: axiosError,
};
}
else if (axiosError.code === 'ECONNABORTED') {
return {
success: false,
message: 'Connection timeout. The server is taking too long to respond.',
error: axiosError,
};
}
return {
success: false,
message: `Connectivity error: ${axiosError.message}`,
error: axiosError,
};
}
}
/**
* Verifica se o plugin AI GROWTH - SEO WP está ativo
* @param credentials Credenciais do WordPress
* @returns Resultado do teste
*/
static async checkAiGrowthPlugin(credentials) {
var _a;
this.logger.info('Checking AI GROWTH - SEO WP plugin...');
const baseUrl = Validator_1.Validator.sanitizeUrl(credentials.url);
try {
const pluginUrl = `${baseUrl}/wp-json/ai-growth-seo/v1/info`;
this.logger.debug('Testing plugin endpoint:', pluginUrl);
// Verificar se o endpoint específico do plugin existe
const response = await axios_1.default.get(pluginUrl, {
auth: {
username: credentials.username,
password: credentials.password,
},
timeout: 10000,
headers: {
'User-Agent': 'n8n-wordpress-node/1.0',
'Accept': 'application/json',
},
});
this.logger.debug('Plugin response:', {
status: response.status,
data: response.data,
});
if (response.status === 200) {
this.logger.info('AI GROWTH - SEO WP plugin is active');
return {
success: true,
message: 'AI GROWTH - SEO WP plugin is active',
data: response.data,
};
}
else {
this.logger.warn('Plugin endpoint returned unexpected response:', response.status);
return {
success: false,
message: 'AI GROWTH - SEO WP plugin endpoint returned an unexpected response',
};
}
}
catch (error) {
const axiosError = error;
this.logger.warn('AI GROWTH - SEO WP plugin check failed:', {
error: axiosError.message,
status: (_a = axiosError.response) === null || _a === void 0 ? void 0 : _a.status,
});
return {
success: false,
message: 'AI GROWTH - SEO WP plugin is not active or not installed',
error: error,
};
}
}
}
exports.AuthTester = AuthTester;
AuthTester.logger = new Logger_1.Logger({
prefix: '[AuthTester]',
level: Logger_1.LogLevel.DEBUG,
});
//# sourceMappingURL=AuthTester.js.map