aws-sdk-jsaws-sdk-js-v3

How to lookup cognito user by their uuid with AWS SDK V3


I want to find users by their sub uuid.

In v2 (inspired from How do I look up a cognito user by their sub/UUID?)

require('dotenv').config();
var AWS = require('aws-sdk');
AWS.config.setPromisesDependency(require('bluebird'));

module.exports = {
  get: async function (uuid) {
    var cog = new AWS.CognitoIdentityServiceProvider({
      region: process.env.AWS_REGION,
      accessKeyId: process.env.AWS_COGNITO_ACCESS_ID,
      secretAccessKey: process.env.AWS_COGNITO_SECRET_ACCESS_KEY,
    });
    var filter = "sub = \"" + uuid + "\"";

    var req = {
      "Filter": filter,
      "UserPoolId": process.env.AWS_COGNITO_USER_POOL_ID
    };

    try {
      var result = await cog.listUsers(req).promise();

      var name = result.Users[0].Attributes.find(u => u.Name == "name");
      var mail = result.Users[0].Attributes.find(u => u.Name == "email");

      return { 'name': name.Value, 'mail': mail.Value };
    } catch (error) {
      console.log(error)
    }
  },
}

Solution

  • Ok it's now working thanks to aws-sdk-js-codemod

    require('dotenv').config();
    const
      {
        CognitoIdentityProvider: CognitoIdentityServiceProvider
      } = require("@aws-sdk/client-cognito-identity-provider");
    
    module.exports = {
      get: async function (uuid) {
        var cog = new CognitoIdentityServiceProvider({
          region: process.env.AWS_REGION,
          credentials: {
            accessKeyId: process.env.AWS_COGNITO_ACCESS_ID,
            secretAccessKey: process.env.AWS_COGNITO_SECRET_ACCESS_KEY
          }
        });
        var filter = "sub = \"" + uuid + "\"";
    
        var req = {
          "Filter": filter,
          "UserPoolId": process.env.AWS_COGNITO_USER_POOL_ID
        };
    
        try {
          var result = await cog.listUsers(req);
    
          var name = result.Users[0].Attributes.find(u => u.Name == "name");
          var mail = result.Users[0].Attributes.find(u => u.Name == "email");
    
          return { 'name': name.Value, 'mail': mail.Value };
        } catch (error) {
          console.log(error)
        }
      },
    }