n8n/packages/core/src/Credentials.ts

Ignoring revisions in .git-blame-ignore-revs. Click here to bypass and see the normal blame view.

53 lines
1.3 KiB
TypeScript
Raw Normal View History

import { Container } from 'typedi';
import type { ICredentialDataDecryptedObject, ICredentialsEncrypted } from 'n8n-workflow';
import { ApplicationError, ICredentials, jsonParse } from 'n8n-workflow';
import { Cipher } from './Cipher';
2019-06-23 03:35:23 -07:00
export class Credentials<
T extends object = ICredentialDataDecryptedObject,
> extends ICredentials<T> {
private readonly cipher = Container.get(Cipher);
2019-06-23 03:35:23 -07:00
/**
* Sets new credential object
*/
setData(data: T): void {
this.data = this.cipher.encrypt(data);
2019-06-23 03:35:23 -07:00
}
/**
* Returns the decrypted credential object
*/
getData(): T {
2019-06-23 03:35:23 -07:00
if (this.data === undefined) {
throw new ApplicationError('No data is set so nothing can be returned.');
2019-06-23 03:35:23 -07:00
}
try {
const decryptedData = this.cipher.decrypt(this.data);
return jsonParse(decryptedData);
2019-06-23 03:35:23 -07:00
} catch (e) {
throw new ApplicationError(
'Credentials could not be decrypted. The likely reason is that a different "encryptionKey" was used to encrypt the data.',
);
2019-06-23 03:35:23 -07:00
}
}
/**
* Returns the encrypted credentials to be saved
*/
getDataToSave(): ICredentialsEncrypted {
if (this.data === undefined) {
throw new ApplicationError('No credentials were set to save.');
2019-06-23 03:35:23 -07:00
}
return {
id: this.id,
2019-06-23 03:35:23 -07:00
name: this.name,
type: this.type,
data: this.data,
};
}
}