UNPKG

@inite/n8n-nodes-instagram-private-api

Version:
94 lines (93 loc) 3.99 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.authenticateInstagram = void 0; const n8n_workflow_1 = require("n8n-workflow"); async function authenticateInstagram(ig, credentials, node) { var _a, _b; try { // Generate device ig.state.generateDevice(credentials.username); // Set proxy if provided if (credentials.proxy) { ig.state.proxyUrl = credentials.proxy; } // Try to use stored session if available if (credentials.sessionStorage && credentials.sessionData) { try { // Parse and set the stored session const sessionData = JSON.parse(credentials.sessionData); const state = ig.state; state.deviceString = sessionData.deviceString; state.deviceId = sessionData.deviceId; state.uuid = sessionData.uuid; state.phoneId = sessionData.phoneId; state.adid = sessionData.adid; state.build = sessionData.build; // Try to login with stored session await ig.simulate.preLoginFlow(); await ig.account.login(credentials.username, credentials.password); // If successful, we're done return undefined; } catch (error) { // If session is invalid, continue with normal login console.log('Stored session invalid, proceeding with normal login'); } } // Normal login flow await ig.simulate.preLoginFlow(); try { // Attempt login await ig.account.login(credentials.username, credentials.password); } catch (error) { // Check if 2FA is required if (error.name === 'IgLoginBadPasswordError' && ((_b = (_a = error.response) === null || _a === void 0 ? void 0 : _a.body) === null || _b === void 0 ? void 0 : _b.two_factor_required)) { // 2FA is required if (!credentials.twoFactorEnabled) { throw new n8n_workflow_1.NodeOperationError(node, 'Two-factor authentication is required for this account. Please enable 2FA in credentials.'); } if (!credentials.twoFactorCode) { throw new n8n_workflow_1.NodeOperationError(node, 'Two-factor authentication code is required. Please provide it in credentials.'); } // Get 2FA info const twoFactorInfo = error.response.body.two_factor_info; const twoFactorIdentifier = twoFactorInfo.two_factor_identifier; // Verify 2FA code await ig.account.twoFactorLogin({ username: credentials.username, verificationCode: credentials.twoFactorCode, twoFactorIdentifier, }); } else { // Other login error throw error; } } // Post-login flow await ig.simulate.postLoginFlow(); // Store session if enabled if (credentials.sessionStorage) { const state = ig.state; const sessionData = { deviceString: state.deviceString, deviceId: state.deviceId, uuid: state.uuid, phoneId: state.phoneId, adid: state.adid, build: state.build, }; // Return the session data to be stored return JSON.stringify(sessionData); } return undefined; } catch (error) { if (error instanceof n8n_workflow_1.NodeOperationError) { throw error; } throw new n8n_workflow_1.NodeOperationError(node, `Authentication failed: ${error.message}`); } } exports.authenticateInstagram = authenticateInstagram;