refactor(editor): Migrate Credentials.store to use composition API (no-changelog) (#9767)

This commit is contained in:
Ricardo Espinoza 2024-06-17 04:54:38 -04:00 committed by GitHub
parent 076c35d193
commit 60491d979d
No known key found for this signature in database
GPG key ID: B5690EEEBB952194

View file

@ -7,20 +7,8 @@ import type {
ICredentialsState, ICredentialsState,
ICredentialTypeMap, ICredentialTypeMap,
} from '@/Interface'; } from '@/Interface';
import { import * as credentialsApi from '@/api/credentials';
createNewCredential, import * as credentialsEeApi from '@/api/credentials.ee';
deleteCredential,
getAllCredentials,
getAllCredentialsForWorkflow,
getCredentialData,
getCredentialsNewName,
getCredentialTypes,
oAuth1CredentialAuthorize,
oAuth2CredentialAuthorize,
testCredential,
updateCredential,
} from '@/api/credentials';
import { setCredentialSharedWith } from '@/api/credentials.ee';
import { makeRestApiRequest } from '@/utils/apiUtils'; import { makeRestApiRequest } from '@/utils/apiUtils';
import { getAppNameFromCredType } from '@/utils/nodeTypesUtils'; import { getAppNameFromCredType } from '@/utils/nodeTypesUtils';
import { EnterpriseEditionFeature, STORES } from '@/constants'; import { EnterpriseEditionFeature, STORES } from '@/constants';
@ -38,6 +26,7 @@ import { useSettingsStore } from './settings.store';
import { isEmpty } from '@/utils/typesUtils'; import { isEmpty } from '@/utils/typesUtils';
import type { ProjectSharingData } from '@/types/projects.types'; import type { ProjectSharingData } from '@/types/projects.types';
import { splitName } from '@/utils/projects.utils'; import { splitName } from '@/utils/projects.utils';
import { computed, ref } from 'vue';
const DEFAULT_CREDENTIAL_NAME = 'Unnamed credential'; const DEFAULT_CREDENTIAL_NAME = 'Unnamed credential';
const DEFAULT_CREDENTIAL_POSTFIX = 'account'; const DEFAULT_CREDENTIAL_POSTFIX = 'account';
@ -45,342 +34,421 @@ const TYPES_WITH_DEFAULT_NAME = ['httpBasicAuth', 'oAuth2Api', 'httpDigestAuth',
export type CredentialsStore = ReturnType<typeof useCredentialsStore>; export type CredentialsStore = ReturnType<typeof useCredentialsStore>;
export const useCredentialsStore = defineStore(STORES.CREDENTIALS, { export const useCredentialsStore = defineStore(STORES.CREDENTIALS, () => {
state: (): ICredentialsState => ({ const state = ref<ICredentialsState>({ credentialTypes: {}, credentials: {} });
credentialTypes: {},
credentials: {},
}),
getters: {
credentialTypesById(): Record<ICredentialType['name'], ICredentialType> {
return this.credentialTypes;
},
allCredentialTypes(): ICredentialType[] {
return Object.values(this.credentialTypes).sort((a, b) =>
a.displayName.localeCompare(b.displayName),
);
},
allCredentials(): ICredentialsResponse[] {
return Object.values(this.credentials).sort((a, b) => a.name.localeCompare(b.name));
},
allCredentialsByType(): { [type: string]: ICredentialsResponse[] } {
const credentials = this.allCredentials;
const types = this.allCredentialTypes;
return types.reduce( // ---------------------------------------------------------------------------
(accu: { [type: string]: ICredentialsResponse[] }, type: ICredentialType) => { // #region Computed
accu[type.name] = credentials.filter( // ---------------------------------------------------------------------------
(cred: ICredentialsResponse) => cred.type === type.name,
);
return accu; const credentialTypesById = computed(() => {
}, return state.value.credentialTypes;
{}, });
);
}, const allCredentialTypes = computed(() => {
allUsableCredentialsForNode() { return Object.values(state.value.credentialTypes).sort((a, b) =>
return (node: INodeUi): ICredentialsResponse[] => { a.displayName.localeCompare(b.displayName),
let credentials: ICredentialsResponse[] = []; );
const nodeType = useNodeTypesStore().getNodeType(node.type, node.typeVersion); });
if (nodeType?.credentials) {
nodeType.credentials.forEach((cred) => { const allCredentials = computed(() => {
credentials = credentials.concat(this.allUsableCredentialsByType[cred.name]); return Object.values(state.value.credentials).sort((a, b) => a.name.localeCompare(b.name));
}); });
}
return credentials.sort((a, b) => { const allCredentialsByType = computed(() => {
const aDate = new Date(a.updatedAt); const credentials = allCredentials.value;
const bDate = new Date(b.updatedAt); const types = allCredentialTypes.value;
return aDate.getTime() - bDate.getTime(); return types.reduce(
(accu: { [type: string]: ICredentialsResponse[] }, type: ICredentialType) => {
accu[type.name] = credentials.filter(
(cred: ICredentialsResponse) => cred.type === type.name,
);
return accu;
},
{},
);
});
const allUsableCredentialsByType = computed(() => {
const credentials = allCredentials.value;
const types = allCredentialTypes.value;
return types.reduce(
(accu: { [type: string]: ICredentialsResponse[] }, type: ICredentialType) => {
accu[type.name] = credentials.filter((cred: ICredentialsResponse) => {
return cred.type === type.name;
}); });
};
},
allUsableCredentialsByType(): { [type: string]: ICredentialsResponse[] } {
const credentials = this.allCredentials;
const types = this.allCredentialTypes;
return types.reduce( return accu;
(accu: { [type: string]: ICredentialsResponse[] }, type: ICredentialType) => { },
accu[type.name] = credentials.filter((cred: ICredentialsResponse) => { {},
return cred.type === type.name; );
}); });
return accu; const allUsableCredentialsForNode = computed(() => {
}, return (node: INodeUi): ICredentialsResponse[] => {
{}, let credentials: ICredentialsResponse[] = [];
); const nodeType = useNodeTypesStore().getNodeType(node.type, node.typeVersion);
}, if (nodeType?.credentials) {
getCredentialTypeByName() { nodeType.credentials.forEach((cred) => {
return (type: string): ICredentialType | undefined => this.credentialTypes[type]; credentials = credentials.concat(allUsableCredentialsByType.value[cred.name]);
}, });
getCredentialById() { }
return (id: string): ICredentialsResponse => this.credentials[id]; return credentials.sort((a, b) => {
}, const aDate = new Date(a.updatedAt);
getCredentialByIdAndType() { const bDate = new Date(b.updatedAt);
return (id: string, type: string): ICredentialsResponse | undefined => { return aDate.getTime() - bDate.getTime();
const credential = this.credentials[id]; });
return !credential || credential.type !== type ? undefined : credential; };
}; });
},
getCredentialsByType() {
return (credentialType: string): ICredentialsResponse[] => {
return this.allCredentialsByType[credentialType] || [];
};
},
getUsableCredentialByType() {
return (credentialType: string): ICredentialsResponse[] => {
return this.allUsableCredentialsByType[credentialType] || [];
};
},
getNodesWithAccess() {
return (credentialTypeName: string) => {
const nodeTypesStore = useNodeTypesStore();
const allNodeTypes: INodeTypeDescription[] = nodeTypesStore.allNodeTypes;
return allNodeTypes.filter((nodeType: INodeTypeDescription) => { const getCredentialTypeByName = computed(() => {
if (!nodeType.credentials) { return (type: string): ICredentialType | undefined => state.value.credentialTypes[type];
return false; });
}
for (const credentialTypeDescription of nodeType.credentials) { const getCredentialById = computed(() => {
if (credentialTypeDescription.name === credentialTypeName) { return (id: string): ICredentialsResponse => state.value.credentials[id];
return true; });
}
}
const getCredentialByIdAndType = computed(() => {
return (id: string, type: string): ICredentialsResponse | undefined => {
const credential = state.value.credentials[id];
return !credential || credential.type !== type ? undefined : credential;
};
});
const getCredentialsByType = computed(() => {
return (credentialType: string): ICredentialsResponse[] => {
return allCredentialsByType.value[credentialType] || [];
};
});
const getUsableCredentialByType = computed(() => {
return (credentialType: string): ICredentialsResponse[] => {
return allUsableCredentialsByType.value[credentialType] || [];
};
});
const getNodesWithAccess = computed(() => {
return (credentialTypeName: string) => {
const nodeTypesStore = useNodeTypesStore();
const allNodeTypes: INodeTypeDescription[] = nodeTypesStore.allNodeTypes;
return allNodeTypes.filter((nodeType: INodeTypeDescription) => {
if (!nodeType.credentials) {
return false; return false;
});
};
},
getScopesByCredentialType() {
return (credentialTypeName: string) => {
const credentialType = this.getCredentialTypeByName(credentialTypeName);
if (!credentialType) {
return [];
} }
const scopeProperty = credentialType.properties.find((p) => p.name === 'scope'); for (const credentialTypeDescription of nodeType.credentials) {
if (credentialTypeDescription.name === credentialTypeName) {
if ( return true;
!scopeProperty || }
!scopeProperty.default ||
typeof scopeProperty.default !== 'string' ||
scopeProperty.default === ''
) {
return [];
} }
let { default: scopeDefault } = scopeProperty; return false;
});
};
});
// disregard expressions for display const getScopesByCredentialType = computed(() => {
scopeDefault = scopeDefault.replace(/^=/, '').replace(/\{\{.*\}\}/, ''); return (credentialTypeName: string) => {
const credentialType = getCredentialTypeByName.value(credentialTypeName);
if (!credentialType) {
return [];
}
if (/ /.test(scopeDefault)) return scopeDefault.split(' '); const scopeProperty = credentialType.properties.find((p) => p.name === 'scope');
if (/,/.test(scopeDefault)) return scopeDefault.split(','); if (
!scopeProperty ||
!scopeProperty.default ||
typeof scopeProperty.default !== 'string' ||
scopeProperty.default === ''
) {
return [];
}
return [scopeDefault]; let { default: scopeDefault } = scopeProperty;
};
},
getCredentialOwnerName() {
return (credential: ICredentialsResponse | IUsedCredential | undefined): string => {
const { firstName, lastName, email } = splitName(credential?.homeProject?.name ?? '');
return credential?.homeProject?.name // disregard expressions for display
? `${firstName} ${lastName} (${email})` scopeDefault = scopeDefault.replace(/^=/, '').replace(/\{\{.*\}\}/, '');
: i18n.baseText('credentialEdit.credentialSharing.info.sharee.fallback');
};
},
getCredentialOwnerNameById() {
return (credentialId: string): string => {
const credential = this.getCredentialById(credentialId);
return this.getCredentialOwnerName(credential); if (/ /.test(scopeDefault)) return scopeDefault.split(' ');
};
},
httpOnlyCredentialTypes(): ICredentialType[] {
return this.allCredentialTypes.filter((credentialType) => credentialType.httpRequestNode);
},
},
actions: {
setCredentialTypes(credentialTypes: ICredentialType[]): void {
this.credentialTypes = credentialTypes.reduce(
(accu: ICredentialTypeMap, cred: ICredentialType) => {
accu[cred.name] = cred;
return accu; if (/,/.test(scopeDefault)) return scopeDefault.split(',');
},
{}, return [scopeDefault];
); };
}, });
setCredentials(credentials: ICredentialsResponse[]): void {
this.credentials = credentials.reduce((accu: ICredentialMap, cred: ICredentialsResponse) => { const getCredentialOwnerName = computed(() => {
return (credential: ICredentialsResponse | IUsedCredential | undefined): string => {
const { firstName, lastName, email } = splitName(credential?.homeProject?.name ?? '');
return credential?.homeProject?.name
? `${firstName} ${lastName} (${email})`
: i18n.baseText('credentialEdit.credentialSharing.info.sharee.fallback');
};
});
const getCredentialOwnerNameById = computed(() => {
return (credentialId: string): string => {
const credential = getCredentialById.value(credentialId);
return getCredentialOwnerName.value(credential);
};
});
const httpOnlyCredentialTypes = computed(() => {
return allCredentialTypes.value.filter((credentialType) => credentialType.httpRequestNode);
});
// #endregion
// ---------------------------------------------------------------------------
// #region Methods
// ---------------------------------------------------------------------------
const setCredentialTypes = (credentialTypes: ICredentialType[]) => {
state.value.credentialTypes = credentialTypes.reduce(
(accu: ICredentialTypeMap, cred: ICredentialType) => {
accu[cred.name] = cred;
return accu;
},
{},
);
};
const addCredentials = (credentials: ICredentialsResponse[]) => {
credentials.forEach((cred: ICredentialsResponse) => {
if (cred.id) {
state.value.credentials[cred.id] = { ...state.value.credentials[cred.id], ...cred };
}
});
};
const setCredentials = (credentials: ICredentialsResponse[]) => {
state.value.credentials = credentials.reduce(
(accu: ICredentialMap, cred: ICredentialsResponse) => {
if (cred.id) { if (cred.id) {
accu[cred.id] = cred; accu[cred.id] = cred;
} }
return accu; return accu;
}, {}); },
}, {},
addCredentials(credentials: ICredentialsResponse[]): void { );
credentials.forEach((cred: ICredentialsResponse) => { };
if (cred.id) {
this.credentials[cred.id] = { ...this.credentials[cred.id], ...cred };
}
});
},
upsertCredential(credential: ICredentialsResponse): void {
if (credential.id) {
this.credentials = {
...this.credentials,
[credential.id]: {
...this.credentials[credential.id],
...credential,
},
};
}
},
async fetchCredentialTypes(forceFetch: boolean): Promise<void> {
if (this.allCredentialTypes.length > 0 && !forceFetch) {
return;
}
const rootStore = useRootStore();
const credentialTypes = await getCredentialTypes(rootStore.getBaseUrl);
this.setCredentialTypes(credentialTypes);
},
async fetchAllCredentials(
projectId?: string,
includeScopes = true,
): Promise<ICredentialsResponse[]> {
const rootStore = useRootStore();
const filter = { const upsertCredential = (credential: ICredentialsResponse) => {
projectId, if (credential.id) {
state.value.credentials = {
...state.value.credentials,
[credential.id]: {
...state.value.credentials[credential.id],
...credential,
},
}; };
}
};
const credentials = await getAllCredentials( const fetchCredentialTypes = async (forceFetch: boolean) => {
rootStore.getRestApiContext, if (allCredentialTypes.value.length > 0 && !forceFetch) {
isEmpty(filter) ? undefined : filter, return;
includeScopes, }
); const rootStore = useRootStore();
this.setCredentials(credentials); const credentialTypes = await credentialsApi.getCredentialTypes(rootStore.getBaseUrl);
return credentials; setCredentialTypes(credentialTypes);
}, };
async fetchAllCredentialsForWorkflow(
options: { workflowId: string } | { projectId: string },
): Promise<ICredentialsResponse[]> {
const rootStore = useRootStore();
const credentials = await getAllCredentialsForWorkflow(rootStore.getRestApiContext, options); const fetchAllCredentials = async (
this.setCredentials(credentials); projectId?: string,
return credentials; includeScopes = true,
}, ): Promise<ICredentialsResponse[]> => {
async getCredentialData({ const rootStore = useRootStore();
id,
}: {
id: string;
}): Promise<ICredentialsResponse | ICredentialsDecryptedResponse | undefined> {
const rootStore = useRootStore();
return await getCredentialData(rootStore.getRestApiContext, id);
},
async createNewCredential(
data: ICredentialsDecrypted,
projectId?: string,
): Promise<ICredentialsResponse> {
const rootStore = useRootStore();
const settingsStore = useSettingsStore();
const credential = await createNewCredential(rootStore.getRestApiContext, data, projectId);
if (settingsStore.isEnterpriseFeatureEnabled(EnterpriseEditionFeature.Sharing)) { const filter = {
this.upsertCredential(credential); projectId,
if (data.sharedWithProjects) { };
await this.setCredentialSharedWith({
credentialId: credential.id,
sharedWithProjects: data.sharedWithProjects,
});
}
} else {
this.upsertCredential(credential);
}
return credential;
},
async updateCredential(params: {
data: ICredentialsDecrypted;
id: string;
}): Promise<ICredentialsResponse> {
const { id, data } = params;
const rootStore = useRootStore();
const credential = await updateCredential(rootStore.getRestApiContext, id, data);
this.upsertCredential(credential); const credentials = await credentialsApi.getAllCredentials(
rootStore.getRestApiContext,
isEmpty(filter) ? undefined : filter,
includeScopes,
);
setCredentials(credentials);
return credentials;
};
return credential; const fetchAllCredentialsForWorkflow = async (
}, options: { workflowId: string } | { projectId: string },
async deleteCredential({ id }: { id: string }) { ): Promise<ICredentialsResponse[]> => {
const rootStore = useRootStore(); const rootStore = useRootStore();
const deleted = await deleteCredential(rootStore.getRestApiContext, id);
if (deleted) { const credentials = await credentialsApi.getAllCredentialsForWorkflow(
const { [id]: deletedCredential, ...rest } = this.credentials; rootStore.getRestApiContext,
this.credentials = rest; options,
} );
}, setCredentials(credentials);
async oAuth2Authorize(data: ICredentialsResponse): Promise<string> { return credentials;
const rootStore = useRootStore(); };
return await oAuth2CredentialAuthorize(rootStore.getRestApiContext, data);
}, const getCredentialData = async ({
async oAuth1Authorize(data: ICredentialsResponse): Promise<string> { id,
const rootStore = useRootStore(); }: {
return await oAuth1CredentialAuthorize(rootStore.getRestApiContext, data); id: string;
}, }): Promise<ICredentialsResponse | ICredentialsDecryptedResponse | undefined> => {
async testCredential(data: ICredentialsDecrypted): Promise<INodeCredentialTestResult> { const rootStore = useRootStore();
const rootStore = useRootStore(); return await credentialsApi.getCredentialData(rootStore.getRestApiContext, id);
return await testCredential(rootStore.getRestApiContext, { credentials: data }); };
},
async getNewCredentialName(params: { credentialTypeName: string }): Promise<string> { const createNewCredential = async (
try { data: ICredentialsDecrypted,
const { credentialTypeName } = params; projectId?: string,
let newName = DEFAULT_CREDENTIAL_NAME; ): Promise<ICredentialsResponse> => {
if (!TYPES_WITH_DEFAULT_NAME.includes(credentialTypeName)) { const rootStore = useRootStore();
const cred = this.getCredentialTypeByName(credentialTypeName); const settingsStore = useSettingsStore();
newName = cred ? getAppNameFromCredType(cred.displayName) : ''; const credential = await credentialsApi.createNewCredential(
newName = rootStore.getRestApiContext,
newName.length > 0 data,
? `${newName} ${DEFAULT_CREDENTIAL_POSTFIX}` projectId,
: DEFAULT_CREDENTIAL_NAME; );
}
const rootStore = useRootStore(); if (settingsStore.isEnterpriseFeatureEnabled(EnterpriseEditionFeature.Sharing)) {
const res = await getCredentialsNewName(rootStore.getRestApiContext, newName); upsertCredential(credential);
return res.name; if (data.sharedWithProjects) {
} catch (e) { await setCredentialSharedWith({
return DEFAULT_CREDENTIAL_NAME; credentialId: credential.id,
} sharedWithProjects: data.sharedWithProjects,
},
async setCredentialSharedWith(payload: {
sharedWithProjects: ProjectSharingData[];
credentialId: string;
}): Promise<ICredentialsResponse> {
if (useSettingsStore().isEnterpriseFeatureEnabled(EnterpriseEditionFeature.Sharing)) {
await setCredentialSharedWith(useRootStore().getRestApiContext, payload.credentialId, {
shareWithIds: payload.sharedWithProjects.map((project) => project.id),
}); });
this.credentials[payload.credentialId] = {
...this.credentials[payload.credentialId],
sharedWithProjects: payload.sharedWithProjects,
};
} }
return this.credentials[payload.credentialId]; } else {
}, upsertCredential(credential);
}
return credential;
};
async getCredentialTranslation(credentialType: string): Promise<object> { const updateCredential = async (params: {
data: ICredentialsDecrypted;
id: string;
}): Promise<ICredentialsResponse> => {
const { id, data } = params;
const rootStore = useRootStore();
const credential = await credentialsApi.updateCredential(rootStore.getRestApiContext, id, data);
upsertCredential(credential);
return credential;
};
const deleteCredential = async ({ id }: { id: string }) => {
const rootStore = useRootStore();
const deleted = await credentialsApi.deleteCredential(rootStore.getRestApiContext, id);
if (deleted) {
const { [id]: deletedCredential, ...rest } = state.value.credentials;
state.value.credentials = rest;
}
};
const oAuth2Authorize = async (data: ICredentialsResponse): Promise<string> => {
const rootStore = useRootStore();
return await credentialsApi.oAuth2CredentialAuthorize(rootStore.getRestApiContext, data);
};
const oAuth1Authorize = async (data: ICredentialsResponse): Promise<string> => {
const rootStore = useRootStore();
return await credentialsApi.oAuth1CredentialAuthorize(rootStore.getRestApiContext, data);
};
const testCredential = async (
data: ICredentialsDecrypted,
): Promise<INodeCredentialTestResult> => {
const rootStore = useRootStore();
return await credentialsApi.testCredential(rootStore.getRestApiContext, { credentials: data });
};
const getNewCredentialName = async (params: { credentialTypeName: string }): Promise<string> => {
try {
const { credentialTypeName } = params;
let newName = DEFAULT_CREDENTIAL_NAME;
if (!TYPES_WITH_DEFAULT_NAME.includes(credentialTypeName)) {
const cred = getCredentialTypeByName.value(credentialTypeName);
newName = cred ? getAppNameFromCredType(cred.displayName) : '';
newName =
newName.length > 0 ? `${newName} ${DEFAULT_CREDENTIAL_POSTFIX}` : DEFAULT_CREDENTIAL_NAME;
}
const rootStore = useRootStore(); const rootStore = useRootStore();
return await makeRestApiRequest( const res = await credentialsApi.getCredentialsNewName(rootStore.getRestApiContext, newName);
rootStore.getRestApiContext, return res.name;
'GET', } catch (e) {
'/credential-translation', return DEFAULT_CREDENTIAL_NAME;
}
};
const setCredentialSharedWith = async (payload: {
sharedWithProjects: ProjectSharingData[];
credentialId: string;
}): Promise<ICredentialsResponse> => {
if (useSettingsStore().isEnterpriseFeatureEnabled(EnterpriseEditionFeature.Sharing)) {
await credentialsEeApi.setCredentialSharedWith(
useRootStore().getRestApiContext,
payload.credentialId,
{ {
credentialType, shareWithIds: payload.sharedWithProjects.map((project) => project.id),
}, },
); );
},
}, state.value.credentials[payload.credentialId] = {
...state.value.credentials[payload.credentialId],
sharedWithProjects: payload.sharedWithProjects,
};
}
return state.value.credentials[payload.credentialId];
};
const getCredentialTranslation = async (credentialType: string): Promise<object> => {
const rootStore = useRootStore();
return await makeRestApiRequest(rootStore.getRestApiContext, 'GET', '/credential-translation', {
credentialType,
});
};
// #endregion
return {
getCredentialOwnerName,
getCredentialsByType,
getCredentialById,
getCredentialTypeByName,
getCredentialByIdAndType,
getNodesWithAccess,
getUsableCredentialByType,
credentialTypesById,
httpOnlyCredentialTypes,
getScopesByCredentialType,
getCredentialOwnerNameById,
allUsableCredentialsForNode,
allCredentials,
allCredentialTypes,
allUsableCredentialsByType,
setCredentialTypes,
addCredentials,
setCredentials,
deleteCredential,
upsertCredential,
fetchCredentialTypes,
fetchAllCredentials,
fetchAllCredentialsForWorkflow,
createNewCredential,
updateCredential,
getCredentialData,
oAuth1Authorize,
oAuth2Authorize,
getNewCredentialName,
testCredential,
getCredentialTranslation,
setCredentialSharedWith,
};
}); });
/** /**
@ -404,12 +472,12 @@ export const listenForCredentialChanges = (opts: {
switch (name) { switch (name) {
case 'createNewCredential': case 'createNewCredential':
const createdCredential = returnValue as ICredentialsResponse; const createdCredential = returnValue as unknown as ICredentialsResponse;
onCredentialCreated?.(createdCredential); onCredentialCreated?.(createdCredential);
break; break;
case 'updateCredential': case 'updateCredential':
const updatedCredential = returnValue as ICredentialsResponse; const updatedCredential = returnValue as unknown as ICredentialsResponse;
onCredentialUpdated?.(updatedCredential); onCredentialUpdated?.(updatedCredential);
break; break;