From 3b757132c80ec00faad33689979aedf605f57c39 Mon Sep 17 00:00:00 2001 From: Marcin Piela Date: Fri, 10 May 2024 15:42:26 +0200 Subject: [PATCH] [EXD-24] Added whitelisting of user email domains --- .env.example | 10 ++++++---- src/auth/auth.service.ts | 16 ++++++++++++++-- 2 files changed, 20 insertions(+), 6 deletions(-) diff --git a/.env.example b/.env.example index 330aba4..c30c192 100644 --- a/.env.example +++ b/.env.example @@ -6,16 +6,18 @@ FRONT_APP_REDIRECT_URL='http://localhost:5173' CORS_ORIGIN='*' -#DB +# DB DATABASE_PORT=5432 DATABASE_HOST=localhost DATABASE_USERNAME=... DATABASE_PASSWORD=... DATABASE_NAME=... -# Disable authentiacation giard for all endpoints - useful for local dev +# Disable authentication guard for all endpoints - useful for local dev AUTH_GUARD_DISABLE=false -#Default user id, should be set when AUTH_GUARD_DISABLE is set to true +# Default user id, should be set when AUTH_GUARD_DISABLE is set to true AUTH_DEFAULT_USER_ID='' +# Only allow users from this list to create accounts +AUTH_EMAIL_DOMAIN_WHITELIST=silksh.pl,silksoftwarehouse.com -DEFAULT_USER_ROLE='USER' \ No newline at end of file +DEFAULT_USER_ROLE='USER' diff --git a/src/auth/auth.service.ts b/src/auth/auth.service.ts index 1fa52be..d294c10 100644 --- a/src/auth/auth.service.ts +++ b/src/auth/auth.service.ts @@ -3,7 +3,7 @@ import { InjectRepository } from '@nestjs/typeorm'; import { Repository } from 'typeorm'; import { UserEntity } from '../user/entity/user.entity'; import { UserRoleEntity } from '../user/entity/user-role.entity'; -import * as process from 'node:process'; +import { ConfigService } from '@nestjs/config'; @Injectable() export class AuthService { @@ -12,6 +12,7 @@ export class AuthService { private readonly userRepo: Repository, @InjectRepository(UserRoleEntity) private readonly userRoleRepo: Repository, + private readonly configService: ConfigService, ) {} async validateUser(email: string, displayName: string) { @@ -24,9 +25,20 @@ export class AuthService { return user; } + // Create new user only if from whitelisted domain + const emailDomain = email.split('@').pop(); + if ( + !this.configService + .get('AUTH_EMAIL_DOMAIN_WHITELIST') + .split(',') + .includes(emailDomain) + ) { + return null; + } + //In case of DEFAULT_USER_ROLE is not set, user will be registered without any role const roles = await this.userRoleRepo.find({ - where: { name: process.env.DEFAULT_USER_ROLE }, + where: { name: this.configService.get('DEFAULT_USER_ROLE') }, }); //Register anyone on their first sign-in