2023-10-23 04:39:35 -07:00
|
|
|
import { Container } from 'typedi';
|
|
|
|
import type { ICredentialDataDecryptedObject, ICredentialsEncrypted } from 'n8n-workflow';
|
2023-11-30 00:06:19 -08:00
|
|
|
import { ApplicationError, ICredentials, jsonParse } from 'n8n-workflow';
|
2023-10-23 04:39:35 -07:00
|
|
|
import { Cipher } from './Cipher';
|
2019-06-23 03:35:23 -07:00
|
|
|
|
2020-01-25 23:48:38 -08:00
|
|
|
export class Credentials extends ICredentials {
|
2023-10-23 04:39:35 -07:00
|
|
|
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
|
|
|
|
*/
|
2023-10-23 04:39:35 -07:00
|
|
|
setData(data: ICredentialDataDecryptedObject): void {
|
|
|
|
this.data = this.cipher.encrypt(data);
|
2019-06-23 03:35:23 -07:00
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Returns the decrypted credential object
|
|
|
|
*/
|
2023-10-23 04:39:35 -07:00
|
|
|
getData(nodeType?: string): ICredentialDataDecryptedObject {
|
2019-06-23 03:35:23 -07:00
|
|
|
if (nodeType && !this.hasNodeAccess(nodeType)) {
|
2023-11-30 00:06:19 -08:00
|
|
|
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) {
|
2023-11-30 00:06:19 -08:00
|
|
|
throw new ApplicationError('No data is set so nothing can be returned.');
|
2019-06-23 03:35:23 -07:00
|
|
|
}
|
|
|
|
|
2023-10-23 04:39:35 -07:00
|
|
|
const decryptedData = this.cipher.decrypt(this.data);
|
2019-06-23 03:35:23 -07:00
|
|
|
|
|
|
|
try {
|
2023-10-23 04:39:35 -07:00
|
|
|
return jsonParse(decryptedData);
|
2019-06-23 03:35:23 -07:00
|
|
|
} catch (e) {
|
2023-11-30 00:06:19 -08:00
|
|
|
throw new ApplicationError(
|
2021-08-27 08:25:54 -07:00
|
|
|
'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) {
|
2023-11-30 00:06:19 -08:00
|
|
|
throw new ApplicationError('No credentials were set to save.');
|
2019-06-23 03:35:23 -07:00
|
|
|
}
|
|
|
|
|
|
|
|
return {
|
2021-10-13 15:21:00 -07:00
|
|
|
id: this.id,
|
2019-06-23 03:35:23 -07:00
|
|
|
name: this.name,
|
|
|
|
type: this.type,
|
|
|
|
data: this.data,
|
|
|
|
nodesAccess: this.nodesAccess,
|
|
|
|
};
|
|
|
|
}
|
|
|
|
}
|