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

feat: ✨ add auth and aws config #91

Merged
merged 6 commits into from
Dec 3, 2024
Merged
Show file tree
Hide file tree
Changes from 2 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
4 changes: 3 additions & 1 deletion .env.sample
Original file line number Diff line number Diff line change
Expand Up @@ -16,4 +16,6 @@ DATABASE_NAME=product_a_main
AWS_REGION=ap-northeast-1
AWS_ACCESS_KEY_ID=xxxx
AWS_SECRET_ACCESS_KEY=xxxx
COGNITO_CLIENT_ID=xxxx
COGNITO_CLIENT_ID=xxxx

JWT_SECRET=xxxx
12 changes: 8 additions & 4 deletions apps/users/src/app/app.module.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,12 @@
import { Module } from '@nestjs/common';
import { ConfigModule } from '@nestjs/config';
import { databaseConfig, userAppConfig } from '@shared/config';

import { UsersModule } from '../users/users.module';
import {
databaseConfig,
userAppConfig,
awsConfig,
authConfig,
} from '@shared/config';
import { UsersModule } from '@users/interface-adapters';

import { AppController } from './app.controller';
import { AppService } from './app.service';
Expand All @@ -11,7 +15,7 @@ import { AppService } from './app.service';
imports: [
ConfigModule.forRoot({
isGlobal: true,
load: [userAppConfig, databaseConfig],
load: [userAppConfig, databaseConfig, awsConfig, authConfig],
}),
UsersModule,
],
Expand Down
2 changes: 2 additions & 0 deletions libs/shared/config/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,2 +1,4 @@
export * from './lib/applications.config';
export * from './lib/database.config';
export * from './lib/aws.config';
export * from './lib/auth.config';
15 changes: 9 additions & 6 deletions libs/shared/config/src/lib/applications.config.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,14 @@
import { registerAs } from '@nestjs/config';
import { z } from 'zod';

interface ServiceConfig {
protocol: string;
host: string;
port: number;
name?: string;
}
const serviceSchema = z.object({
protocol: z.string().min(1),
host: z.string().min(1),
port: z.coerce.number().int().min(1).max(65535),
name: z.string().optional(),
});

export type ServiceConfig = z.infer<typeof serviceSchema>;

const DEFAULT_PROTOCOL = 'http' as const;
const DEFAULT_HOST = 'localhost' as const;
Expand Down
27 changes: 27 additions & 0 deletions libs/shared/config/src/lib/auth.config.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import { authConfig } from './auth.config';

describe('authConfig', () => {
const OLD_ENV = process.env;

beforeEach(() => {
jest.resetModules();
process.env = { ...OLD_ENV };
});

afterAll(() => {
process.env = OLD_ENV;
});

it('should return the JWT secret from environment variable', () => {
process.env['JWT_SECRET'] = 'test-secret';

const config = authConfig();
expect(config.secret).toBe('test-secret');
});

it('should throw error if JWT_SECRET is not set', () => {
delete process.env['JWT_SECRET'];

expect(() => authConfig()).toThrow();
});
});
16 changes: 16 additions & 0 deletions libs/shared/config/src/lib/auth.config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import { registerAs } from '@nestjs/config';
import { z } from 'zod';

const authSchema = z.object({
secret: z.string().min(1).max(22),
});
zhumeisongsong marked this conversation as resolved.
Show resolved Hide resolved

export type AuthConfig = z.infer<typeof authSchema>;

export const authConfig = registerAs('auth', (): AuthConfig => {
const config = {
secret: process.env['JWT_SECRET'],
};

return authSchema.parse(config);
});
zhumeisongsong marked this conversation as resolved.
Show resolved Hide resolved
51 changes: 51 additions & 0 deletions libs/shared/config/src/lib/aws.config.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
import { awsConfig } from './aws.config';

describe('awsConfig', () => {
const OLD_ENV = process.env;

beforeEach(() => {
jest.resetModules();
process.env = { ...OLD_ENV };
});

afterAll(() => {
process.env = OLD_ENV;
});

it('should return AWS config from environment variables', () => {
process.env['AWS_REGION'] = 'us-east-1';
process.env['AWS_ACCESS_KEY_ID'] = 'test-key-id';
process.env['AWS_SECRET_ACCESS_KEY'] = 'test-secret-key';

const config = awsConfig();
expect(config).toEqual({
region: 'us-east-1',
accessKeyId: 'test-key-id',
secretAccessKey: 'test-secret-key',
});
});

it('should throw error if AWS_REGION is not set', () => {
process.env['AWS_ACCESS_KEY_ID'] = 'test-key-id';
process.env['AWS_SECRET_ACCESS_KEY'] = 'test-secret-key';
delete process.env['AWS_REGION'];

expect(() => awsConfig()).toThrow();
});

it('should throw error if AWS_ACCESS_KEY_ID is not set', () => {
process.env['AWS_REGION'] = 'us-east-1';
process.env['AWS_SECRET_ACCESS_KEY'] = 'test-secret-key';
delete process.env['AWS_ACCESS_KEY_ID'];

expect(() => awsConfig()).toThrow();
});

it('should throw error if AWS_SECRET_ACCESS_KEY is not set', () => {
process.env['AWS_REGION'] = 'us-east-1';
process.env['AWS_ACCESS_KEY_ID'] = 'test-key-id';
delete process.env['AWS_SECRET_ACCESS_KEY'];

expect(() => awsConfig()).toThrow();
});
});
22 changes: 22 additions & 0 deletions libs/shared/config/src/lib/aws.config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import { registerAs } from '@nestjs/config';
import { z } from 'zod';

const awsSchema = z.object({
region: z.string().min(1),
accessKeyId: z.string().min(1),
secretAccessKey: z.string().min(1),
cognitoClientId: z.string().min(1),
});

export type AwsConfig = z.infer<typeof awsSchema>;

export const awsConfig = registerAs('aws', (): AwsConfig => {
const config = {
region: process.env['AWS_REGION'],
accessKeyId: process.env['AWS_ACCESS_KEY_ID'],
secretAccessKey: process.env['AWS_SECRET_ACCESS_KEY'],
cognitoClientId: process.env['COGNITO_CLIENT_ID'],
};

return awsSchema.parse(config);
});
zhumeisongsong marked this conversation as resolved.
Show resolved Hide resolved
2 changes: 1 addition & 1 deletion libs/shared/config/src/lib/database.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ const databaseSchema = z.object({

export type DatabaseConfig = z.infer<typeof databaseSchema>;

export const databaseConfig = registerAs('database', () => {
export const databaseConfig = registerAs('database', (): DatabaseConfig => {
const config = {
host: process.env['DATABASE_HOST'] || 'localhost',
port: process.env['DATABASE_PORT'] || 27017,
Expand Down
Original file line number Diff line number Diff line change
@@ -1,26 +1,32 @@
import { Injectable, Logger } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { awsConfig } from '@shared/config';
import * as AWS from 'aws-sdk';

@Injectable()
export class AwsCognitoService {
private cognito: AWS.CognitoIdentityServiceProvider;
private readonly logger = new Logger(AwsCognitoService.name);
// private readonly configService: ConfigService;
private cognito: AWS.CognitoIdentityServiceProvider;

constructor(private readonly configService: ConfigService) {
const awsConfig = this.configService.get('aws');

constructor() {
// Initial CognitoIdentityServiceProvider instance
this.cognito = new AWS.CognitoIdentityServiceProvider({
region: process.env['AWS_REGION'],
accessKeyId: process.env['AWS_ACCESS_KEY_ID'],
secretAccessKey: process.env['AWS_SECRET_ACCESS_KEY'],
region: awsConfig.region,
accessKeyId: awsConfig.accessKeyId,
secretAccessKey: awsConfig.secretAccessKey,
});
}

async signUp(
email: string,
password: string,
): Promise<AWS.CognitoIdentityServiceProvider.SignUpResponse> {
const awsConfig = this.configService.get('aws');
const params: AWS.CognitoIdentityServiceProvider.SignUpRequest = {
ClientId: process.env['COGNITO_CLIENT_ID'] ?? '', // TODO: add this to the config
ClientId: awsConfig.cognitoClientId,
Username: email,
Password: password,
UserAttributes: [
Expand All @@ -41,9 +47,10 @@ export class AwsCognitoService {
email: string,
password: string,
): Promise<AWS.CognitoIdentityServiceProvider.InitiateAuthResponse> {
const awsConfig = this.configService.get('aws');
const params: AWS.CognitoIdentityServiceProvider.InitiateAuthRequest = {
AuthFlow: 'USER_PASSWORD_AUTH',
ClientId: process.env['COGNITO_CLIENT_ID'] || '',
ClientId: awsConfig.cognitoClientId,
AuthParameters: {
USERNAME: email,
PASSWORD: password,
Expand All @@ -61,9 +68,10 @@ export class AwsCognitoService {
async refreshToken(
refreshToken: string,
): Promise<AWS.CognitoIdentityServiceProvider.InitiateAuthResponse> {
const awsConfig = this.configService.get('aws');
const params: AWS.CognitoIdentityServiceProvider.InitiateAuthRequest = {
AuthFlow: 'REFRESH_TOKEN_AUTH',
ClientId: process.env['COGNITO_CLIENT_ID'] || '',
ClientId: awsConfig.cognitoClientId,
AuthParameters: {
REFRESH_TOKEN: refreshToken,
},
Expand All @@ -78,8 +86,9 @@ export class AwsCognitoService {
}

async confirmSignUp(email: string, confirmationCode: string): Promise<void> {
const awsConfig = this.configService.get('aws');
const params: AWS.CognitoIdentityServiceProvider.ConfirmSignUpRequest = {
ClientId: process.env['COGNITO_CLIENT_ID'] || '',
ClientId: awsConfig.cognitoClientId,
Username: email,
ConfirmationCode: confirmationCode,
};
Expand Down
Loading