refactor(core): Remove all legacy auth middleware code (no-changelog) (#8755)

This commit is contained in:
कारतोफ्फेलस्क्रिप्ट™
2024-02-28 13:12:28 +01:00
committed by GitHub
parent 2e84684f04
commit 56c8791aff
37 changed files with 679 additions and 864 deletions

View File

@@ -1,12 +1,12 @@
import validator from 'validator';
import { AuthService } from '@/auth/auth.service';
import { Authorized, Get, Post, RestController } from '@/decorators';
import { issueCookie, resolveJwt } from '@/auth/jwt';
import { AUTH_COOKIE_NAME, RESPONSE_ERROR_MESSAGES } from '@/constants';
import { RESPONSE_ERROR_MESSAGES } from '@/constants';
import { Request, Response } from 'express';
import type { User } from '@db/entities/User';
import { LoginRequest, UserRequest } from '@/requests';
import { AuthenticatedRequest, LoginRequest, UserRequest } from '@/requests';
import type { PublicUser } from '@/Interfaces';
import config from '@/config';
import { handleEmailLogin, handleLdapLogin } from '@/auth';
import { PostHogClient } from '@/posthog';
import {
@@ -20,7 +20,6 @@ import { UserService } from '@/services/user.service';
import { MfaService } from '@/Mfa/mfa.service';
import { Logger } from '@/Logger';
import { AuthError } from '@/errors/response-errors/auth.error';
import { InternalServerError } from '@/errors/response-errors/internal-server.error';
import { BadRequestError } from '@/errors/response-errors/bad-request.error';
import { UnauthorizedError } from '@/errors/response-errors/unauthorized.error';
import { ApplicationError } from 'n8n-workflow';
@@ -31,6 +30,7 @@ export class AuthController {
constructor(
private readonly logger: Logger,
private readonly internalHooks: InternalHooks,
private readonly authService: AuthService,
private readonly mfaService: MfaService,
private readonly userService: UserService,
private readonly license: License,
@@ -96,7 +96,7 @@ export class AuthController {
}
}
await issueCookie(res, user);
this.authService.issueCookie(res, user);
void this.internalHooks.onUserLoginSuccess({
user,
authenticationMethod: usedAuthenticationMethod,
@@ -112,45 +112,14 @@ export class AuthController {
throw new AuthError('Wrong username or password. Do you have caps lock on?');
}
/**
* Manually check the `n8n-auth` cookie.
*/
/** Check if the user is already logged in */
@Authorized()
@Get('/login')
async currentUser(req: Request, res: Response): Promise<PublicUser> {
// Manually check the existing cookie.
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
const cookieContents = req.cookies?.[AUTH_COOKIE_NAME] as string | undefined;
let user: User;
if (cookieContents) {
// If logged in, return user
try {
user = await resolveJwt(cookieContents);
return await this.userService.toPublic(user, { posthog: this.postHog, withScopes: true });
} catch (error) {
res.clearCookie(AUTH_COOKIE_NAME);
}
}
if (config.getEnv('userManagement.isInstanceOwnerSetUp')) {
throw new AuthError('Not logged in');
}
try {
user = await this.userRepository.findOneOrFail({ where: {} });
} catch (error) {
throw new InternalServerError(
'No users found in database - did you wipe the users table? Create at least one user.',
);
}
if (user.email || user.password) {
throw new InternalServerError('Invalid database state - user has password set.');
}
await issueCookie(res, user);
return await this.userService.toPublic(user, { posthog: this.postHog, withScopes: true });
async currentUser(req: AuthenticatedRequest): Promise<PublicUser> {
return await this.userService.toPublic(req.user, {
posthog: this.postHog,
withScopes: true,
});
}
/**
@@ -228,8 +197,8 @@ export class AuthController {
*/
@Authorized()
@Post('/logout')
logout(req: Request, res: Response) {
res.clearCookie(AUTH_COOKIE_NAME);
logout(_: Request, res: Response) {
this.authService.clearCookie(res);
return { loggedOut: true };
}

View File

@@ -1,9 +1,9 @@
import { Response } from 'express';
import validator from 'validator';
import { AuthService } from '@/auth/auth.service';
import config from '@/config';
import { Authorized, NoAuthRequired, Post, RequireGlobalScope, RestController } from '@/decorators';
import { issueCookie } from '@/auth/jwt';
import { RESPONSE_ERROR_MESSAGES } from '@/constants';
import { UserRequest } from '@/requests';
import { License } from '@/License';
@@ -26,6 +26,7 @@ export class InvitationController {
private readonly logger: Logger,
private readonly internalHooks: InternalHooks,
private readonly externalHooks: ExternalHooks,
private readonly authService: AuthService,
private readonly userService: UserService,
private readonly license: License,
private readonly passwordUtility: PasswordUtility,
@@ -165,7 +166,7 @@ export class InvitationController {
const updatedUser = await this.userRepository.save(invitee, { transaction: false });
await issueCookie(res, updatedUser);
this.authService.issueCookie(res, updatedUser);
void this.internalHooks.onUserSignup(updatedUser, {
user_type: 'email',

View File

@@ -2,10 +2,11 @@ import validator from 'validator';
import { plainToInstance } from 'class-transformer';
import { Response } from 'express';
import { randomBytes } from 'crypto';
import { AuthService } from '@/auth/auth.service';
import { Authorized, Delete, Get, Patch, Post, RestController } from '@/decorators';
import { PasswordUtility } from '@/services/password.utility';
import { validateEntity } from '@/GenericHelpers';
import { issueCookie } from '@/auth/jwt';
import type { User } from '@db/entities/User';
import {
AuthenticatedRequest,
@@ -14,7 +15,7 @@ import {
UserUpdatePayload,
} from '@/requests';
import type { PublicUser } from '@/Interfaces';
import { isSamlLicensedAndEnabled } from '../sso/saml/samlHelpers';
import { isSamlLicensedAndEnabled } from '@/sso/saml/samlHelpers';
import { UserService } from '@/services/user.service';
import { Logger } from '@/Logger';
import { ExternalHooks } from '@/ExternalHooks';
@@ -29,6 +30,7 @@ export class MeController {
private readonly logger: Logger,
private readonly externalHooks: ExternalHooks,
private readonly internalHooks: InternalHooks,
private readonly authService: AuthService,
private readonly userService: UserService,
private readonly passwordUtility: PasswordUtility,
private readonly userRepository: UserRepository,
@@ -84,7 +86,7 @@ export class MeController {
this.logger.info('User updated successfully', { userId });
await issueCookie(res, user);
this.authService.issueCookie(res, user);
const updatedKeys = Object.keys(payload);
void this.internalHooks.onUserUpdate({
@@ -137,7 +139,7 @@ export class MeController {
const updatedUser = await this.userRepository.save(user, { transaction: false });
this.logger.info('Password updated successfully', { userId: user.id });
await issueCookie(res, updatedUser);
this.authService.issueCookie(res, updatedUser);
void this.internalHooks.onUserUpdate({
user: updatedUser,

View File

@@ -1,19 +1,19 @@
import validator from 'validator';
import { Response } from 'express';
import { AuthService } from '@/auth/auth.service';
import config from '@/config';
import { validateEntity } from '@/GenericHelpers';
import { Authorized, Post, RestController } from '@/decorators';
import { PasswordUtility } from '@/services/password.utility';
import { issueCookie } from '@/auth/jwt';
import { OwnerRequest } from '@/requests';
import { SettingsRepository } from '@db/repositories/settings.repository';
import { UserRepository } from '@db/repositories/user.repository';
import { PostHogClient } from '@/posthog';
import { UserService } from '@/services/user.service';
import { Logger } from '@/Logger';
import { BadRequestError } from '@/errors/response-errors/bad-request.error';
import { InternalHooks } from '@/InternalHooks';
import { UserRepository } from '@/databases/repositories/user.repository';
@Authorized('global:owner')
@RestController('/owner')
@@ -22,6 +22,7 @@ export class OwnerController {
private readonly logger: Logger,
private readonly internalHooks: InternalHooks,
private readonly settingsRepository: SettingsRepository,
private readonly authService: AuthService,
private readonly userService: UserService,
private readonly passwordUtility: PasswordUtility,
private readonly postHog: PostHogClient,
@@ -89,7 +90,7 @@ export class OwnerController {
this.logger.debug('Setting isInstanceOwnerSetUp updated successfully', { userId });
await issueCookie(res, owner);
this.authService.issueCookie(res, owner);
void this.internalHooks.onInstanceOwnerSetup({ user_id: userId });

View File

@@ -2,11 +2,11 @@ import { Response } from 'express';
import { rateLimit } from 'express-rate-limit';
import validator from 'validator';
import { AuthService } from '@/auth/auth.service';
import { Get, Post, RestController } from '@/decorators';
import { PasswordUtility } from '@/services/password.utility';
import { UserManagementMailer } from '@/UserManagement/email';
import { PasswordResetRequest } from '@/requests';
import { issueCookie } from '@/auth/jwt';
import { isSamlCurrentAuthenticationMethod } from '@/sso/ssoHelpers';
import { UserService } from '@/services/user.service';
import { License } from '@/License';
@@ -36,6 +36,7 @@ export class PasswordResetController {
private readonly externalHooks: ExternalHooks,
private readonly internalHooks: InternalHooks,
private readonly mailer: UserManagementMailer,
private readonly authService: AuthService,
private readonly userService: UserService,
private readonly mfaService: MfaService,
private readonly urlService: UrlService,
@@ -114,7 +115,7 @@ export class PasswordResetController {
throw new UnprocessableRequestError('forgotPassword.ldapUserPasswordResetUnavailable');
}
const url = this.userService.generatePasswordResetUrl(user);
const url = this.authService.generatePasswordResetUrl(user);
const { id, firstName, lastName } = user;
try {
@@ -163,7 +164,7 @@ export class PasswordResetController {
throw new BadRequestError('');
}
const user = await this.userService.resolvePasswordResetToken(token);
const user = await this.authService.resolvePasswordResetToken(token);
if (!user) throw new NotFoundError('');
if (!user?.isOwner && !this.license.isWithinUsersLimit()) {
@@ -197,7 +198,7 @@ export class PasswordResetController {
const validPassword = this.passwordUtility.validate(password);
const user = await this.userService.resolvePasswordResetToken(token);
const user = await this.authService.resolvePasswordResetToken(token);
if (!user) throw new NotFoundError('');
if (user.mfaEnabled) {
@@ -216,7 +217,7 @@ export class PasswordResetController {
this.logger.info('User password updated successfully', { userId: user.id });
await issueCookie(res, user);
this.authService.issueCookie(res, user);
void this.internalHooks.onUserUpdate({
user,

View File

@@ -1,3 +1,6 @@
import { plainToInstance } from 'class-transformer';
import { AuthService } from '@/auth/auth.service';
import { User } from '@db/entities/User';
import { SharedCredentials } from '@db/entities/SharedCredentials';
import { SharedWorkflow } from '@db/entities/SharedWorkflow';
@@ -22,7 +25,6 @@ import { AuthIdentity } from '@db/entities/AuthIdentity';
import { SharedCredentialsRepository } from '@db/repositories/sharedCredentials.repository';
import { SharedWorkflowRepository } from '@db/repositories/sharedWorkflow.repository';
import { UserRepository } from '@db/repositories/user.repository';
import { plainToInstance } from 'class-transformer';
import { UserService } from '@/services/user.service';
import { listQueryMiddleware } from '@/middlewares';
import { Logger } from '@/Logger';
@@ -44,6 +46,7 @@ export class UsersController {
private readonly sharedWorkflowRepository: SharedWorkflowRepository,
private readonly userRepository: UserRepository,
private readonly activeWorkflowRunner: ActiveWorkflowRunner,
private readonly authService: AuthService,
private readonly userService: UserService,
) {}
@@ -116,7 +119,7 @@ export class UsersController {
throw new NotFoundError('User not found');
}
const link = this.userService.generatePasswordResetUrl(user);
const link = this.authService.generatePasswordResetUrl(user);
return { link };
}