Skip to content

Commit

Permalink
refactor(core): Switch over all user-management routes to use decorat…
Browse files Browse the repository at this point in the history
…ors (#5115)
  • Loading branch information
netroy authored Jan 27, 2023
1 parent 08a90d7 commit 845f0f9
Show file tree
Hide file tree
Showing 71 changed files with 1,803 additions and 1,667 deletions.
2 changes: 1 addition & 1 deletion cypress/e2e/4-node-creator.cy.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { NodeCreator } from '../pages/features/node-creator';
import { INodeTypeDescription } from '../../packages/workflow';
import { INodeTypeDescription } from 'n8n-workflow';
import CustomNodeFixture from '../fixtures/Custom_node.json';
import { DEFAULT_USER_EMAIL, DEFAULT_USER_PASSWORD } from '../constants';
import { randFirstName, randLastName } from '@ngneat/falso';
Expand Down
2 changes: 1 addition & 1 deletion cypress/pages/features/node-creator.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { BasePage } from '../base';
import { INodeTypeDescription } from '../../packages/workflow';
import { INodeTypeDescription } from 'n8n-workflow';

export class NodeCreator extends BasePage {
url = '/workflow/new';
Expand Down
2 changes: 1 addition & 1 deletion packages/cli/src/AbstractServer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ import {
sendSuccessResponse,
ServiceUnavailableError,
} from '@/ResponseHelper';
import { corsMiddleware } from '@/middlewares/cors';
import { corsMiddleware } from '@/middlewares';
import * as TestWebhooks from '@/TestWebhooks';
import { WaitingWebhooks } from '@/WaitingWebhooks';
import { WEBHOOK_METHODS } from '@/WebhookHelpers';
Expand Down
43 changes: 41 additions & 2 deletions packages/cli/src/Interfaces.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
/* eslint-disable @typescript-eslint/naming-convention */
import type { Application } from 'express';
import type {
ExecutionError,
ICredentialDataDecryptedObject,
Expand All @@ -21,9 +22,11 @@ import type {
WorkflowExecuteMode,
} from 'n8n-workflow';

import { WorkflowExecute } from 'n8n-core';
import type { ActiveWorkflowRunner } from '@/ActiveWorkflowRunner';

import PCancelable from 'p-cancelable';
import type { WorkflowExecute } from 'n8n-core';

import type PCancelable from 'p-cancelable';
import type { FindOperator, Repository } from 'typeorm';

import type { ChildProcess } from 'child_process';
Expand Down Expand Up @@ -365,6 +368,7 @@ export interface IInternalHooksClass {
user: User;
target_user_id: string[];
public_api: boolean;
email_sent: boolean;
}): Promise<void>;
onUserReinvite(userReinviteData: {
user: User;
Expand All @@ -378,6 +382,7 @@ export interface IInternalHooksClass {
userTransactionalEmailData: {
user_id: string;
message_type: 'Reset password' | 'New user invite' | 'Resend invite';
public_api: boolean;
},
user?: User,
): Promise<void>;
Expand Down Expand Up @@ -841,3 +846,37 @@ export interface ILicenseReadResponse {
export interface ILicensePostResponse extends ILicenseReadResponse {
managementToken: string;
}

export interface JwtToken {
token: string;
expiresIn: number;
}

export interface JwtPayload {
id: string;
email: string | null;
password: string | null;
}

export interface PublicUser {
id: string;
email?: string;
firstName?: string;
lastName?: string;
personalizationAnswers?: IPersonalizationSurveyAnswers | null;
password?: string;
passwordResetToken?: string;
createdAt: Date;
isPending: boolean;
globalRole?: Role;
signInType: AuthProviderType;
disabled: boolean;
inviteAcceptUrl?: string;
}

export interface N8nApp {
app: Application;
restEndpoint: string;
externalHooks: IExternalHooksClass;
activeWorkflowRunner: ActiveWorkflowRunner;
}
2 changes: 1 addition & 1 deletion packages/cli/src/Ldap/helpers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import * as Db from '@/Db';
import config from '@/config';
import type { Role } from '@db/entities/Role';
import { User } from '@db/entities/User';
import { AuthIdentity } from '@/databases/entities/AuthIdentity';
import { AuthIdentity } from '@db/entities/AuthIdentity';
import type { AuthProviderSyncHistory } from '@db/entities/AuthProviderSyncHistory';
import { isUserManagementEnabled } from '@/UserManagement/UserManagementHelper';
import { LdapManager } from './LdapManager.ee';
Expand Down
48 changes: 40 additions & 8 deletions packages/cli/src/Server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -63,9 +63,6 @@ import {
WorkflowExecuteMode,
INodeTypes,
ICredentialTypes,
INode,
IWorkflowBase,
IRun,
} from 'n8n-workflow';

import basicAuth from 'basic-auth';
Expand Down Expand Up @@ -103,8 +100,15 @@ import type {
OAuthRequest,
WorkflowRequest,
} from '@/requests';
import { userManagementRouter } from '@/UserManagement';
import { resolveJwt } from '@/UserManagement/auth/jwt';
import { registerController } from '@/decorators';
import {
AuthController,
MeController,
OwnerController,
PasswordResetController,
UsersController,
} from '@/controllers';
import { resolveJwt } from '@/auth/jwt';

import { executionsController } from '@/executions/executions.controller';
import { nodeTypesController } from '@/api/nodeTypes.api';
Expand All @@ -118,6 +122,7 @@ import {
isUserManagementEnabled,
whereClause,
} from '@/UserManagement/UserManagementHelper';
import { getInstance as getMailerInstance } from '@/UserManagement/email';
import * as Db from '@/Db';
import {
DatabaseType,
Expand Down Expand Up @@ -151,7 +156,7 @@ import { eventBusRouter } from '@/eventbus/eventBusRoutes';
import { isLogStreamingEnabled } from '@/eventbus/MessageEventBus/MessageEventBusHelper';
import { getLicense } from '@/License';
import { licenseController } from './license/license.controller';
import { corsMiddleware } from './middlewares/cors';
import { corsMiddleware, setupAuthMiddlewares } from './middlewares';
import { initEvents } from './events';
import { ldapController } from './Ldap/routes/ldap.controller.ee';
import { getLdapLoginLabel, isLdapEnabled, isLdapLoginEnabled } from './Ldap/helpers';
Expand Down Expand Up @@ -336,6 +341,33 @@ class Server extends AbstractServer {
}
}

private registerControllers(ignoredEndpoints: Readonly<string[]>) {
const { app, externalHooks, activeWorkflowRunner } = this;
const repositories = Db.collections;
setupAuthMiddlewares(app, ignoredEndpoints, this.restEndpoint, repositories.User);

const logger = LoggerProxy;
const internalHooks = InternalHooksManager.getInstance();
const mailer = getMailerInstance();

const controllers = [
new AuthController({ config, internalHooks, repositories, logger }),
new OwnerController({ config, internalHooks, repositories, logger }),
new MeController({ externalHooks, internalHooks, repositories, logger }),
new PasswordResetController({ config, externalHooks, internalHooks, repositories, logger }),
new UsersController({
config,
mailer,
externalHooks,
internalHooks,
repositories,
activeWorkflowRunner,
logger,
}),
];
controllers.forEach((controller) => registerController(app, config, controller));
}

async configure(): Promise<void> {
configureMetrics(this.app);

Expand All @@ -354,7 +386,7 @@ class Server extends AbstractServer {
const publicApiEndpoint = config.getEnv('publicApi.path');
const excludeEndpoints = config.getEnv('security.excludeEndpoints');

const ignoredEndpoints = [
const ignoredEndpoints: Readonly<string[]> = [
'assets',
'healthz',
'metrics',
Expand Down Expand Up @@ -587,7 +619,7 @@ class Server extends AbstractServer {
// ----------------------------------------
// User Management
// ----------------------------------------
await userManagementRouter.addRoutes.apply(this, [ignoredEndpoints, this.restEndpoint]);
this.registerControllers(ignoredEndpoints);

this.app.use(`/${this.restEndpoint}/credentials`, credentialsController);

Expand Down
39 changes: 0 additions & 39 deletions packages/cli/src/UserManagement/Interfaces.ts

This file was deleted.

7 changes: 3 additions & 4 deletions packages/cli/src/UserManagement/UserManagementHelper.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,14 +6,13 @@ import { compare, genSaltSync, hash } from 'bcryptjs';

import * as Db from '@/Db';
import * as ResponseHelper from '@/ResponseHelper';
import { PublicUser } from './Interfaces';
import type { PublicUser, WhereClause } from '@/Interfaces';
import { MAX_PASSWORD_LENGTH, MIN_PASSWORD_LENGTH, User } from '@db/entities/User';
import { Role } from '@db/entities/Role';
import { AuthenticatedRequest } from '@/requests';
import config from '@/config';
import { getWebhookBaseUrl } from '../WebhookHelpers';
import { getWebhookBaseUrl } from '@/WebhookHelpers';
import { getLicense } from '@/License';
import { WhereClause } from '@/Interfaces';
import { RoleService } from '@/role/role.service';

export async function getWorkflowOwner(workflowId: string): Promise<User> {
Expand Down Expand Up @@ -177,7 +176,7 @@ export async function getUserById(userId: string): Promise<User> {
/**
* Check if a URL contains an auth-excluded endpoint.
*/
export function isAuthExcluded(url: string, ignoredEndpoints: string[]): boolean {
export function isAuthExcluded(url: string, ignoredEndpoints: Readonly<string[]>): boolean {
return !!ignoredEndpoints
.filter(Boolean) // skip empty paths
.find((ignoredEndpoint) => url.startsWith(`/${ignoredEndpoint}`));
Expand Down
3 changes: 0 additions & 3 deletions packages/cli/src/UserManagement/index.ts

This file was deleted.

55 changes: 0 additions & 55 deletions packages/cli/src/UserManagement/middlewares/auth.ts

This file was deleted.

Loading

0 comments on commit 845f0f9

Please sign in to comment.