Tips for sending code confirmation in Amazon Cognito identity using nest.js

Having some issues with implementing AWS Cognito login in Nest.js? Check out this helpful guide on token validation: https://medium.com/weekly-webtips/token-validation-with-aws-cognito-and-nestjs-6f9e4088393c. I need to add a feature where users receive a confirmation code via email. Should I modify the RegisterUser Service or create a new method in both the service and controller?

import { AuthConfig } from './auth.config';
import { Inject, Injectable } from '@nestjs/common';
import {
  AuthenticationDetails,
  CognitoUser,
  CognitoUserPool,
  CognitoUserAttribute,
} from 'amazon-cognito-identity-js';

@Injectable()
export class AuthService {
  private userPool: CognitoUserPool;
  private sessionUserAttributes: {};
  constructor(
    @Inject('AuthConfig')
    private readonly authConfig: AuthConfig,
  ) {
    this.userPool = new CognitoUserPool({
      UserPoolId: this.authConfig.userPoolId,
      ClientId: this.authConfig.clientId,
    });
  }

  registerUser(registerRequest: {
    name: string;
    email: string;
    password: string;
  }) {
    const { name, email, password } = registerRequest;
    return new Promise((resolve, reject) => {
      return this.userPool.signUp(
        name,
        password,
        [new CognitoUserAttribute({ Name: 'email', Value: email })],
        null,
        (err, result) => {
          if (!result) {
            reject(err);
          } else {
            resolve(result.user);
          }
        },
      );
    });
  }

  authenticateUser(user: { name: string; password: string }) {
    const { name, password } = user;

    const authenticationDetails = new AuthenticationDetails({
      Username: name,
      Password: password,
    });
    const userData = {
      Username: name,
      Pool: this.userPool,
    };

    const newUser = new CognitoUser(userData);

    return new Promise((resolve, reject) => {
      return newUser.authenticateUser(authenticationDetails, {
        onSuccess: result => {
          resolve(result);
        },
        onFailure: err => {
          reject(err);
        },
      });
    });
  }
}

import { BadRequestException, Body, Controller, Post } from '@nestjs/common';
import { AuthService } from './auth.service';

@Controller('auth')
export class AuthController {
  constructor(private readonly authService: AuthService) {}

  @Post('register')
  async register(
    @Body() registerRequest: { name: string; password: string; email: string },
  ) {
    return await this.authService.registerUser(registerRequest);
  }

  @Post('login')
  async login(@Body() authenticateRequest: { name: string; password: string }) {
    try {
      return await this.authService.authenticateUser(authenticateRequest);
    } catch (e) {
      throw new BadRequestException(e.message);
    }
  }
}

Answer №1

By introducing a new method in the service and calling it from the controller, I was able to resolve the issue.

 confirmUser(user: { username: string; confirmationCode: string }) {
        const { username, confirmationCode } = user;
    
        const userData = {
          Username: username,
          Pool: this.userPool,
        };
        const cognitoUser = new CognitoUser(userData);
    
        return new Promise((resolve, reject) => {
         cognitoUser.confirmRegistration(confirmationCode, true, function (err, result) {
          if (err) {
           console.log(err);
           reject(err);
          } else {
           resolve(result);
          }
         });
        });
       }

---------------------------controller--------------

@Post('confirm')
  async confirm(@Body()  confirmUser: { username: string; confirmationCode: string }) {
    try {
      return await this.authService.confirmUser(confirmUser);
    } catch (e) {
      throw new BadRequestException(e.message);
    }
  }

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Error: Dependency Not Found in NestJS

Encountering a problem with NestJS: "[Nest] 5068 - 08/11/2021, 3:12:02 PM ERROR [ExceptionHandler] Nest can't resolve dependencies of the AppService (?). Please make sure that the argument UserRepository at index [0] is available in the AppModule ...

What is the process for specifying a method on a third-party class in TypeScript?

I'm facing a challenge while trying to extend a third-party class in TypeScript. The issue is that I am unable to access any existing methods of the class within my new method. One possible solution could be to redeclare the existing methods in a sep ...

Why am I unable to use a string as the src in next/image component?

After importing the Image module with the code import Image from "next/image";, I encountered an error that states: The type '{ src: string; }' cannot be assigned to type 'IntrinsicAttributes & ImageProps'. The type &apo ...

TypeScript compiler not processing recently generated files

While working on a project using TypeScript, I've noticed that the files compile without any issues when using tsc with the watch flag to monitor changes. However, I have run into an issue where when I create a new file, tsc does not automatically det ...

Sorting an object array by date is causing a problem

UPDATE: Finally cracked the code on this issue. I initially assumed that Date was interpreting the date ("29-04-2020") as DD-MM-YYYY, when it should actually be MM-DD-YYYY. For instance, here's an object array I'm working with: let t ...

Passing a value to a property with a dynamically passed name in TypeScript

I'm encountering an eslint/typescript error message: errorUnsafe member access .value on an any value @typescript-eslint/no-unsafe-member-access when attempting to assign a value to a dynamically named property: selectChange(name: string, value: stri ...

Divs are not being organized into rows correctly due to issues with Bootstrap styling

I have implemented Bootstrap in my Angular application. The stylesheet link is included in my Index.html file as follows: <link rel="stylesheet" href="../node_modules/bootstrap/dist/css/bootstrap.css"> In addition to that, I have listed Bootstrap a ...

Using Angular 6 to upload an XML document via httpClient

I have a service in Angular 6 using httpClient with the following code: import { Injectable } from '@angular/core'; import { HttpClient, HttpHeaders } from '@angular/common/http'; const httpOptions = { headers: new HttpHeaders({ &ap ...

Tips for integrating Tailwind CSS into Create React App using React

I recently started using tailwindcss with my react app. I tried to follow the guide from tailwindcss but encountered various issues and bugs along the way. If anyone has advice on how to successfully start a project using tailwind and react, I would apprec ...

Retrieve a particular element from an array within a JSON object using Ionic

I am currently facing a challenge in extracting a specific array element from a JSON response that I have retrieved. While I can successfully fetch the entire feed, I am struggling to narrow it down to just one particular element. Here is what my service ...

Do [(ngModel)] bindings strictly adhere to being strings?

Imagine a scenario where you have a radiobutton HTML element within an angular application, <div class="radio"> <label> <input type="radio" name="approvedeny" value="true" [(ngModel)]=_approvedOrDenied> Approve < ...

Creating a different type by utilizing an existing type for re-use

Can you help me specify that type B in the code sample below should comprise of elements from interface A? The key "id" is mandatory, while both "key" and "value" are optional. interface A { id: string; key: string; value: string | number; } /** ...

Angular 2: Integrating a service into a class

I am working on an Angular class that represents a shape. My goal is to be able to create multiple instances of this class using a constructor. The constructor requires several arguments that define the properties of the shape. constructor(public center: ...

Developing a project using npm and Node.js with Typescript has been smooth sailing so far. However, an issue has arisen

Recently, I came across a helpful guide on setting up a Node.js project in Typescript on this website: https://basarat.gitbooks.io/typescript/docs/quick/nodejs.html The guide also provides instructions for auto-recompilation upon changes when using npm st ...

Refreshing the Mat Dialog content when removing items in Angular Material

I have successfully implemented a mat dialog table with 3 columns - name, email, and delete icon. When the user clicks on the delete icon, it prompts a confirmation message to confirm the deletion. Upon confirming, the item is removed from the database. Ho ...

Issue encountered in Ionic/React/Typescript - Incorrect props supplied to React.FC<'erroneous props provided here'>

Having struggled with this issue for a while now without any success, I have searched through numerous questions here but none seem to address my specific case. Therefore, I kindly request your assistance. I am encountering difficulties passing props thro ...

Forwarding parameter data type

I am facing an issue with 2 navigation points leading to the same screen 1. this.router.navigate([this.config.AppTree.App.Module.Details.Path], { state: { data: { id: this.TableId } } }); this.router.navigate([this.config.AppTree.App.Module.Details.Pa ...

Trouble accessing images from database in Angular 2 with Firebase

Recently, I've integrated an image upload feature for my database using the following function: private saveFileData(upload: Upload): void { this.firebaseAuth.authState.subscribe(auth => { this.db.list(`uploads/${auth && auth.email && au ...

Unable to link to '' because it is not recognized as a valid attribute of '' in Angular 2

I encountered an exception while working on my Angular 2 project and I'm struggling to figure out the cause. Below is the snippet of my code: ts: import {Component} from "@angular/core"; import {GridOptions} from "ag-grid"; import {RedComponentComp ...

Troubleshooting error "is not assignable to type..." when simulating global fetch using TypeScript

I am encountering an issue with the "global.fetch" part and cannot seem to figure out why. Despite following the standard procedure, I am still facing this TS2322 error. I am seeking assistance to understand why this error is occurring. I am open to sugges ...