2023-10-23 04:39:35 -07:00
|
|
|
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
|
|
|
|
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)) {
|
|
|
|
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.');
|
|
|
|
}
|
|
|
|
|
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) {
|
2021-08-27 08:25:54 -07:00
|
|
|
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) {
|
2022-12-29 03:20:43 -08:00
|
|
|
throw new Error('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,
|
|
|
|
};
|
|
|
|
}
|
|
|
|
}
|