Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Make google auth optional on server side #508

Merged
merged 3 commits into from
Jul 4, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 1 addition & 5 deletions server/.env.example
Original file line number Diff line number Diff line change
@@ -1,6 +1,3 @@
AUTH_GOOGLE_CLIENT_ID=REPLACE_ME
AUTH_GOOGLE_CLIENT_SECRET=REPLACE_ME
AUTH_GOOGLE_CALLBACK_URL=http://localhost:3000/auth/google/redirect
ACCESS_TOKEN_SECRET=secret_jwt
ACCESS_TOKEN_EXPIRES_IN=5m
LOGIN_TOKEN_SECRET=secret_login_token
Expand All @@ -10,5 +7,4 @@ REFRESH_TOKEN_EXPIRES_IN=90d
PG_DATABASE_URL=postgres://postgres:postgrespassword@postgres:5432/default?connection_limit=1
FRONT_AUTH_CALLBACK_URL=http://localhost:3001/auth/callback
STORAGE_TYPE=local
STORAGE_REGION=eu-west-1
STORAGE_LOCATION=.local-storage
STORAGE_LOCAL_PATH=.local-storage
5 changes: 3 additions & 2 deletions server/src/core/auth/controllers/google-auth.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import { Response } from 'express';
import { GoogleRequest } from '../strategies/google.auth.strategy';
import { UserService } from '../../user/user.service';
import { TokenService } from '../services/token.service';
import { GoogleProviderEnabledGuard } from '../guards/google-provider-enabled.guard';

@Controller('auth/google')
export class GoogleAuthController {
Expand All @@ -20,14 +21,14 @@ export class GoogleAuthController {
) {}

@Get()
@UseGuards(AuthGuard('google'))
@UseGuards(GoogleProviderEnabledGuard, AuthGuard('google'))
async googleAuth() {
// As this method is protected by Google Auth guard, it will trigger Google SSO flow
return;
}

@Get('redirect')
@UseGuards(AuthGuard('google'))
@UseGuards(GoogleProviderEnabledGuard, AuthGuard('google'))
async googleAuthRedirect(@Req() req: GoogleRequest, @Res() res: Response) {
const { firstName, lastName, email } = req.user;

Expand Down
14 changes: 14 additions & 0 deletions server/src/core/auth/guards/google-provider-enabled.guard.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import { Injectable, CanActivate, HttpException } from '@nestjs/common';
import { Observable } from 'rxjs';
import { EnvironmentService } from 'src/integrations/environment/environment.service';

@Injectable()
export class GoogleProviderEnabledGuard implements CanActivate {
constructor(private readonly environmentService: EnvironmentService) {}
canActivate(): boolean | Promise<boolean> | Observable<boolean> {
if (!this.environmentService.getAuthGoogleEnabled()) {
throw new HttpException('Google auth is not enabled', 404);
}
return true;
}
}
13 changes: 10 additions & 3 deletions server/src/core/auth/strategies/google.auth.strategy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,10 +16,17 @@ export type GoogleRequest = Request & {
@Injectable()
export class GoogleStrategy extends PassportStrategy(Strategy, 'google') {
constructor(environmentService: EnvironmentService) {
const isAuthGoogleEnabled = environmentService.getAuthGoogleEnabled();
super({
clientID: environmentService.getAuthGoogleClientId(),
clientSecret: environmentService.getAuthGoogleClientSecret(),
callbackURL: environmentService.getAuthGoogleCallbackUrl(),
clientID: isAuthGoogleEnabled
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@magrinj @emilienchvt not very proud of these disabled but super() has to be called.
Another solution would be to not register the strategy using DynamicModules

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not extremely better, but disabledClientId, disabledClientSecret and disabledCallbackUrl might be less generic

? environmentService.getAuthGoogleClientId()
: 'disabled',
clientSecret: isAuthGoogleEnabled
? environmentService.getAuthGoogleClientSecret()
: 'disabled',
callbackURL: isAuthGoogleEnabled
? environmentService.getAuthGoogleCallbackUrl()
: 'disabled',
scope: ['email', 'profile'],
});
}
Expand Down
2 changes: 1 addition & 1 deletion server/src/core/file/services/file.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ export class FileService {
}

private async getLocalFileStream(folderPath: string, filename: string) {
const storageLocation = this.environmentService.getStorageLocation();
const storageLocation = this.environmentService.getStorageLocalPath();

const filePath = join(
process.cwd(),
Expand Down
16 changes: 12 additions & 4 deletions server/src/integrations/environment/environment.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,10 @@ export class EnvironmentService {
return this.configService.get<string>('FRONT_AUTH_CALLBACK_URL')!;
}

getAuthGoogleEnabled(): boolean | undefined {
return this.configService.get<boolean>('AUTH_GOOGLE_ENABLED');
}

getAuthGoogleClientId(): string | undefined {
return this.configService.get<string>('AUTH_GOOGLE_CLIENT_ID');
}
Expand All @@ -56,11 +60,15 @@ export class EnvironmentService {
return this.configService.get<StorageType>('STORAGE_TYPE');
}

getStorageRegion(): AwsRegion | undefined {
return this.configService.get<AwsRegion>('STORAGE_REGION');
getStorageS3Region(): AwsRegion | undefined {
return this.configService.get<AwsRegion>('STORAGE_S3_REGION');
}

getStorageS3Name(): string | undefined {
return this.configService.get<AwsRegion>('STORAGE_S3_NAME');
}

getStorageLocation(): string {
return this.configService.get<string>('STORAGE_LOCATION')!;
getStorageLocalPath(): string | undefined {
return this.configService.get<string>('STORAGE_LOCAL_PATH')!;
}
}
40 changes: 32 additions & 8 deletions server/src/integrations/environment/environment.validation.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
import { plainToClass } from 'class-transformer';
import { plainToClass, Transform } from 'class-transformer';
import {
IsEnum,
IsOptional,
IsString,
IsUrl,
ValidateIf,
validateSync,
IsBoolean,
} from 'class-validator';
import { assert } from 'src/utils/assert';
import { IsDuration } from './decorators/is-duration.decorator';
Expand Down Expand Up @@ -38,34 +39,44 @@ export class EnvironmentVariables {
@IsUrl({ require_tld: false })
FRONT_AUTH_CALLBACK_URL: string;

@IsString()
@Transform(({ value }) => envValueToBoolean(value))
@IsOptional()
@IsBoolean()
AUTH_GOOGLE_ENABLED?: boolean;

@IsString()
@ValidateIf((env) => env.AUTH_GOOGLE_ENABLED === true)
AUTH_GOOGLE_CLIENT_ID?: string;

@IsString()
@IsOptional()
@ValidateIf((env) => env.AUTH_GOOGLE_ENABLED === true)
AUTH_GOOGLE_CLIENT_SECRET?: string;

@IsUrl({ require_tld: false })
@IsOptional()
@ValidateIf((env) => env.AUTH_GOOGLE_ENABLED === true)
AUTH_GOOGLE_CALLBACK_URL?: string;

// Storage
@IsEnum(StorageType)
@IsOptional()
STORAGE_TYPE?: StorageType;

@ValidateIf((_, value) => value === StorageType.S3)
@ValidateIf((env) => env.STORAGE_TYPE === StorageType.S3)
@IsAWSRegion()
STORAGE_REGION?: AwsRegion;
STORAGE_S3_REGION?: AwsRegion;

@ValidateIf((env) => env.STORAGE_TYPE === StorageType.S3)
@IsString()
STORAGE_S3_NAME?: string;

@IsString()
STORAGE_LOCATION: string;
@ValidateIf((env) => env.STORAGE_TYPE === StorageType.Local)
STORAGE_LOCAL_PATH?: string;
}

export function validate(config: Record<string, unknown>) {
const validatedConfig = plainToClass(EnvironmentVariables, config, {
enableImplicitConversion: true,
enableImplicitConversion: false,
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I have disabled this because it was casting ENV_VARIABLE=false to TRUE...

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

see my other comment below

Copy link
Contributor

@emilienchvt emilienchvt Jul 4, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Indeed, maybe some ideas here: typestack/class-transformer#550
The workarounds described do not look too different from yours

Copy link
Member Author

@charlesBochet charlesBochet Jul 4, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nice link did not find it

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I prefer to use Transform instead of disabling this, because it's going to stop inferring types on all other env variables

});

const errors = validateSync(validatedConfig, {
Expand All @@ -75,3 +86,16 @@ export function validate(config: Record<string, unknown>) {

return validatedConfig;
}

const envValueToBoolean = (value: any) => {
if (typeof value === 'boolean') {
return value;
}
if (['true', 'on', 'yes', '1'].includes(value.toLowerCase())) {
return true;
}
if (['false', 'off', 'no', '0'].includes(value.toLowerCase())) {
return false;
}
return undefined;
};
20 changes: 6 additions & 14 deletions server/src/integrations/integrations.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ import { LocalStorageModule } from './local-storage/local-storage.module';
import { LocalStorageModuleOptions } from './local-storage/interfaces';
import { EnvironmentModule } from './environment/environment.module';
import { EnvironmentService } from './environment/environment.service';
import { assert } from 'src/utils/assert';

/**
* S3 Storage Module factory
Expand All @@ -16,23 +15,16 @@ import { assert } from 'src/utils/assert';
const S3StorageModuleFactory = async (
environmentService: EnvironmentService,
): Promise<S3StorageModuleOptions> => {
const fileSystem = environmentService.getStorageType();
const bucketName = environmentService.getStorageLocation();
const region = environmentService.getStorageRegion();

if (fileSystem === 'local') {
return { bucketName };
}

assert(region, 'S3 region is not defined');
const bucketName = environmentService.getStorageS3Name();
const region = environmentService.getStorageS3Region();

return {
bucketName,
bucketName: bucketName ?? '',
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm only moving the problem to here. I believe the S3Module should not be instanciated if S3 is not configured in env variables. I would encapsulated LocalDriver and S3Driver behind one common FileStorage Interface.
To be discussed and treated in another PR!

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should we track this as a new task ?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, I'll discuss it with Jeremy tomorrow and create a task based on discussion!

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Created here: #510 we can discuss it tomorrow

credentials: fromNodeProviderChain({
clientConfig: { region },
}),
forcePathStyle: true,
region,
region: region ?? '',
};
};

Expand All @@ -44,10 +36,10 @@ const S3StorageModuleFactory = async (
const localStorageModuleFactory = async (
environmentService: EnvironmentService,
): Promise<LocalStorageModuleOptions> => {
const folderName = environmentService.getStorageLocation();
const storagePath = environmentService.getStorageLocalPath();

return {
storagePath: process.cwd() + '/' + folderName,
storagePath: process.cwd() + '/' + storagePath,
};
};

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,5 @@ import { S3ClientConfig } from '@aws-sdk/client-s3';

export interface S3StorageModuleOptions extends S3ClientConfig {
bucketName: string;
region: string;
}
8 changes: 6 additions & 2 deletions server/src/integrations/s3-storage/s3-storage.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,9 +23,13 @@ export class S3StorageService {
@Inject(MODULE_OPTIONS_TOKEN)
private readonly options: S3StorageModuleOptions,
) {
const { bucketName, ...s3Options } = options;
const { bucketName, region, ...s3Options } = options;

this.s3Client = new S3(s3Options);
if (!bucketName || !region) {
return;
}

this.s3Client = new S3({ ...s3Options, region });
this.bucketName = bucketName;
}

Expand Down