n8n/packages/core/src/Credentials.ts

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

71 lines
1.7 KiB
TypeScript
Raw Normal View History

import { Container } from 'typedi';
import type { ICredentialDataDecryptedObject, ICredentialsEncrypted } from 'n8n-workflow';
import { ICredentials, jsonParse } from 'n8n-workflow';
import { Cipher } from './Cipher';
2019-06-23 03:35:23 -07:00
export class Credentials extends ICredentials {
private readonly cipher = Container.get(Cipher);
2019-06-23 03:35:23 -07:00
/**
* Returns if the given nodeType has access to data
*/
hasNodeAccess(nodeType: string): boolean {
for (const accessData of this.nodesAccess) {
if (accessData.nodeType === nodeType) {
return true;
}
}
return false;
}
/**
* Sets new credential object
*/
setData(data: ICredentialDataDecryptedObject): void {
this.data = this.cipher.encrypt(data);
2019-06-23 03:35:23 -07:00
}
/**
* Returns the decrypted credential object
*/
getData(nodeType?: string): ICredentialDataDecryptedObject {
2019-06-23 03:35:23 -07:00
if (nodeType && !this.hasNodeAccess(nodeType)) {
throw new Error(
`The node of type "${nodeType}" does not have access to credentials "${this.name}" of type "${this.type}".`,
);
}
if (this.data === undefined) {
throw new Error('No data is set so nothing can be returned.');
}
const decryptedData = this.cipher.decrypt(this.data);
2019-06-23 03:35:23 -07:00
try {
return jsonParse(decryptedData);
2019-06-23 03:35:23 -07:00
} catch (e) {
throw new Error(
'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 Error('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,
nodesAccess: this.nodesAccess,
};
}
}