n8n/packages/core/src/Credentials.ts

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

72 lines
1.8 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 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 ApplicationError('Node does not have access to credential', {
tags: { nodeType, credentialType: this.type },
extra: { credentialName: this.name },
});
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
}
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 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,
nodesAccess: this.nodesAccess,
};
}
}