refactor: Remove reintroduced non-null assertions in Db calls (#3162)

* 🔥 Remove reintroduced non-null assertions

* 🔥 Remove duplicate cred references

* 🔥 Remove unneeded `@ts-ignore`

* 🔥 Remove another `@ts-ignore`

* 🔥 Remove outdated suite version

* 🔥 Remove leftover non-null assertion

Co-authored-by: Ben Hesseldieck <1849459+BHesseldieck@users.noreply.github.com>

* 🔥 Remove more leftovers

* 🔥 Remove unneeded optional chaining operators

Co-authored-by: Ben Hesseldieck <1849459+BHesseldieck@users.noreply.github.com>
This commit is contained in:
Iván Ovejero 2022-04-28 18:39:57 +02:00 committed by GitHub
parent 2b008815ca
commit 5e2589e626
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
18 changed files with 132 additions and 299 deletions

View file

@ -28,7 +28,7 @@ export class DbRevertMigrationCommand extends Command {
let connection: Connection | undefined; let connection: Connection | undefined;
try { try {
await Db.init(); await Db.init();
connection = Db.collections.Credentials?.manager.connection; connection = Db.collections.Credentials.manager.connection;
if (!connection) { if (!connection) {
throw new Error(`No database connection available.`); throw new Error(`No database connection available.`);

View file

@ -82,7 +82,7 @@ export class ImportWorkflowsCommand extends Command {
// Make sure the settings exist // Make sure the settings exist
await UserSettings.prepareUserSettings(); await UserSettings.prepareUserSettings();
const credentials = (await Db.collections.Credentials?.find()) ?? []; const credentials = (await Db.collections.Credentials.find()) ?? [];
let totalImported = 0; let totalImported = 0;

View file

@ -70,9 +70,7 @@ export class ActiveExecutions {
const execution = ResponseHelper.flattenExecutionData(fullExecutionData); const execution = ResponseHelper.flattenExecutionData(fullExecutionData);
const executionResult = await Db.collections.Execution!.save( const executionResult = await Db.collections.Execution.save(execution as IExecutionFlattedDb);
execution as IExecutionFlattedDb,
);
executionId = executionId =
typeof executionResult.id === 'object' typeof executionResult.id === 'object'
? // @ts-ignore ? // @ts-ignore
@ -87,8 +85,7 @@ export class ActiveExecutions {
waitTill: null, waitTill: null,
}; };
// @ts-ignore await Db.collections.Execution.update(executionId, execution);
await Db.collections.Execution!.update(executionId, execution);
} }
// @ts-ignore // @ts-ignore

View file

@ -83,7 +83,7 @@ export class ActiveWorkflowRunner {
// This is not officially supported but there is no reason // This is not officially supported but there is no reason
// it should not work. // it should not work.
// Clear up active workflow table // Clear up active workflow table
await Db.collections.Webhook?.clear(); await Db.collections.Webhook.clear();
} }
this.activeWorkflows = new ActiveWorkflows(); this.activeWorkflows = new ActiveWorkflows();
@ -189,7 +189,7 @@ export class ActiveWorkflowRunner {
path = path.slice(0, -1); path = path.slice(0, -1);
} }
let webhook = (await Db.collections.Webhook?.findOne({ let webhook = (await Db.collections.Webhook.findOne({
webhookPath: path, webhookPath: path,
method: httpMethod, method: httpMethod,
})) as IWebhookDb; })) as IWebhookDb;
@ -200,7 +200,7 @@ export class ActiveWorkflowRunner {
// check if a dynamic webhook path exists // check if a dynamic webhook path exists
const pathElements = path.split('/'); const pathElements = path.split('/');
webhookId = pathElements.shift(); webhookId = pathElements.shift();
const dynamicWebhooks = await Db.collections.Webhook?.find({ const dynamicWebhooks = await Db.collections.Webhook.find({
webhookId, webhookId,
method: httpMethod, method: httpMethod,
pathLength: pathElements.length, pathLength: pathElements.length,
@ -332,7 +332,7 @@ export class ActiveWorkflowRunner {
* @memberof ActiveWorkflowRunner * @memberof ActiveWorkflowRunner
*/ */
async getWebhookMethods(path: string): Promise<string[]> { async getWebhookMethods(path: string): Promise<string[]> {
const webhooks = await Db.collections.Webhook?.find({ webhookPath: path }); const webhooks = await Db.collections.Webhook.find({ webhookPath: path });
// Gather all request methods in string array // Gather all request methods in string array
const webhookMethods: string[] = webhooks.map((webhook) => webhook.method); const webhookMethods: string[] = webhooks.map((webhook) => webhook.method);
@ -443,7 +443,7 @@ export class ActiveWorkflowRunner {
try { try {
// eslint-disable-next-line no-await-in-loop // eslint-disable-next-line no-await-in-loop
await Db.collections.Webhook?.insert(webhook); await Db.collections.Webhook.insert(webhook);
const webhookExists = await workflow.runWebhookMethod( const webhookExists = await workflow.runWebhookMethod(
'checkExists', 'checkExists',
webhookData, webhookData,
@ -556,7 +556,7 @@ export class ActiveWorkflowRunner {
workflowId: workflowData.id, workflowId: workflowData.id,
} as IWebhookDb; } as IWebhookDb;
await Db.collections.Webhook?.delete(webhook); await Db.collections.Webhook.delete(webhook);
} }
/** /**

View file

@ -756,7 +756,7 @@ class App {
const { tags: tagIds } = req.body; const { tags: tagIds } = req.body;
if (tagIds?.length && !config.getEnv('workflowTagsDisabled')) { if (tagIds?.length && !config.getEnv('workflowTagsDisabled')) {
newWorkflow.tags = await Db.collections.Tag!.findByIds(tagIds, { newWorkflow.tags = await Db.collections.Tag.findByIds(tagIds, {
select: ['id', 'name'], select: ['id', 'name'],
}); });
} }
@ -768,7 +768,7 @@ class App {
await getConnection().transaction(async (transactionManager) => { await getConnection().transaction(async (transactionManager) => {
savedWorkflow = await transactionManager.save<WorkflowEntity>(newWorkflow); savedWorkflow = await transactionManager.save<WorkflowEntity>(newWorkflow);
const role = await Db.collections.Role!.findOneOrFail({ const role = await Db.collections.Role.findOneOrFail({
name: 'owner', name: 'owner',
scope: 'workflow', scope: 'workflow',
}); });
@ -878,13 +878,13 @@ class App {
} }
if (req.user.globalRole.name === 'owner') { if (req.user.globalRole.name === 'owner') {
workflows = await Db.collections.Workflow!.find( workflows = await Db.collections.Workflow.find(
Object.assign(query, { Object.assign(query, {
where: filter, where: filter,
}), }),
); );
} else { } else {
const shared = await Db.collections.SharedWorkflow!.find({ const shared = await Db.collections.SharedWorkflow.find({
relations: ['workflow'], relations: ['workflow'],
where: whereClause({ where: whereClause({
user: req.user, user: req.user,
@ -894,7 +894,7 @@ class App {
if (!shared.length) return []; if (!shared.length) return [];
workflows = await Db.collections.Workflow!.find( workflows = await Db.collections.Workflow.find(
Object.assign(query, { Object.assign(query, {
where: { where: {
id: In(shared.map(({ workflow }) => workflow.id)), id: In(shared.map(({ workflow }) => workflow.id)),
@ -937,7 +937,7 @@ class App {
relations = relations.filter((relation) => relation !== 'workflow.tags'); relations = relations.filter((relation) => relation !== 'workflow.tags');
} }
const shared = await Db.collections.SharedWorkflow!.findOne({ const shared = await Db.collections.SharedWorkflow.findOne({
relations, relations,
where: whereClause({ where: whereClause({
user: req.user, user: req.user,
@ -979,7 +979,7 @@ class App {
const { tags, ...rest } = req.body; const { tags, ...rest } = req.body;
Object.assign(updateData, rest); Object.assign(updateData, rest);
const shared = await Db.collections.SharedWorkflow!.findOne({ const shared = await Db.collections.SharedWorkflow.findOne({
relations: ['workflow'], relations: ['workflow'],
where: whereClause({ where: whereClause({
user: req.user, user: req.user,
@ -1041,7 +1041,7 @@ class App {
await validateEntity(updateData); await validateEntity(updateData);
} }
await Db.collections.Workflow!.update(workflowId, updateData); await Db.collections.Workflow.update(workflowId, updateData);
if (tags && !config.getEnv('workflowTagsDisabled')) { if (tags && !config.getEnv('workflowTagsDisabled')) {
const tablePrefix = config.getEnv('database.tablePrefix'); const tablePrefix = config.getEnv('database.tablePrefix');
@ -1062,7 +1062,7 @@ class App {
// We sadly get nothing back from "update". Neither if it updated a record // We sadly get nothing back from "update". Neither if it updated a record
// nor the new value. So query now the hopefully updated entry. // nor the new value. So query now the hopefully updated entry.
const updatedWorkflow = await Db.collections.Workflow!.findOne(workflowId, options); const updatedWorkflow = await Db.collections.Workflow.findOne(workflowId, options);
if (updatedWorkflow === undefined) { if (updatedWorkflow === undefined) {
throw new ResponseHelper.ResponseError( throw new ResponseHelper.ResponseError(
@ -1079,7 +1079,6 @@ class App {
} }
await this.externalHooks.run('workflow.afterUpdate', [updatedWorkflow]); await this.externalHooks.run('workflow.afterUpdate', [updatedWorkflow]);
// @ts-ignore
void InternalHooksManager.getInstance().onWorkflowSaved(req.user.id, updatedWorkflow); void InternalHooksManager.getInstance().onWorkflowSaved(req.user.id, updatedWorkflow);
if (updatedWorkflow.active) { if (updatedWorkflow.active) {
@ -1093,8 +1092,7 @@ class App {
} catch (error) { } catch (error) {
// If workflow could not be activated set it again to inactive // If workflow could not be activated set it again to inactive
updateData.active = false; updateData.active = false;
// @ts-ignore await Db.collections.Workflow.update(workflowId, updateData);
await Db.collections.Workflow!.update(workflowId, updateData);
// Also set it in the returned data // Also set it in the returned data
updatedWorkflow.active = false; updatedWorkflow.active = false;
@ -1121,7 +1119,7 @@ class App {
await this.externalHooks.run('workflow.delete', [workflowId]); await this.externalHooks.run('workflow.delete', [workflowId]);
const shared = await Db.collections.SharedWorkflow!.findOne({ const shared = await Db.collections.SharedWorkflow.findOne({
relations: ['workflow'], relations: ['workflow'],
where: whereClause({ where: whereClause({
user: req.user, user: req.user,
@ -1147,7 +1145,7 @@ class App {
await this.activeWorkflowRunner.remove(workflowId); await this.activeWorkflowRunner.remove(workflowId);
} }
await Db.collections.Workflow!.delete(workflowId); await Db.collections.Workflow.delete(workflowId);
void InternalHooksManager.getInstance().onWorkflowDeleted(req.user.id, workflowId); void InternalHooksManager.getInstance().onWorkflowDeleted(req.user.id, workflowId);
await this.externalHooks.run('workflow.afterDelete', [workflowId]); await this.externalHooks.run('workflow.afterDelete', [workflowId]);
@ -1246,7 +1244,7 @@ class App {
return TagHelpers.getTagsWithCountDb(tablePrefix); return TagHelpers.getTagsWithCountDb(tablePrefix);
} }
return Db.collections.Tag!.find({ select: ['id', 'name'] }); return Db.collections.Tag.find({ select: ['id', 'name'] });
}, },
), ),
); );
@ -1265,7 +1263,7 @@ class App {
await this.externalHooks.run('tag.beforeCreate', [newTag]); await this.externalHooks.run('tag.beforeCreate', [newTag]);
await validateEntity(newTag); await validateEntity(newTag);
const tag = await Db.collections.Tag!.save(newTag); const tag = await Db.collections.Tag.save(newTag);
await this.externalHooks.run('tag.afterCreate', [tag]); await this.externalHooks.run('tag.afterCreate', [tag]);
@ -1294,7 +1292,7 @@ class App {
await this.externalHooks.run('tag.beforeUpdate', [newTag]); await this.externalHooks.run('tag.beforeUpdate', [newTag]);
await validateEntity(newTag); await validateEntity(newTag);
const tag = await Db.collections.Tag!.save(newTag); const tag = await Db.collections.Tag.save(newTag);
await this.externalHooks.run('tag.afterUpdate', [tag]); await this.externalHooks.run('tag.afterUpdate', [tag]);
@ -1326,7 +1324,7 @@ class App {
await this.externalHooks.run('tag.beforeDelete', [id]); await this.externalHooks.run('tag.beforeDelete', [id]);
await Db.collections.Tag!.delete({ id }); await Db.collections.Tag.delete({ id });
await this.externalHooks.run('tag.afterDelete', [id]); await this.externalHooks.run('tag.afterDelete', [id]);
@ -1591,7 +1589,7 @@ class App {
ResponseHelper.send(async (req: WorkflowRequest.GetAllActivationErrors) => { ResponseHelper.send(async (req: WorkflowRequest.GetAllActivationErrors) => {
const { id: workflowId } = req.params; const { id: workflowId } = req.params;
const shared = await Db.collections.SharedWorkflow!.findOne({ const shared = await Db.collections.SharedWorkflow.findOne({
relations: ['workflow'], relations: ['workflow'],
where: whereClause({ where: whereClause({
user: req.user, user: req.user,
@ -1794,7 +1792,7 @@ class App {
newCredentialsData.updatedAt = this.getCurrentDate(); newCredentialsData.updatedAt = this.getCurrentDate();
// Update the credentials in DB // Update the credentials in DB
await Db.collections.Credentials!.update(credentialId, newCredentialsData); await Db.collections.Credentials.update(credentialId, newCredentialsData);
LoggerProxy.verbose('OAuth1 authorization successful for new credential', { LoggerProxy.verbose('OAuth1 authorization successful for new credential', {
userId: req.user.id, userId: req.user.id,
@ -1911,7 +1909,7 @@ class App {
// Add special database related data // Add special database related data
newCredentialsData.updatedAt = this.getCurrentDate(); newCredentialsData.updatedAt = this.getCurrentDate();
// Save the credentials in DB // Save the credentials in DB
await Db.collections.Credentials!.update(credentialId, newCredentialsData); await Db.collections.Credentials.update(credentialId, newCredentialsData);
LoggerProxy.verbose('OAuth1 callback successful for new credential', { LoggerProxy.verbose('OAuth1 callback successful for new credential', {
userId: req.user?.id, userId: req.user?.id,
@ -2026,7 +2024,7 @@ class App {
newCredentialsData.updatedAt = this.getCurrentDate(); newCredentialsData.updatedAt = this.getCurrentDate();
// Update the credentials in DB // Update the credentials in DB
await Db.collections.Credentials!.update(req.query.id as string, newCredentialsData); await Db.collections.Credentials.update(req.query.id as string, newCredentialsData);
const authQueryParameters = _.get(oauthCredentials, 'authQueryParameters', '') as string; const authQueryParameters = _.get(oauthCredentials, 'authQueryParameters', '') as string;
let returnUri = oAuthObj.code.getUri(); let returnUri = oAuthObj.code.getUri();
@ -2213,7 +2211,7 @@ class App {
// Add special database related data // Add special database related data
newCredentialsData.updatedAt = this.getCurrentDate(); newCredentialsData.updatedAt = this.getCurrentDate();
// Save the credentials in DB // Save the credentials in DB
await Db.collections.Credentials!.update(state.cid, newCredentialsData); await Db.collections.Credentials.update(state.cid, newCredentialsData);
LoggerProxy.verbose('OAuth2 callback successful for new credential', { LoggerProxy.verbose('OAuth2 callback successful for new credential', {
userId: req.user?.id, userId: req.user?.id,
credentialId: state.cid, credentialId: state.cid,
@ -2319,7 +2317,7 @@ class App {
}); });
} }
const executions = await Db.collections.Execution!.find(findOptions); const executions = await Db.collections.Execution.find(findOptions);
const { count, estimated } = await getExecutionsCount(countFilter, req.user); const { count, estimated } = await getExecutionsCount(countFilter, req.user);
@ -2360,7 +2358,7 @@ class App {
if (!sharedWorkflowIds.length) return undefined; if (!sharedWorkflowIds.length) return undefined;
const execution = await Db.collections.Execution!.findOne({ const execution = await Db.collections.Execution.findOne({
where: { where: {
id: executionId, id: executionId,
workflowId: In(sharedWorkflowIds), workflowId: In(sharedWorkflowIds),
@ -2403,7 +2401,7 @@ class App {
if (!sharedWorkflowIds.length) return false; if (!sharedWorkflowIds.length) return false;
const execution = await Db.collections.Execution!.findOne({ const execution = await Db.collections.Execution.findOne({
where: { where: {
id: executionId, id: executionId,
workflowId: In(sharedWorkflowIds), workflowId: In(sharedWorkflowIds),
@ -2465,9 +2463,7 @@ class App {
// Loads the currently saved workflow to execute instead of the // Loads the currently saved workflow to execute instead of the
// one saved at the time of the execution. // one saved at the time of the execution.
const workflowId = fullExecutionData.workflowData.id; const workflowId = fullExecutionData.workflowData.id;
const workflowData = (await Db.collections.Workflow!.findOne( const workflowData = (await Db.collections.Workflow.findOne(workflowId)) as IWorkflowBase;
workflowId,
)) as IWorkflowBase;
if (workflowData === undefined) { if (workflowData === undefined) {
throw new Error( throw new Error(
@ -2549,7 +2545,7 @@ class App {
Object.assign(filters, requestFilters); Object.assign(filters, requestFilters);
} }
const executions = await Db.collections.Execution!.find({ const executions = await Db.collections.Execution.find({
where: { where: {
workflowId: In(sharedWorkflowIds), workflowId: In(sharedWorkflowIds),
...filters, ...filters,
@ -2564,7 +2560,7 @@ class App {
idsToDelete.map(async (id) => binaryDataManager.deleteBinaryDataByExecutionId(id)), idsToDelete.map(async (id) => binaryDataManager.deleteBinaryDataByExecutionId(id)),
); );
await Db.collections.Execution!.delete({ id: In(idsToDelete) }); await Db.collections.Execution.delete({ id: In(idsToDelete) });
return; return;
} }
@ -2572,7 +2568,7 @@ class App {
// delete executions by IDs, if user may access the underyling worfklows // delete executions by IDs, if user may access the underyling worfklows
if (ids) { if (ids) {
const executions = await Db.collections.Execution!.find({ const executions = await Db.collections.Execution.find({
where: { where: {
id: In(ids), id: In(ids),
workflowId: In(sharedWorkflowIds), workflowId: In(sharedWorkflowIds),
@ -2593,7 +2589,7 @@ class App {
idsToDelete.map(async (id) => binaryDataManager.deleteBinaryDataByExecutionId(id)), idsToDelete.map(async (id) => binaryDataManager.deleteBinaryDataByExecutionId(id)),
); );
await Db.collections.Execution!.delete(idsToDelete); await Db.collections.Execution.delete(idsToDelete);
} }
}), }),
); );
@ -2644,7 +2640,7 @@ class App {
Object.assign(findOptions.where, { workflowId: In(sharedWorkflowIds) }); Object.assign(findOptions.where, { workflowId: In(sharedWorkflowIds) });
} }
const executions = await Db.collections.Execution!.find(findOptions); const executions = await Db.collections.Execution.find(findOptions);
if (!executions.length) return []; if (!executions.length) return [];
@ -2705,7 +2701,7 @@ class App {
throw new ResponseHelper.ResponseError('Execution not found', undefined, 404); throw new ResponseHelper.ResponseError('Execution not found', undefined, 404);
} }
const execution = await Db.collections.Execution!.findOne({ const execution = await Db.collections.Execution.findOne({
where: { where: {
id: executionId, id: executionId,
workflowId: In(sharedWorkflowIds), workflowId: In(sharedWorkflowIds),
@ -2748,7 +2744,7 @@ class App {
await Queue.getInstance().stopJob(job); await Queue.getInstance().stopJob(job);
} }
const executionDb = (await Db.collections.Execution?.findOne( const executionDb = (await Db.collections.Execution.findOne(
req.params.id, req.params.id,
)) as IExecutionFlattedDb; )) as IExecutionFlattedDb;
const fullExecutionData = ResponseHelper.unflattenExecutionData(executionDb); const fullExecutionData = ResponseHelper.unflattenExecutionData(executionDb);
@ -3083,7 +3079,7 @@ async function getExecutionsCount(
if (dbType !== 'postgresdb' || filteredFields.length > 0 || user.globalRole.name !== 'owner') { if (dbType !== 'postgresdb' || filteredFields.length > 0 || user.globalRole.name !== 'owner') {
const sharedWorkflowIds = await getSharedWorkflowIds(user); const sharedWorkflowIds = await getSharedWorkflowIds(user);
const count = await Db.collections.Execution!.count({ const count = await Db.collections.Execution.count({
where: { where: {
workflowId: In(sharedWorkflowIds), workflowId: In(sharedWorkflowIds),
...countFilter, ...countFilter,
@ -3097,7 +3093,7 @@ async function getExecutionsCount(
// Get an estimate of rows count. // Get an estimate of rows count.
const estimateRowsNumberSql = const estimateRowsNumberSql =
"SELECT n_live_tup FROM pg_stat_all_tables WHERE relname = 'execution_entity';"; "SELECT n_live_tup FROM pg_stat_all_tables WHERE relname = 'execution_entity';";
const rows: Array<{ n_live_tup: string }> = await Db.collections.Execution!.query( const rows: Array<{ n_live_tup: string }> = await Db.collections.Execution.query(
estimateRowsNumberSql, estimateRowsNumberSql,
); );
@ -3114,7 +3110,7 @@ async function getExecutionsCount(
const sharedWorkflowIds = await getSharedWorkflowIds(user); const sharedWorkflowIds = await getSharedWorkflowIds(user);
const count = await Db.collections.Execution!.count({ const count = await Db.collections.Execution.count({
where: { where: {
workflowId: In(sharedWorkflowIds), workflowId: In(sharedWorkflowIds),
}, },

View file

@ -50,7 +50,7 @@ export class WaitingWebhooks {
const executionId = pathParts.shift(); const executionId = pathParts.shift();
const path = pathParts.join('/'); const path = pathParts.join('/');
const execution = await Db.collections.Execution?.findOne(executionId); const execution = await Db.collections.Execution.findOne(executionId);
if (execution === undefined) { if (execution === undefined) {
throw new ResponseHelper.ResponseError( throw new ResponseHelper.ResponseError(

View file

@ -584,7 +584,7 @@ function hookFunctionsSave(parentProcessMode?: string): IWorkflowExecuteHooks {
if (fullRunData.finished === true && this.retryOf !== undefined) { if (fullRunData.finished === true && this.retryOf !== undefined) {
// If the retry was successful save the reference it on the original execution // If the retry was successful save the reference it on the original execution
// await Db.collections.Execution!.save(executionData as IExecutionFlattedDb); // await Db.collections.Execution.save(executionData as IExecutionFlattedDb);
await Db.collections.Execution.update(this.retryOf, { await Db.collections.Execution.update(this.retryOf, {
retrySuccessId: this.executionId, retrySuccessId: this.executionId,
}); });

View file

@ -479,7 +479,7 @@ export async function replaceInvalidCredentials(workflow: WorkflowEntity): Promi
credentialsByName[nodeCredentialType] = {}; credentialsByName[nodeCredentialType] = {};
} }
if (credentialsByName[nodeCredentialType][name] === undefined) { if (credentialsByName[nodeCredentialType][name] === undefined) {
const credentials = await Db.collections.Credentials?.find({ const credentials = await Db.collections.Credentials.find({
name, name,
type: nodeCredentialType, type: nodeCredentialType,
}); });
@ -515,7 +515,7 @@ export async function replaceInvalidCredentials(workflow: WorkflowEntity): Promi
// check if credentials for ID-type are not yet cached // check if credentials for ID-type are not yet cached
if (credentialsById[nodeCredentialType][nodeCredentials.id] === undefined) { if (credentialsById[nodeCredentialType][nodeCredentials.id] === undefined) {
// check first if ID-type combination exists // check first if ID-type combination exists
const credentials = await Db.collections.Credentials?.findOne({ const credentials = await Db.collections.Credentials.findOne({
id: nodeCredentials.id, id: nodeCredentials.id,
type: nodeCredentialType, type: nodeCredentialType,
}); });
@ -529,7 +529,7 @@ export async function replaceInvalidCredentials(workflow: WorkflowEntity): Promi
continue; continue;
} }
// no credentials found for ID, check if some exist for name // no credentials found for ID, check if some exist for name
const credsByName = await Db.collections.Credentials?.find({ const credsByName = await Db.collections.Credentials.find({
name: nodeCredentials.name, name: nodeCredentials.name,
type: nodeCredentialType, type: nodeCredentialType,
}); });

View file

@ -33,7 +33,7 @@ beforeEach(async () => {
config.set('userManagement.isInstanceOwnerSetUp', true); config.set('userManagement.isInstanceOwnerSetUp', true);
await Db.collections.Settings!.update( await Db.collections.Settings.update(
{ key: 'userManagement.isInstanceOwnerSetUp' }, { key: 'userManagement.isInstanceOwnerSetUp' },
{ value: JSON.stringify(true) }, { value: JSON.stringify(true) },
); );
@ -102,7 +102,7 @@ test('GET /login should return cookie if UM is disabled', async () => {
config.set('userManagement.isInstanceOwnerSetUp', false); config.set('userManagement.isInstanceOwnerSetUp', false);
await Db.collections.Settings!.update( await Db.collections.Settings.update(
{ key: 'userManagement.isInstanceOwnerSetUp' }, { key: 'userManagement.isInstanceOwnerSetUp' },
{ value: JSON.stringify(false) }, { value: JSON.stringify(false) },
); );

View file

@ -1,157 +0,0 @@
import express from 'express';
import validator from 'validator';
import { v4 as uuid } from 'uuid';
import * as config from '../../config';
import * as utils from './shared/utils';
import { LOGGED_OUT_RESPONSE_BODY } from './shared/constants';
import { Db } from '../../src';
import { Role } from '../../src/databases/entities/Role';
import { randomEmail, randomValidPassword, randomName } from './shared/random';
import { getGlobalOwnerRole } from './shared/testDb';
import * as testDb from './shared/testDb';
jest.mock('../../src/telemetry');
let globalOwnerRole: Role;
let app: express.Application;
let testDbName = '';
beforeAll(async () => {
app = utils.initTestServer({ endpointGroups: ['auth'], applyAuth: true });
const initResult = await testDb.init();
testDbName = initResult.testDbName;
await testDb.truncate(['User'], testDbName);
globalOwnerRole = await getGlobalOwnerRole();
utils.initTestLogger();
utils.initTestTelemetry();
});
beforeEach(async () => {
await testDb.createUser({
id: uuid(),
email: TEST_USER.email,
firstName: TEST_USER.firstName,
lastName: TEST_USER.lastName,
password: TEST_USER.password,
globalRole: globalOwnerRole,
});
config.set('userManagement.isInstanceOwnerSetUp', true);
await Db.collections.Settings!.update(
{ key: 'userManagement.isInstanceOwnerSetUp' },
{ value: JSON.stringify(true) },
);
});
afterEach(async () => {
await testDb.truncate(['User'], testDbName);
});
afterAll(async () => {
await testDb.terminate(testDbName);
});
test('POST /login should log user in', async () => {
const authlessAgent = utils.createAgent(app);
await Promise.all(
[
{
email: TEST_USER.email,
password: TEST_USER.password,
},
{
email: TEST_USER.email.toUpperCase(),
password: TEST_USER.password,
},
].map(async (payload) => {
const response = await authlessAgent.post('/login').send(payload);
expect(response.statusCode).toBe(200);
const {
id,
email,
firstName,
lastName,
password,
personalizationAnswers,
globalRole,
resetPasswordToken,
} = response.body.data;
expect(validator.isUUID(id)).toBe(true);
expect(email).toBe(TEST_USER.email);
expect(firstName).toBe(TEST_USER.firstName);
expect(lastName).toBe(TEST_USER.lastName);
expect(password).toBeUndefined();
expect(personalizationAnswers).toBeNull();
expect(resetPasswordToken).toBeUndefined();
expect(globalRole).toBeDefined();
expect(globalRole.name).toBe('owner');
expect(globalRole.scope).toBe('global');
const authToken = utils.getAuthToken(response);
expect(authToken).toBeDefined();
}),
);
});
test('GET /login should receive logged in user', async () => {
const owner = await Db.collections.User!.findOneOrFail();
const authOwnerAgent = utils.createAgent(app, { auth: true, user: owner });
const response = await authOwnerAgent.get('/login');
expect(response.statusCode).toBe(200);
const {
id,
email,
firstName,
lastName,
password,
personalizationAnswers,
globalRole,
resetPasswordToken,
} = response.body.data;
expect(validator.isUUID(id)).toBe(true);
expect(email).toBe(TEST_USER.email);
expect(firstName).toBe(TEST_USER.firstName);
expect(lastName).toBe(TEST_USER.lastName);
expect(password).toBeUndefined();
expect(personalizationAnswers).toBeNull();
expect(password).toBeUndefined();
expect(resetPasswordToken).toBeUndefined();
expect(globalRole).toBeDefined();
expect(globalRole.name).toBe('owner');
expect(globalRole.scope).toBe('global');
expect(response.headers['set-cookie']).toBeUndefined();
});
test('POST /logout should log user out', async () => {
const owner = await Db.collections.User!.findOneOrFail();
const authOwnerAgent = utils.createAgent(app, { auth: true, user: owner });
const response = await authOwnerAgent.post('/logout');
expect(response.statusCode).toBe(200);
expect(response.body).toEqual(LOGGED_OUT_RESPONSE_BODY);
const authToken = utils.getAuthToken(response);
expect(authToken).toBeUndefined();
});
const TEST_USER = {
email: randomEmail(),
password: randomValidPassword(),
firstName: randomName(),
lastName: randomName(),
};

View file

@ -62,14 +62,14 @@ test('POST /credentials should create cred', async () => {
expect(nodesAccess[0].nodeType).toBe(payload.nodesAccess[0].nodeType); expect(nodesAccess[0].nodeType).toBe(payload.nodesAccess[0].nodeType);
expect(encryptedData).not.toBe(payload.data); expect(encryptedData).not.toBe(payload.data);
const credential = await Db.collections.Credentials!.findOneOrFail(id); const credential = await Db.collections.Credentials.findOneOrFail(id);
expect(credential.name).toBe(payload.name); expect(credential.name).toBe(payload.name);
expect(credential.type).toBe(payload.type); expect(credential.type).toBe(payload.type);
expect(credential.nodesAccess[0].nodeType).toBe(payload.nodesAccess[0].nodeType); expect(credential.nodesAccess[0].nodeType).toBe(payload.nodesAccess[0].nodeType);
expect(credential.data).not.toBe(payload.data); expect(credential.data).not.toBe(payload.data);
const sharedCredential = await Db.collections.SharedCredentials!.findOneOrFail({ const sharedCredential = await Db.collections.SharedCredentials.findOneOrFail({
relations: ['user', 'credentials'], relations: ['user', 'credentials'],
where: { credentials: credential }, where: { credentials: credential },
}); });
@ -131,11 +131,11 @@ test('DELETE /credentials/:id should delete owned cred for owner', async () => {
expect(response.statusCode).toBe(200); expect(response.statusCode).toBe(200);
expect(response.body).toEqual({ data: true }); expect(response.body).toEqual({ data: true });
const deletedCredential = await Db.collections.Credentials!.findOne(savedCredential.id); const deletedCredential = await Db.collections.Credentials.findOne(savedCredential.id);
expect(deletedCredential).toBeUndefined(); // deleted expect(deletedCredential).toBeUndefined(); // deleted
const deletedSharedCredential = await Db.collections.SharedCredentials!.findOne(); const deletedSharedCredential = await Db.collections.SharedCredentials.findOne();
expect(deletedSharedCredential).toBeUndefined(); // deleted expect(deletedSharedCredential).toBeUndefined(); // deleted
}); });
@ -151,11 +151,11 @@ test('DELETE /credentials/:id should delete non-owned cred for owner', async ()
expect(response.statusCode).toBe(200); expect(response.statusCode).toBe(200);
expect(response.body).toEqual({ data: true }); expect(response.body).toEqual({ data: true });
const deletedCredential = await Db.collections.Credentials!.findOne(savedCredential.id); const deletedCredential = await Db.collections.Credentials.findOne(savedCredential.id);
expect(deletedCredential).toBeUndefined(); // deleted expect(deletedCredential).toBeUndefined(); // deleted
const deletedSharedCredential = await Db.collections.SharedCredentials!.findOne(); const deletedSharedCredential = await Db.collections.SharedCredentials.findOne();
expect(deletedSharedCredential).toBeUndefined(); // deleted expect(deletedSharedCredential).toBeUndefined(); // deleted
}); });
@ -170,11 +170,11 @@ test('DELETE /credentials/:id should delete owned cred for member', async () =>
expect(response.statusCode).toBe(200); expect(response.statusCode).toBe(200);
expect(response.body).toEqual({ data: true }); expect(response.body).toEqual({ data: true });
const deletedCredential = await Db.collections.Credentials!.findOne(savedCredential.id); const deletedCredential = await Db.collections.Credentials.findOne(savedCredential.id);
expect(deletedCredential).toBeUndefined(); // deleted expect(deletedCredential).toBeUndefined(); // deleted
const deletedSharedCredential = await Db.collections.SharedCredentials!.findOne(); const deletedSharedCredential = await Db.collections.SharedCredentials.findOne();
expect(deletedSharedCredential).toBeUndefined(); // deleted expect(deletedSharedCredential).toBeUndefined(); // deleted
}); });
@ -189,11 +189,11 @@ test('DELETE /credentials/:id should not delete non-owned cred for member', asyn
expect(response.statusCode).toBe(404); expect(response.statusCode).toBe(404);
const shellCredential = await Db.collections.Credentials!.findOne(savedCredential.id); const shellCredential = await Db.collections.Credentials.findOne(savedCredential.id);
expect(shellCredential).toBeDefined(); // not deleted expect(shellCredential).toBeDefined(); // not deleted
const deletedSharedCredential = await Db.collections.SharedCredentials!.findOne(); const deletedSharedCredential = await Db.collections.SharedCredentials.findOne();
expect(deletedSharedCredential).toBeDefined(); // not deleted expect(deletedSharedCredential).toBeDefined(); // not deleted
}); });
@ -226,14 +226,14 @@ test('PATCH /credentials/:id should update owned cred for owner', async () => {
expect(nodesAccess[0].nodeType).toBe(patchPayload.nodesAccess[0].nodeType); expect(nodesAccess[0].nodeType).toBe(patchPayload.nodesAccess[0].nodeType);
expect(encryptedData).not.toBe(patchPayload.data); expect(encryptedData).not.toBe(patchPayload.data);
const credential = await Db.collections.Credentials!.findOneOrFail(id); const credential = await Db.collections.Credentials.findOneOrFail(id);
expect(credential.name).toBe(patchPayload.name); expect(credential.name).toBe(patchPayload.name);
expect(credential.type).toBe(patchPayload.type); expect(credential.type).toBe(patchPayload.type);
expect(credential.nodesAccess[0].nodeType).toBe(patchPayload.nodesAccess[0].nodeType); expect(credential.nodesAccess[0].nodeType).toBe(patchPayload.nodesAccess[0].nodeType);
expect(credential.data).not.toBe(patchPayload.data); expect(credential.data).not.toBe(patchPayload.data);
const sharedCredential = await Db.collections.SharedCredentials!.findOneOrFail({ const sharedCredential = await Db.collections.SharedCredentials.findOneOrFail({
relations: ['credentials'], relations: ['credentials'],
where: { credentials: credential }, where: { credentials: credential },
}); });
@ -261,14 +261,14 @@ test('PATCH /credentials/:id should update non-owned cred for owner', async () =
expect(nodesAccess[0].nodeType).toBe(patchPayload.nodesAccess[0].nodeType); expect(nodesAccess[0].nodeType).toBe(patchPayload.nodesAccess[0].nodeType);
expect(encryptedData).not.toBe(patchPayload.data); expect(encryptedData).not.toBe(patchPayload.data);
const credential = await Db.collections.Credentials!.findOneOrFail(id); const credential = await Db.collections.Credentials.findOneOrFail(id);
expect(credential.name).toBe(patchPayload.name); expect(credential.name).toBe(patchPayload.name);
expect(credential.type).toBe(patchPayload.type); expect(credential.type).toBe(patchPayload.type);
expect(credential.nodesAccess[0].nodeType).toBe(patchPayload.nodesAccess[0].nodeType); expect(credential.nodesAccess[0].nodeType).toBe(patchPayload.nodesAccess[0].nodeType);
expect(credential.data).not.toBe(patchPayload.data); expect(credential.data).not.toBe(patchPayload.data);
const sharedCredential = await Db.collections.SharedCredentials!.findOneOrFail({ const sharedCredential = await Db.collections.SharedCredentials.findOneOrFail({
relations: ['credentials'], relations: ['credentials'],
where: { credentials: credential }, where: { credentials: credential },
}); });
@ -295,14 +295,14 @@ test('PATCH /credentials/:id should update owned cred for member', async () => {
expect(nodesAccess[0].nodeType).toBe(patchPayload.nodesAccess[0].nodeType); expect(nodesAccess[0].nodeType).toBe(patchPayload.nodesAccess[0].nodeType);
expect(encryptedData).not.toBe(patchPayload.data); expect(encryptedData).not.toBe(patchPayload.data);
const credential = await Db.collections.Credentials!.findOneOrFail(id); const credential = await Db.collections.Credentials.findOneOrFail(id);
expect(credential.name).toBe(patchPayload.name); expect(credential.name).toBe(patchPayload.name);
expect(credential.type).toBe(patchPayload.type); expect(credential.type).toBe(patchPayload.type);
expect(credential.nodesAccess[0].nodeType).toBe(patchPayload.nodesAccess[0].nodeType); expect(credential.nodesAccess[0].nodeType).toBe(patchPayload.nodesAccess[0].nodeType);
expect(credential.data).not.toBe(patchPayload.data); expect(credential.data).not.toBe(patchPayload.data);
const sharedCredential = await Db.collections.SharedCredentials!.findOneOrFail({ const sharedCredential = await Db.collections.SharedCredentials.findOneOrFail({
relations: ['credentials'], relations: ['credentials'],
where: { credentials: credential }, where: { credentials: credential },
}); });
@ -323,7 +323,7 @@ test('PATCH /credentials/:id should not update non-owned cred for member', async
expect(response.statusCode).toBe(404); expect(response.statusCode).toBe(404);
const shellCredential = await Db.collections.Credentials!.findOneOrFail(savedCredential.id); const shellCredential = await Db.collections.Credentials.findOneOrFail(savedCredential.id);
expect(shellCredential.name).not.toBe(patchPayload.name); // not updated expect(shellCredential.name).not.toBe(patchPayload.name); // not updated
}); });

View file

@ -101,7 +101,7 @@ describe('Owner shell', () => {
expect(globalRole.name).toBe('owner'); expect(globalRole.name).toBe('owner');
expect(globalRole.scope).toBe('global'); expect(globalRole.scope).toBe('global');
const storedOwnerShell = await Db.collections.User!.findOneOrFail(id); const storedOwnerShell = await Db.collections.User.findOneOrFail(id);
expect(storedOwnerShell.email).toBe(validPayload.email.toLowerCase()); expect(storedOwnerShell.email).toBe(validPayload.email.toLowerCase());
expect(storedOwnerShell.firstName).toBe(validPayload.firstName); expect(storedOwnerShell.firstName).toBe(validPayload.firstName);
@ -117,7 +117,7 @@ describe('Owner shell', () => {
const response = await authOwnerShellAgent.patch('/me').send(invalidPayload); const response = await authOwnerShellAgent.patch('/me').send(invalidPayload);
expect(response.statusCode).toBe(400); expect(response.statusCode).toBe(400);
const storedOwnerShell = await Db.collections.User!.findOneOrFail(); const storedOwnerShell = await Db.collections.User.findOneOrFail();
expect(storedOwnerShell.email).toBeNull(); expect(storedOwnerShell.email).toBeNull();
expect(storedOwnerShell.firstName).toBeNull(); expect(storedOwnerShell.firstName).toBeNull();
expect(storedOwnerShell.lastName).toBeNull(); expect(storedOwnerShell.lastName).toBeNull();
@ -140,7 +140,7 @@ describe('Owner shell', () => {
const response = await authOwnerShellAgent.patch('/me/password').send(payload); const response = await authOwnerShellAgent.patch('/me/password').send(payload);
expect([400, 500].includes(response.statusCode)).toBe(true); expect([400, 500].includes(response.statusCode)).toBe(true);
const storedMember = await Db.collections.User!.findOneOrFail(); const storedMember = await Db.collections.User.findOneOrFail();
if (payload.newPassword) { if (payload.newPassword) {
expect(storedMember.password).not.toBe(payload.newPassword); expect(storedMember.password).not.toBe(payload.newPassword);
@ -152,7 +152,7 @@ describe('Owner shell', () => {
}), }),
); );
const storedOwnerShell = await Db.collections.User!.findOneOrFail(); const storedOwnerShell = await Db.collections.User.findOneOrFail();
expect(storedOwnerShell.password).toBeNull(); expect(storedOwnerShell.password).toBeNull();
}); });
@ -168,7 +168,7 @@ describe('Owner shell', () => {
expect(response.statusCode).toBe(200); expect(response.statusCode).toBe(200);
expect(response.body).toEqual(SUCCESS_RESPONSE_BODY); expect(response.body).toEqual(SUCCESS_RESPONSE_BODY);
const storedShellOwner = await Db.collections.User!.findOneOrFail({ const storedShellOwner = await Db.collections.User.findOneOrFail({
where: { email: IsNull() }, where: { email: IsNull() },
}); });
@ -181,7 +181,7 @@ describe('Member', () => {
beforeEach(async () => { beforeEach(async () => {
config.set('userManagement.isInstanceOwnerSetUp', true); config.set('userManagement.isInstanceOwnerSetUp', true);
await Db.collections.Settings!.update( await Db.collections.Settings.update(
{ key: 'userManagement.isInstanceOwnerSetUp' }, { key: 'userManagement.isInstanceOwnerSetUp' },
{ value: JSON.stringify(true) }, { value: JSON.stringify(true) },
); );
@ -255,7 +255,7 @@ describe('Member', () => {
expect(globalRole.name).toBe('member'); expect(globalRole.name).toBe('member');
expect(globalRole.scope).toBe('global'); expect(globalRole.scope).toBe('global');
const storedMember = await Db.collections.User!.findOneOrFail(id); const storedMember = await Db.collections.User.findOneOrFail(id);
expect(storedMember.email).toBe(validPayload.email.toLowerCase()); expect(storedMember.email).toBe(validPayload.email.toLowerCase());
expect(storedMember.firstName).toBe(validPayload.firstName); expect(storedMember.firstName).toBe(validPayload.firstName);
@ -271,7 +271,7 @@ describe('Member', () => {
const response = await authMemberAgent.patch('/me').send(invalidPayload); const response = await authMemberAgent.patch('/me').send(invalidPayload);
expect(response.statusCode).toBe(400); expect(response.statusCode).toBe(400);
const storedMember = await Db.collections.User!.findOneOrFail(); const storedMember = await Db.collections.User.findOneOrFail();
expect(storedMember.email).toBe(member.email); expect(storedMember.email).toBe(member.email);
expect(storedMember.firstName).toBe(member.firstName); expect(storedMember.firstName).toBe(member.firstName);
expect(storedMember.lastName).toBe(member.lastName); expect(storedMember.lastName).toBe(member.lastName);
@ -295,7 +295,7 @@ describe('Member', () => {
expect(response.statusCode).toBe(200); expect(response.statusCode).toBe(200);
expect(response.body).toEqual(SUCCESS_RESPONSE_BODY); expect(response.body).toEqual(SUCCESS_RESPONSE_BODY);
const storedMember = await Db.collections.User!.findOneOrFail(); const storedMember = await Db.collections.User.findOneOrFail();
expect(storedMember.password).not.toBe(member.password); expect(storedMember.password).not.toBe(member.password);
expect(storedMember.password).not.toBe(validPayload.newPassword); expect(storedMember.password).not.toBe(validPayload.newPassword);
}); });
@ -308,7 +308,7 @@ describe('Member', () => {
const response = await authMemberAgent.patch('/me/password').send(payload); const response = await authMemberAgent.patch('/me/password').send(payload);
expect([400, 500].includes(response.statusCode)).toBe(true); expect([400, 500].includes(response.statusCode)).toBe(true);
const storedMember = await Db.collections.User!.findOneOrFail(); const storedMember = await Db.collections.User.findOneOrFail();
if (payload.newPassword) { if (payload.newPassword) {
expect(storedMember.password).not.toBe(payload.newPassword); expect(storedMember.password).not.toBe(payload.newPassword);
@ -330,7 +330,7 @@ describe('Member', () => {
expect(response.statusCode).toBe(200); expect(response.statusCode).toBe(200);
expect(response.body).toEqual(SUCCESS_RESPONSE_BODY); expect(response.body).toEqual(SUCCESS_RESPONSE_BODY);
const { personalizationAnswers: storedAnswers } = await Db.collections.User!.findOneOrFail(); const { personalizationAnswers: storedAnswers } = await Db.collections.User.findOneOrFail();
expect(storedAnswers).toEqual(validPayload); expect(storedAnswers).toEqual(validPayload);
} }
@ -410,7 +410,7 @@ describe('Owner', () => {
expect(globalRole.name).toBe('owner'); expect(globalRole.name).toBe('owner');
expect(globalRole.scope).toBe('global'); expect(globalRole.scope).toBe('global');
const storedOwner = await Db.collections.User!.findOneOrFail(id); const storedOwner = await Db.collections.User.findOneOrFail(id);
expect(storedOwner.email).toBe(validPayload.email.toLowerCase()); expect(storedOwner.email).toBe(validPayload.email.toLowerCase());
expect(storedOwner.firstName).toBe(validPayload.firstName); expect(storedOwner.firstName).toBe(validPayload.firstName);

View file

@ -81,7 +81,7 @@ test('POST /owner should create owner and enable isInstanceOwnerSetUp', async ()
expect(globalRole.name).toBe('owner'); expect(globalRole.name).toBe('owner');
expect(globalRole.scope).toBe('global'); expect(globalRole.scope).toBe('global');
const storedOwner = await Db.collections.User!.findOneOrFail(id); const storedOwner = await Db.collections.User.findOneOrFail(id);
expect(storedOwner.password).not.toBe(newOwnerData.password); expect(storedOwner.password).not.toBe(newOwnerData.password);
expect(storedOwner.email).toBe(newOwnerData.email); expect(storedOwner.email).toBe(newOwnerData.email);
expect(storedOwner.firstName).toBe(newOwnerData.firstName); expect(storedOwner.firstName).toBe(newOwnerData.firstName);
@ -113,7 +113,7 @@ test('POST /owner should create owner with lowercased email', async () => {
expect(email).toBe(newOwnerData.email.toLowerCase()); expect(email).toBe(newOwnerData.email.toLowerCase());
const storedOwner = await Db.collections.User!.findOneOrFail(id); const storedOwner = await Db.collections.User.findOneOrFail(id);
expect(storedOwner.email).toBe(newOwnerData.email.toLowerCase()); expect(storedOwner.email).toBe(newOwnerData.email.toLowerCase());
}); });
@ -140,7 +140,7 @@ test('POST /owner/skip-setup should persist skipping setup to the DB', async ()
const skipConfig = config.getEnv('userManagement.skipInstanceOwnerSetup'); const skipConfig = config.getEnv('userManagement.skipInstanceOwnerSetup');
expect(skipConfig).toBe(true); expect(skipConfig).toBe(true);
const { value } = await Db.collections.Settings!.findOneOrFail({ const { value } = await Db.collections.Settings.findOneOrFail({
key: 'userManagement.skipInstanceOwnerSetup', key: 'userManagement.skipInstanceOwnerSetup',
}); });
expect(value).toBe('true'); expect(value).toBe('true');

View file

@ -67,7 +67,7 @@ test(
expect(response.statusCode).toBe(200); expect(response.statusCode).toBe(200);
expect(response.body).toEqual({}); expect(response.body).toEqual({});
const user = await Db.collections.User!.findOneOrFail({ email: payload.email }); const user = await Db.collections.User.findOneOrFail({ email: payload.email });
expect(user.resetPasswordToken).toBeDefined(); expect(user.resetPasswordToken).toBeDefined();
expect(user.resetPasswordTokenExpiration).toBeGreaterThan(Math.ceil(Date.now() / 1000)); expect(user.resetPasswordTokenExpiration).toBeGreaterThan(Math.ceil(Date.now() / 1000));
}), }),
@ -85,7 +85,7 @@ test('POST /forgot-password should fail if emailing is not set up', async () =>
expect(response.statusCode).toBe(500); expect(response.statusCode).toBe(500);
const storedOwner = await Db.collections.User!.findOneOrFail({ email: owner.email }); const storedOwner = await Db.collections.User.findOneOrFail({ email: owner.email });
expect(storedOwner.resetPasswordToken).toBeNull(); expect(storedOwner.resetPasswordToken).toBeNull();
}); });
@ -109,7 +109,7 @@ test('POST /forgot-password should fail with invalid inputs', async () => {
const response = await authlessAgent.post('/forgot-password').send(invalidPayload); const response = await authlessAgent.post('/forgot-password').send(invalidPayload);
expect(response.statusCode).toBe(400); expect(response.statusCode).toBe(400);
const storedOwner = await Db.collections.User!.findOneOrFail({ email: owner.email }); const storedOwner = await Db.collections.User.findOneOrFail({ email: owner.email });
expect(storedOwner.resetPasswordToken).toBeNull(); expect(storedOwner.resetPasswordToken).toBeNull();
}), }),
); );
@ -133,7 +133,7 @@ test('GET /resolve-password-token should succeed with valid inputs', async () =>
const resetPasswordToken = uuid(); const resetPasswordToken = uuid();
const resetPasswordTokenExpiration = Math.floor(Date.now() / 1000) + 100; const resetPasswordTokenExpiration = Math.floor(Date.now() / 1000) + 100;
await Db.collections.User!.update(owner.id, { await Db.collections.User.update(owner.id, {
resetPasswordToken, resetPasswordToken,
resetPasswordTokenExpiration, resetPasswordTokenExpiration,
}); });
@ -183,7 +183,7 @@ test('GET /resolve-password-token should fail if token is expired', async () =>
const resetPasswordToken = uuid(); const resetPasswordToken = uuid();
const resetPasswordTokenExpiration = Math.floor(Date.now() / 1000) - 1; const resetPasswordTokenExpiration = Math.floor(Date.now() / 1000) - 1;
await Db.collections.User!.update(owner.id, { await Db.collections.User.update(owner.id, {
resetPasswordToken, resetPasswordToken,
resetPasswordTokenExpiration, resetPasswordTokenExpiration,
}); });
@ -205,7 +205,7 @@ test('POST /change-password should succeed with valid inputs', async () => {
const resetPasswordToken = uuid(); const resetPasswordToken = uuid();
const resetPasswordTokenExpiration = Math.floor(Date.now() / 1000) + 100; const resetPasswordTokenExpiration = Math.floor(Date.now() / 1000) + 100;
await Db.collections.User!.update(owner.id, { await Db.collections.User.update(owner.id, {
resetPasswordToken, resetPasswordToken,
resetPasswordTokenExpiration, resetPasswordTokenExpiration,
}); });
@ -223,7 +223,7 @@ test('POST /change-password should succeed with valid inputs', async () => {
const authToken = utils.getAuthToken(response); const authToken = utils.getAuthToken(response);
expect(authToken).toBeDefined(); expect(authToken).toBeDefined();
const { password: storedPassword } = await Db.collections.User!.findOneOrFail(owner.id); const { password: storedPassword } = await Db.collections.User.findOneOrFail(owner.id);
const comparisonResult = await compare(passwordToStore, storedPassword); const comparisonResult = await compare(passwordToStore, storedPassword);
expect(comparisonResult).toBe(true); expect(comparisonResult).toBe(true);
@ -238,7 +238,7 @@ test('POST /change-password should fail with invalid inputs', async () => {
const resetPasswordToken = uuid(); const resetPasswordToken = uuid();
const resetPasswordTokenExpiration = Math.floor(Date.now() / 1000) + 100; const resetPasswordTokenExpiration = Math.floor(Date.now() / 1000) + 100;
await Db.collections.User!.update(owner.id, { await Db.collections.User.update(owner.id, {
resetPasswordToken, resetPasswordToken,
resetPasswordTokenExpiration, resetPasswordTokenExpiration,
}); });
@ -267,7 +267,7 @@ test('POST /change-password should fail with invalid inputs', async () => {
const response = await authlessAgent.post('/change-password').query(invalidPayload); const response = await authlessAgent.post('/change-password').query(invalidPayload);
expect(response.statusCode).toBe(400); expect(response.statusCode).toBe(400);
const { password: storedPassword } = await Db.collections.User!.findOneOrFail(); const { password: storedPassword } = await Db.collections.User.findOneOrFail();
expect(owner.password).toBe(storedPassword); expect(owner.password).toBe(storedPassword);
}), }),
); );
@ -281,7 +281,7 @@ test('POST /change-password should fail when token has expired', async () => {
const resetPasswordToken = uuid(); const resetPasswordToken = uuid();
const resetPasswordTokenExpiration = Math.floor(Date.now() / 1000) - 1; const resetPasswordTokenExpiration = Math.floor(Date.now() / 1000) - 1;
await Db.collections.User!.update(owner.id, { await Db.collections.User.update(owner.id, {
resetPasswordToken, resetPasswordToken,
resetPasswordTokenExpiration, resetPasswordTokenExpiration,
}); });

View file

@ -109,7 +109,7 @@ export async function truncate(collections: CollectionName[], testDbName: string
if (dbType === 'sqlite') { if (dbType === 'sqlite') {
await testDb.query('PRAGMA foreign_keys=OFF'); await testDb.query('PRAGMA foreign_keys=OFF');
await Promise.all(collections.map((collection) => Db.collections[collection]!.clear())); await Promise.all(collections.map((collection) => Db.collections[collection].clear()));
return testDb.query('PRAGMA foreign_keys=ON'); return testDb.query('PRAGMA foreign_keys=ON');
} }
@ -182,11 +182,11 @@ export async function saveCredential(
Object.assign(newCredential, encryptedData); Object.assign(newCredential, encryptedData);
const savedCredential = await Db.collections.Credentials!.save(newCredential); const savedCredential = await Db.collections.Credentials.save(newCredential);
savedCredential.data = newCredential.data; savedCredential.data = newCredential.data;
await Db.collections.SharedCredentials!.save({ await Db.collections.SharedCredentials.save({
user, user,
credentials: savedCredential, credentials: savedCredential,
role, role,
@ -211,7 +211,7 @@ export async function createUser(attributes: Partial<User> & { globalRole: Role
...rest, ...rest,
}; };
return Db.collections.User!.save(user); return Db.collections.User.save(user);
} }
export function createUserShell(globalRole: Role): Promise<User> { export function createUserShell(globalRole: Role): Promise<User> {
@ -225,7 +225,7 @@ export function createUserShell(globalRole: Role): Promise<User> {
shell.email = randomEmail(); shell.email = randomEmail();
} }
return Db.collections.User!.save(shell); return Db.collections.User.save(shell);
} }
// ---------------------------------- // ----------------------------------
@ -233,28 +233,28 @@ export function createUserShell(globalRole: Role): Promise<User> {
// ---------------------------------- // ----------------------------------
export function getGlobalOwnerRole() { export function getGlobalOwnerRole() {
return Db.collections.Role!.findOneOrFail({ return Db.collections.Role.findOneOrFail({
name: 'owner', name: 'owner',
scope: 'global', scope: 'global',
}); });
} }
export function getGlobalMemberRole() { export function getGlobalMemberRole() {
return Db.collections.Role!.findOneOrFail({ return Db.collections.Role.findOneOrFail({
name: 'member', name: 'member',
scope: 'global', scope: 'global',
}); });
} }
export function getWorkflowOwnerRole() { export function getWorkflowOwnerRole() {
return Db.collections.Role!.findOneOrFail({ return Db.collections.Role.findOneOrFail({
name: 'owner', name: 'owner',
scope: 'workflow', scope: 'workflow',
}); });
} }
export function getCredentialOwnerRole() { export function getCredentialOwnerRole() {
return Db.collections.Role!.findOneOrFail({ return Db.collections.Role.findOneOrFail({
name: 'owner', name: 'owner',
scope: 'credential', scope: 'credential',
}); });

View file

@ -198,7 +198,7 @@ export function getAuthToken(response: request.Response, authCookieName = AUTH_C
// ---------------------------------- // ----------------------------------
export async function isInstanceOwnerSetUp() { export async function isInstanceOwnerSetUp() {
const { value } = await Db.collections.Settings!.findOneOrFail({ const { value } = await Db.collections.Settings.findOneOrFail({
key: 'userManagement.isInstanceOwnerSetUp', key: 'userManagement.isInstanceOwnerSetUp',
}); });

View file

@ -119,9 +119,9 @@ test('DELETE /users/:id should delete the user', async () => {
nodes: [], nodes: [],
}); });
const savedWorkflow = await Db.collections.Workflow!.save(newWorkflow); const savedWorkflow = await Db.collections.Workflow.save(newWorkflow);
await Db.collections.SharedWorkflow!.save({ await Db.collections.SharedWorkflow.save({
role: workflowOwnerRole, role: workflowOwnerRole,
user: userToDelete, user: userToDelete,
workflow: savedWorkflow, workflow: savedWorkflow,
@ -136,9 +136,9 @@ test('DELETE /users/:id should delete the user', async () => {
nodesAccess: [], nodesAccess: [],
}); });
const savedCredential = await Db.collections.Credentials!.save(newCredential); const savedCredential = await Db.collections.Credentials.save(newCredential);
await Db.collections.SharedCredentials!.save({ await Db.collections.SharedCredentials.save({
role: credentialOwnerRole, role: credentialOwnerRole,
user: userToDelete, user: userToDelete,
credentials: savedCredential, credentials: savedCredential,
@ -149,27 +149,27 @@ test('DELETE /users/:id should delete the user', async () => {
expect(response.statusCode).toBe(200); expect(response.statusCode).toBe(200);
expect(response.body).toEqual(SUCCESS_RESPONSE_BODY); expect(response.body).toEqual(SUCCESS_RESPONSE_BODY);
const user = await Db.collections.User!.findOne(userToDelete.id); const user = await Db.collections.User.findOne(userToDelete.id);
expect(user).toBeUndefined(); // deleted expect(user).toBeUndefined(); // deleted
const sharedWorkflow = await Db.collections.SharedWorkflow!.findOne({ const sharedWorkflow = await Db.collections.SharedWorkflow.findOne({
relations: ['user'], relations: ['user'],
where: { user: userToDelete }, where: { user: userToDelete },
}); });
expect(sharedWorkflow).toBeUndefined(); // deleted expect(sharedWorkflow).toBeUndefined(); // deleted
const sharedCredential = await Db.collections.SharedCredentials!.findOne({ const sharedCredential = await Db.collections.SharedCredentials.findOne({
relations: ['user'], relations: ['user'],
where: { user: userToDelete }, where: { user: userToDelete },
}); });
expect(sharedCredential).toBeUndefined(); // deleted expect(sharedCredential).toBeUndefined(); // deleted
const workflow = await Db.collections.Workflow!.findOne(savedWorkflow.id); const workflow = await Db.collections.Workflow.findOne(savedWorkflow.id);
expect(workflow).toBeUndefined(); // deleted expect(workflow).toBeUndefined(); // deleted
// TODO: Include active workflow and check whether webhook has been removed // TODO: Include active workflow and check whether webhook has been removed
const credential = await Db.collections.Credentials!.findOne(savedCredential.id); const credential = await Db.collections.Credentials.findOne(savedCredential.id);
expect(credential).toBeUndefined(); // deleted expect(credential).toBeUndefined(); // deleted
}); });
@ -181,7 +181,7 @@ test('DELETE /users/:id should fail to delete self', async () => {
expect(response.statusCode).toBe(400); expect(response.statusCode).toBe(400);
const user = await Db.collections.User!.findOne(owner.id); const user = await Db.collections.User.findOne(owner.id);
expect(user).toBeDefined(); expect(user).toBeDefined();
}); });
@ -197,7 +197,7 @@ test('DELETE /users/:id should fail if user to delete is transferee', async () =
expect(response.statusCode).toBe(400); expect(response.statusCode).toBe(400);
const user = await Db.collections.User!.findOne(idToDelete); const user = await Db.collections.User.findOne(idToDelete);
expect(user).toBeDefined(); expect(user).toBeDefined();
}); });
@ -205,7 +205,7 @@ test('DELETE /users/:id with transferId should perform transfer', async () => {
const owner = await testDb.createUser({ globalRole: globalOwnerRole }); const owner = await testDb.createUser({ globalRole: globalOwnerRole });
const authOwnerAgent = utils.createAgent(app, { auth: true, user: owner }); const authOwnerAgent = utils.createAgent(app, { auth: true, user: owner });
const userToDelete = await Db.collections.User!.save({ const userToDelete = await Db.collections.User.save({
id: uuid(), id: uuid(),
email: randomEmail(), email: randomEmail(),
password: randomValidPassword(), password: randomValidPassword(),
@ -225,9 +225,9 @@ test('DELETE /users/:id with transferId should perform transfer', async () => {
nodes: [], nodes: [],
}); });
const savedWorkflow = await Db.collections.Workflow!.save(newWorkflow); const savedWorkflow = await Db.collections.Workflow.save(newWorkflow);
await Db.collections.SharedWorkflow!.save({ await Db.collections.SharedWorkflow.save({
role: workflowOwnerRole, role: workflowOwnerRole,
user: userToDelete, user: userToDelete,
workflow: savedWorkflow, workflow: savedWorkflow,
@ -242,9 +242,9 @@ test('DELETE /users/:id with transferId should perform transfer', async () => {
nodesAccess: [], nodesAccess: [],
}); });
const savedCredential = await Db.collections.Credentials!.save(newCredential); const savedCredential = await Db.collections.Credentials.save(newCredential);
await Db.collections.SharedCredentials!.save({ await Db.collections.SharedCredentials.save({
role: credentialOwnerRole, role: credentialOwnerRole,
user: userToDelete, user: userToDelete,
credentials: savedCredential, credentials: savedCredential,
@ -256,17 +256,17 @@ test('DELETE /users/:id with transferId should perform transfer', async () => {
expect(response.statusCode).toBe(200); expect(response.statusCode).toBe(200);
const sharedWorkflow = await Db.collections.SharedWorkflow!.findOneOrFail({ const sharedWorkflow = await Db.collections.SharedWorkflow.findOneOrFail({
relations: ['user'], relations: ['user'],
where: { user: owner }, where: { user: owner },
}); });
const sharedCredential = await Db.collections.SharedCredentials!.findOneOrFail({ const sharedCredential = await Db.collections.SharedCredentials.findOneOrFail({
relations: ['user'], relations: ['user'],
where: { user: owner }, where: { user: owner },
}); });
const deletedUser = await Db.collections.User!.findOne(userToDelete); const deletedUser = await Db.collections.User.findOne(userToDelete);
expect(sharedWorkflow.user.id).toBe(owner.id); expect(sharedWorkflow.user.id).toBe(owner.id);
expect(sharedCredential.user.id).toBe(owner.id); expect(sharedCredential.user.id).toBe(owner.id);
@ -317,7 +317,7 @@ test('GET /resolve-signup-token should fail with invalid inputs', async () => {
.query({ inviteeId }); .query({ inviteeId });
// cause inconsistent DB state // cause inconsistent DB state
await Db.collections.User!.update(owner.id, { email: '' }); await Db.collections.User.update(owner.id, { email: '' });
const fifth = await authOwnerAgent const fifth = await authOwnerAgent
.get('/resolve-signup-token') .get('/resolve-signup-token')
.query({ inviterId: owner.id }) .query({ inviterId: owner.id })
@ -369,7 +369,7 @@ test('POST /users/:id should fill out a user shell', async () => {
const authToken = utils.getAuthToken(response); const authToken = utils.getAuthToken(response);
expect(authToken).toBeDefined(); expect(authToken).toBeDefined();
const member = await Db.collections.User!.findOneOrFail(memberShell.id); const member = await Db.collections.User.findOneOrFail(memberShell.id);
expect(member.firstName).toBe(memberData.firstName); expect(member.firstName).toBe(memberData.firstName);
expect(member.lastName).toBe(memberData.lastName); expect(member.lastName).toBe(memberData.lastName);
expect(member.password).not.toBe(memberData.password); expect(member.password).not.toBe(memberData.password);
@ -382,7 +382,7 @@ test('POST /users/:id should fail with invalid inputs', async () => {
const memberShellEmail = randomEmail(); const memberShellEmail = randomEmail();
const memberShell = await Db.collections.User!.save({ const memberShell = await Db.collections.User.save({
email: memberShellEmail, email: memberShellEmail,
globalRole: globalMemberRole, globalRole: globalMemberRole,
}); });
@ -421,7 +421,7 @@ test('POST /users/:id should fail with invalid inputs', async () => {
const response = await authlessAgent.post(`/users/${memberShell.id}`).send(invalidPayload); const response = await authlessAgent.post(`/users/${memberShell.id}`).send(invalidPayload);
expect(response.statusCode).toBe(400); expect(response.statusCode).toBe(400);
const storedUser = await Db.collections.User!.findOneOrFail({ const storedUser = await Db.collections.User.findOneOrFail({
where: { email: memberShellEmail }, where: { email: memberShellEmail },
}); });
expect(storedUser.firstName).toBeNull(); expect(storedUser.firstName).toBeNull();
@ -448,7 +448,7 @@ test('POST /users/:id should fail with already accepted invite', async () => {
expect(response.statusCode).toBe(400); expect(response.statusCode).toBe(400);
const storedMember = await Db.collections.User!.findOneOrFail({ const storedMember = await Db.collections.User.findOneOrFail({
where: { email: member.email }, where: { email: member.email },
}); });
expect(storedMember.firstName).not.toBe(newMemberData.firstName); expect(storedMember.firstName).not.toBe(newMemberData.firstName);
@ -517,7 +517,7 @@ test(
expect(error).toBe('Email could not be sent'); expect(error).toBe('Email could not be sent');
} }
const storedUser = await Db.collections.User!.findOneOrFail(id); const storedUser = await Db.collections.User.findOneOrFail(id);
const { firstName, lastName, personalizationAnswers, password, resetPasswordToken } = const { firstName, lastName, personalizationAnswers, password, resetPasswordToken } =
storedUser; storedUser;
@ -552,7 +552,7 @@ test(
const response = await authOwnerAgent.post('/users').send(invalidPayload); const response = await authOwnerAgent.post('/users').send(invalidPayload);
expect(response.statusCode).toBe(400); expect(response.statusCode).toBe(400);
const users = await Db.collections.User!.find(); const users = await Db.collections.User.find();
expect(users.length).toBe(1); // DB unaffected expect(users.length).toBe(1); // DB unaffected
}), }),
); );
@ -576,7 +576,7 @@ test(
expect(Array.isArray(data)).toBe(true); expect(Array.isArray(data)).toBe(true);
expect(data.length).toBe(0); expect(data.length).toBe(0);
const users = await Db.collections.User!.find(); const users = await Db.collections.User.find();
expect(users.length).toBe(1); expect(users.length).toBe(1);
}, },
SMTP_TEST_TIMEOUT, SMTP_TEST_TIMEOUT,
@ -586,7 +586,7 @@ test(
// TODO: UserManagementMailer is a singleton - cannot reinstantiate with wrong creds // TODO: UserManagementMailer is a singleton - cannot reinstantiate with wrong creds
// test('POST /users should error for wrong SMTP config', async () => { // test('POST /users should error for wrong SMTP config', async () => {
// const owner = await Db.collections.User!.findOneOrFail(); // const owner = await Db.collections.User.findOneOrFail();
// const authOwnerAgent = utils.createAgent(app, { auth: true, user: owner }); // const authOwnerAgent = utils.createAgent(app, { auth: true, user: owner });
// config.set('userManagement.emails.mode', 'smtp'); // config.set('userManagement.emails.mode', 'smtp');

View file

@ -247,11 +247,9 @@
"dist/credentials/SalesforceJwtApi.credentials.js", "dist/credentials/SalesforceJwtApi.credentials.js",
"dist/credentials/SalesforceOAuth2Api.credentials.js", "dist/credentials/SalesforceOAuth2Api.credentials.js",
"dist/credentials/SalesmateApi.credentials.js", "dist/credentials/SalesmateApi.credentials.js",
"dist/credentials/SalesmateApi.credentials.js",
"dist/credentials/SeaTableApi.credentials.js", "dist/credentials/SeaTableApi.credentials.js",
"dist/credentials/SecurityScorecardApi.credentials.js", "dist/credentials/SecurityScorecardApi.credentials.js",
"dist/credentials/SegmentApi.credentials.js", "dist/credentials/SegmentApi.credentials.js",
"dist/credentials/SegmentApi.credentials.js",
"dist/credentials/SendGridApi.credentials.js", "dist/credentials/SendGridApi.credentials.js",
"dist/credentials/SendyApi.credentials.js", "dist/credentials/SendyApi.credentials.js",
"dist/credentials/SentryIoApi.credentials.js", "dist/credentials/SentryIoApi.credentials.js",
@ -262,7 +260,6 @@
"dist/credentials/Sftp.credentials.js", "dist/credentials/Sftp.credentials.js",
"dist/credentials/ShopifyApi.credentials.js", "dist/credentials/ShopifyApi.credentials.js",
"dist/credentials/Signl4Api.credentials.js", "dist/credentials/Signl4Api.credentials.js",
"dist/credentials/Signl4Api.credentials.js",
"dist/credentials/SlackApi.credentials.js", "dist/credentials/SlackApi.credentials.js",
"dist/credentials/SlackOAuth2Api.credentials.js", "dist/credentials/SlackOAuth2Api.credentials.js",
"dist/credentials/Sms77Api.credentials.js", "dist/credentials/Sms77Api.credentials.js",