Skip to content

Commit

Permalink
feat: cognito user auth endpoint (#431)
Browse files Browse the repository at this point in the history
Signed-off-by: Matthew Heroux <[email protected]>
  • Loading branch information
hxtree authored Oct 3, 2023
1 parent 63de3cc commit d7d9875
Show file tree
Hide file tree
Showing 6 changed files with 77 additions and 11 deletions.
4 changes: 3 additions & 1 deletion services/authentication-service/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,6 @@

![Lifecycle](https://img.shields.io/badge/lifecycle-unstable-red)

TODO cognito pool, rbac/mongoose,
## TODO

rbac/mongoose,
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import { JwtAuthGuard } from './jwt-auth.guard';
import { LoginDto } from './login-dto';
import { ForgotPasswordDto } from './forgot-password-dto';
import { ResetPasswordDto } from './reset-password-dto';
import { SignUpDto } from './sign-up-dto';

@Controller({
version: VERSION_NEUTRAL,
Expand Down Expand Up @@ -58,7 +59,7 @@ export class AuthController {
}

@Post('sign-up')
async signUp(@Body() body: LoginDto) {
async signUp(@Body() body: SignUpDto) {
const { username, password } = body;
await this.cognitoService.signUp(username, password);
return {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,17 +3,47 @@ import * as AWS from 'aws-sdk';

@Injectable()
export class CognitoService {
private ssm: AWS.SSM;

private readonly cognitoIdentityServiceProvider: AWS.CognitoIdentityServiceProvider;

constructor() {
AWS.config.region = process.env.AWS_REGION ?? 'us-east-2';
this.ssm = new AWS.SSM();

this.cognitoIdentityServiceProvider = new AWS.CognitoIdentityServiceProvider();
}

async fetchUserPoolId(): Promise<string> {
const parameterName = 'cognito-user-pool-id';
const response = await this.ssm
.getParameter({ Name: parameterName })
.promise();

if (response && response.Parameter && response.Parameter.Value) {
return response.Parameter.Value;
}

return Promise.reject(new Error(`Failed to get ${parameterName}`));
}

async fetchUserPoolClientId(): Promise<string> {
const parameterName = 'cognito-user-pool-client-id';
const response = await this.ssm
.getParameter({ Name: parameterName })
.promise();

if (response && response.Parameter && response.Parameter.Value) {
return response.Parameter.Value;
}

return Promise.reject(new Error(`Failed to get ${parameterName}`));
}

async authenticate(username: string, password: string): Promise<any> {
const params = {
AuthFlow: 'USER_PASSWORD_AUTH',
ClientId: 'YOUR_CLIENT_ID',
ClientId: await this.fetchUserPoolClientId(),
AuthParameters: {
USERNAME: username,
PASSWORD: password,
Expand All @@ -28,7 +58,7 @@ export class CognitoService {

async forgotPassword(username: string): Promise<void> {
const params = {
ClientId: 'YOUR_CLIENT_ID',
ClientId: await this.fetchUserPoolClientId(),
Username: username,
};

Expand All @@ -41,7 +71,7 @@ export class CognitoService {
newPassword: string,
): Promise<void> {
const params = {
ClientId: 'YOUR_CLIENT_ID',
ClientId: await this.fetchUserPoolClientId(),
ConfirmationCode: code,
Password: newPassword,
Username: username,
Expand All @@ -54,7 +84,7 @@ export class CognitoService {

async signUp(username: string, password: string): Promise<void> {
const params = {
ClientId: 'YOUR_CLIENT_ID',
ClientId: await this.fetchUserPoolClientId(),
Password: password,
Username: username,
};
Expand All @@ -64,7 +94,7 @@ export class CognitoService {

async deleteUser(userId: string): Promise<void> {
const params = {
UserPoolId: 'YOUR_USER_POOL_ID',
UserPoolId: await this.fetchUserPoolId(),
Username: userId,
};

Expand Down
18 changes: 18 additions & 0 deletions services/authentication-service/src/modules/auth/sign-up-dto.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import { ApiProperty } from '@nestjs/swagger';
import { IsOptional, IsString } from 'class-validator';

export class SignUpDto {
@IsString()
@IsOptional()
@ApiProperty({
default: 'jdoe',
})
username: string;

@IsString()
@IsOptional()
@ApiProperty({
default: 'password1234!',
})
password: string;
}
6 changes: 3 additions & 3 deletions services/authentication-service/stacks/cognito-pool.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,6 @@ export class CognitoPool extends Construct {

public client: cognito.UserPoolClient;

public userPoolId: string;

constructor(scope: Construct, id: string, props: CognitoPoolProps) {
super(scope, id);

Expand Down Expand Up @@ -60,7 +58,9 @@ export class CognitoPool extends Construct {
this.client = this.cognitoPool.addClient('AuthenticationClient', {
userPoolClientName: 'AuthenticationClient',
oAuth: {
flows: { authorizationCodeGrant: true },
flows: {
authorizationCodeGrant: true,
},
scopes: [cognito.OAuthScope.OPENID],
// TODO pick domain name
callbackUrls: ['https://catscradle.com/home'],
Expand Down
17 changes: 16 additions & 1 deletion services/authentication-service/stacks/main-stack.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,10 +23,25 @@ export class MainStack extends cdk.Stack {
},
);

/**
* A User Pool ID is a unique identifier for an Amazon Cognito User Pool.
* A User Pool is a user directory that helps you manage and authenticate users.
* It stores user attributes such as username, email, and phone number.
*/
new ssm.StringParameter(this, `${id}-user-pool-id`, {
description: 'Cognito User Pool ID',
parameterName: 'cognito-user-pool-id',
stringValue: cognitoPool.userPoolId,
stringValue: cognitoPool.cognitoPool.userPoolId,
});

/**
* A Client ID is a unique identifier for a specific client application
* that interacts with your Amazon Cognito User Pool.
*/
new ssm.StringParameter(this, `${id}-user-pool-client-id`, {
description: 'Cognito User Pool Client ID',
parameterName: 'cognito-user-pool-client-id',
stringValue: cognitoPool.client.userPoolClientId,
});

new cdk.CfnOutput(this, 'Localhost API Example', {
Expand Down

0 comments on commit d7d9875

Please sign in to comment.