n8n/packages/cli/commands/import/credentials.ts
Omar Ajoue 1e551a202f
🚨 Add Workflow testing framework (#1814)
* Added flag to simplify output to execute command and created executeAll

Also created a command that lists workflows so it can be used by
other applications that wish to interact with n8n via CLI.

* Added compare funcionality that helps us identify possible breaking changes

*  Add JSON flag to output execution result in json format

* Add execution time to execution result

* Add --output flag to save JSON formated results

* Fix typos

* Adding usage examples and warning message

* Changing command to always output JSON information

*  Add concurrency to executeAll command

*  Add IDs filter to executeAll command

* ✏️ Fix typos

* Fix lint issues

* Improvements to execute all

* Added colors and beautified execute all command output

* Improving premature termination of execute all command

* Refactored output

* Added detection for warnings instead of errors for a few cases

* Fixed linting

* Improved process finishing

* Added encryption key init, removed messages from non-debug run and created sample github actions file

* Updated test command to use correct encryption key

* Correcting paths

* Changed command name and changed concurrency to be slot based

* Added the retry functionality

* Improved typing and fixed executions filtering

* Updated test description

* Added concurrency

* Added skip list and concurrency

* Fixed termination behavior, removed unnecessary code and added main mode to executions

* Added special edge cases handling

* Added safe debug flag for non tty terminals

* Removed comparison and retries for testing

* Changed the way we run commands to add more debug info

* Test adding concurrency

* Testing with regular testing procedure without comparison

* Adding compare flag

* Fixing short output command

* Upgraded concurrency to 16, fixed short output and covered nodes count

* Fixed short output condition

* Correcting short output information

* Correcting the output for short output

* Added a string to possible warnings list

* Added example usages with more arguments

* Improvements to code made by Ivan

* Removed colorize output setting (always use colors), moved execution timeout to become static and removed node list from executions

* Moving types to a separate file on execute batch command

* Changed interfaces file extension to prevent oclif warnings

* Updated workflow pdf files

*  Change rule when tests run + minor formatting fixes

Co-authored-by: dali <servfrdali@yahoo.fr>
Co-authored-by: Jan Oberhauser <jan.oberhauser@gmail.com>
2021-07-01 09:04:24 +02:00

114 lines
2.9 KiB
TypeScript

import {
Command,
flags,
} from '@oclif/command';
import {
Credentials,
UserSettings,
} from 'n8n-core';
import {
Db,
} from '../../src';
import {
getLogger,
} from '../../src/Logger';
import {
LoggerProxy,
} from 'n8n-workflow';
import * as fs from 'fs';
import * as glob from 'glob-promise';
import * as path from 'path';
export class ImportCredentialsCommand extends Command {
static description = 'Import credentials';
static examples = [
`$ n8n import:credentials --input=file.json`,
`$ n8n import:credentials --separate --input=backups/latest/`,
];
static flags = {
help: flags.help({ char: 'h' }),
input: flags.string({
char: 'i',
description: 'Input file name or directory if --separate is used',
}),
separate: flags.boolean({
description: 'Imports *.json files from directory provided by --input',
}),
};
async run() {
const logger = getLogger();
LoggerProxy.init(logger);
const { flags } = this.parse(ImportCredentialsCommand);
if (!flags.input) {
console.info(`An input file or directory with --input must be provided`);
return;
}
if (flags.separate) {
if (fs.existsSync(flags.input)) {
if (!fs.lstatSync(flags.input).isDirectory()) {
console.info(`The paramenter --input must be a directory`);
return;
}
}
}
try {
await Db.init();
// Make sure the settings exist
await UserSettings.prepareUserSettings();
let i;
const encryptionKey = await UserSettings.getEncryptionKey();
if (encryptionKey === undefined) {
throw new Error('No encryption key got found to encrypt the credentials!');
}
if (flags.separate) {
const files = await glob((flags.input.endsWith(path.sep) ? flags.input : flags.input + path.sep) + '*.json');
for (i = 0; i < files.length; i++) {
const credential = JSON.parse(fs.readFileSync(files[i], { encoding: 'utf8' }));
if (typeof credential.data === 'object') {
// plain data / decrypted input. Should be encrypted first.
Credentials.prototype.setData.call(credential, credential.data, encryptionKey);
}
await Db.collections.Credentials!.save(credential);
}
} else {
const fileContents = JSON.parse(fs.readFileSync(flags.input, { encoding: 'utf8' }));
if (!Array.isArray(fileContents)) {
throw new Error(`File does not seem to contain credentials.`);
}
for (i = 0; i < fileContents.length; i++) {
if (typeof fileContents[i].data === 'object') {
// plain data / decrypted input. Should be encrypted first.
Credentials.prototype.setData.call(fileContents[i], fileContents[i].data, encryptionKey);
}
await Db.collections.Credentials!.save(fileContents[i]);
}
}
console.info(`Successfully imported ${i} ${i === 1 ? 'credential.' : 'credentials.'}`);
process.exit(0);
} catch (error) {
console.error('An error occurred while exporting credentials. See log messages for details.');
logger.error(error.message);
this.exit(1);
}
}
}