AWS : how to get cognito user attributes in Lambda/cloud logic

Lambda function(js)

const AWS = require('aws-sdk');
const cognito = new AWS.CognitoIdentityServiceProvider();

function getUser(Username) {
    return new Promise((resolve, reject) => {
        cognito.adminGetUser({
            UserPoolId: process.env.COGNITO_USER_POOL_ID,
            Username: Username
        }, (err, data) => {
            if (err)
                reject(err.stack);
            else
                resolve(data.UserAttributes[2].Value);
        });
    });
}

async function getEmail(Username) {
  return await getUser(Username);
}

exports.handler = async (event) => {
    console.log(await getEmail('abcdef'));
    console.log(await getEmail('hijklmn'));
    console.log('done');
    return 'ok';
};
set Execution role with correct policy as below descripted.
set an environment 'COGNITO_USER_POOL_ID' with the user pool id.

Role policy

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "VisualEditor0",
            "Effect": "Allow",
            "Action": "cognito-idp:AdminGetUser",
            "Resource": "your user pool arn"
        }
    ]
}
userpool

Eexcution Result

Response:
"ok"

Request ID:
"a327a22f-0363-11e9-a897-6f0106540a1d"

Function Logs:
START RequestId: a327a22f-0363-11e9-a897-6f0106540a1d Version: $LATEST
2018-12-19T07:56:49.880Z    a327a22f-0363-11e9-a897-6f0106540a1d    errong.leng
@gmail.com
2018-12-19T07:56:50.056Z    a327a22f-0363-11e9-a897-6f0106540a1d    errong.leng
@hotmail.com
2018-12-19T07:56:50.056Z    a327a22f-0363-11e9-a897-6f0106540a1d    done
END RequestId: a327a22f-0363-11e9-a897-6f0106540a1d
REPORT RequestId: a327a22f-0363-11e9-a897-6f0106540a1d  Duration: 1149.09 ms
 Billed Duration: 1200 ms    Memory Size: 128 MB Max Memory Used: 30 MB

Refers

AWS.CognitoIdentityServiceProvider.adminGetUser

No comments:

Post a Comment

fixed: embedded-redis: Unable to run on macOS Sonoma

Issue you might see below error while trying to run embedded-redis for your testing on your macOS after you upgrade to Sonoma. java.la...