From cd4ee84ec31e52639f34d2121d757b3dc8618ff8 Mon Sep 17 00:00:00 2001 From: Philip Molares Date: Sat, 4 Sep 2021 18:31:01 +0200 Subject: [PATCH] feat: add LoginEnabledGuard and RegistrationEnabledGuard These guards check if the login or registration are enabled in the config. If so the guarded method is executed, if not the client will get the HTTP Error 400 Forbidden as an answer Signed-off-by: Philip Molares --- src/api/utils/login-enabled.guard.ts | 33 +++++++++++++++++++++ src/api/utils/registration-enabled.guard.ts | 33 +++++++++++++++++++++ 2 files changed, 66 insertions(+) create mode 100644 src/api/utils/login-enabled.guard.ts create mode 100644 src/api/utils/registration-enabled.guard.ts diff --git a/src/api/utils/login-enabled.guard.ts b/src/api/utils/login-enabled.guard.ts new file mode 100644 index 000000000..fe1b98eb2 --- /dev/null +++ b/src/api/utils/login-enabled.guard.ts @@ -0,0 +1,33 @@ +/* + * SPDX-FileCopyrightText: 2021 The HedgeDoc developers (see AUTHORS file) + * + * SPDX-License-Identifier: AGPL-3.0-only + */ +import { + BadRequestException, + CanActivate, + Inject, + Injectable, +} from '@nestjs/common'; + +import authConfiguration, { AuthConfig } from '../../config/auth.config'; +import { ConsoleLoggerService } from '../../logger/console-logger.service'; + +@Injectable() +export class LoginEnabledGuard implements CanActivate { + constructor( + private readonly logger: ConsoleLoggerService, + @Inject(authConfiguration.KEY) + private authConfig: AuthConfig, + ) { + this.logger.setContext(LoginEnabledGuard.name); + } + + canActivate(): boolean { + if (!this.authConfig.local.enableLogin) { + this.logger.debug('Local auth is disabled.', 'canActivate'); + throw new BadRequestException('Local auth is disabled.'); + } + return true; + } +} diff --git a/src/api/utils/registration-enabled.guard.ts b/src/api/utils/registration-enabled.guard.ts new file mode 100644 index 000000000..6289f857f --- /dev/null +++ b/src/api/utils/registration-enabled.guard.ts @@ -0,0 +1,33 @@ +/* + * SPDX-FileCopyrightText: 2021 The HedgeDoc developers (see AUTHORS file) + * + * SPDX-License-Identifier: AGPL-3.0-only + */ +import { + BadRequestException, + CanActivate, + Inject, + Injectable, +} from '@nestjs/common'; + +import authConfiguration, { AuthConfig } from '../../config/auth.config'; +import { ConsoleLoggerService } from '../../logger/console-logger.service'; + +@Injectable() +export class RegistrationEnabledGuard implements CanActivate { + constructor( + private readonly logger: ConsoleLoggerService, + @Inject(authConfiguration.KEY) + private authConfig: AuthConfig, + ) { + this.logger.setContext(RegistrationEnabledGuard.name); + } + + canActivate(): boolean { + if (!this.authConfig.local.enableRegister) { + this.logger.debug('User registration is disabled.', 'canActivate'); + throw new BadRequestException('User registration is disabled.'); + } + return true; + } +}