how can I get all Users from aws cognito?
I found this: list Users
http://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/CognitoIdentityServiceProvider.html#listUsers-property
var cognito = new AWSCognito.CognitoIdentityServiceProvider;
cognito.listUsers(params, function(err, data) {
if (err) console.log(err, err.stack); // an error occurred
else console.log(data); // successful response
});
But when I do this I got this error:
No reagon defined ...
also tried this:
AWS.config.region = 'eu-central-1'; // Region
AWS.config.credentials = new AWS.CognitoIdentityCredentials({
IdentityPoolId: 'eu-central-1:',
Logins: {
'cognito-idp.eu-central-1.amazonaws.com/eu-central-1_': result.getIdToken().getJwtToken()
}
});
here I got result is not defined ...
how can I fetch all Users?
This is an working example:
let params = {
UserPoolId: '<<PoolID>>',
AttributesToGet: [
'email',
'family_name',
'given_name',
'custom:client',
'phone_number'
],
Limit: 0,
};
this.awsSDKAuth().listUsers(params, (err, data) => {
if (err) console.log(err, err.stack); // an error occurred
else {
console.log(data.Users);
}
});
Related
I am trying to have lambda trigger a codebuild function when it hits the point within the lambda function, here is the current code im using for lamda:
console.log('Loading function');
const aws = require('aws-sdk');
const s3 = new aws.S3();
exports.handler = async (event, context) => {
const codebuild = new aws.CodeBuild();
let body = JSON.parse(event.body);
let key = body.model;
var getParams = {
Bucket: 'bucketname', // your bucket name,
Key: key + '/config/training_parameters.json' // path to the object you're looking for
}
if (key) {
const objects = await s3.listObjects({
Bucket: 'bucketname',
Prefix: key + "/data"
}).promise();
console.log(objects)
if (objects.Contents.length == 3) {
console.log("Pushing")
await s3.getObject(getParams, function(err, data) {
if (err)
console.log(err);
if (data) {
let objectData = JSON.parse(data.Body.toString('utf-8'));
const build = {
projectName: "projname",
environmentVariablesOverride: [
{
name: 'MODEL_NAME',
value: objectData.title,
type: 'PLAINTEXT',
},
]
};
console.log(objectData.title)
codebuild.startBuild(build,function(err, data){
if (err) {
console.log(err, err.stack);
}
else {
console.log(data);
}
});
console.log("Done with codebuild")
}
}).promise();
const message = {
'message': 'Execution started successfully!',
}
return {
'statusCode': 200,
'headers': {'Content-Type': 'application/json'},
'body': JSON.stringify(message)
};
}
}
};
Specifically this part should trigger it:
codebuild.startBuild(build,function(err, data){
if (err) {
console.log(err, err.stack);
}
else {
console.log(data);
}
});
But its not, it even outputs after the function? Im thinking its something to do with promises/await/async but cant find the right solution? Any help would be appreciated.
As you pointed out the problem is related to promises. Change your code like this:
const result = await codebuild.startBuild(build).promise();
And if you configured your lambda permissions for CodeBuild it should work.
You can change your s3.getObject the same way without the callback function:
const file = await s3.getObject(getParams).promise();
console.log(file.Body);
I have recently started to work with the AWS SDK and how a user can authenticate with Cognito in an identity pool.
When querying the credentials I have the following question:
To what extent do the following approaches differ?
approach: getId() and getCredentialsForIdentity():
const cognitoidentity = new AWS.CognitoIdentity()
var params = {
IdentityPoolId: 'STRING_VALUE', /* required */
AccountId: 'STRING_VALUE',
Logins: {
'<IdentityProviderName>': 'STRING_VALUE',
/* '<IdentityProviderName>': ... */
}
};
cognitoidentity.getId(params, function(err, data) {
if (err) console.log(err, err.stack); // an error occurred
else console.log(data); // successful response
});
var params = {
IdentityId: 'STRING_VALUE', /* required */
CustomRoleArn: 'STRING_VALUE',
Logins: {
'<IdentityProviderName>': 'STRING_VALUE',
/* '<IdentityProviderName>': ... */
}
};
cognitoidentity.getCredentialsForIdentity(params, function(err, data) {
if (err) console.log(err, err.stack); // an error occurred
else console.log(data); // data AccesKeyId,Expiration, SecretKey, SessionToken
});
approach:
AWS.config.credentials = new AWS.CognitoIdentityCredentials({
IdentityPoolId: identityPoolId,
Logins:{
'Provider': jwtToken
},
region: "eu-central-1"
});
AWS.config.credentials.get(function(){
// Credentials will be available when this function is called.
const{ accessKeyId} = AWS.config.credentials
const {secretAccessKey} = AWS.config.credentials
const {sessionToken} = AWS.config.credentials
})
the credentials of the two attempts are different, the SessionToken is the same. What is the difference between the SecretKey obtained in the first attempt and the SecretAccesKey obtained in the second attempt?
What are the differences between the two attempts?
The first attempt : enhanced simpliefied authflow with GetId and GetCredentialsForIdentity
https://docs.aws.amazon.com/cognito/latest/developerguide/authentication-flow.html
second attempt:
https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/loading-browser-credentials-cognito.html
I am grateful for any help :)
https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/CognitoIdentityCredentials.html
According to this it is doing the same thing in the background.The difference in syntax for SecretKey and SecretAccesKey appears to be purely cosmetic. I have noticed the same in boto3. Regardless, you can pass either with accesskey and sessionid to authenticate other AWS services.
This is the code Iam using,
var AWS = require('aws-sdk');
var iotdata = new AWS.IotData({
endpoint: '###########.iot.ap-south-1.amazonaws.com'
});
exports.handler = async (event) => {
var params = {
payload: Buffer.from('...') || 'STRING_VALUE'
encoded on your behalf */, /* required */
thingName: 'ESP32', /* required */
//shadowName: 'STRING_VALUE'
};
iotdata.updateThingShadow(params, function(err, data) {
if (err) console.log(err, err.stack); // an error occurred
else console.log(data); // successful response
});
};
I referred to this from the given link,
https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/IotData.html#updateThingShadow-property
But I cant update my shadow.
I also dont understand in which format I should include the payload.
I am running this on AWS Lambda function in Nodejs 12.x environment. I also dont receive any errors in cloudwatch . Cloudwatch tells me execution result has succeeded? Can you help me?
I have already given permission for Lambda to updateShadow.
This the final correct code .....
var AWS = require('aws-sdk');
var iotdata = new AWS.IotData({
endpoint: '#######.iot.ap-south-1.amazonaws.com'
});
exports.handler = async (event) => {
var POST_DATA = JSON.stringify({"state":{"desired":{"state":10}}});
await new Promise((resolve, reject) => {
var params = {
payload:POST_DATA ,
thingName: 'ESP32', /* required */
//shadowName: 'STRING_VALUE'
};
iotdata.updateThingShadow(params, function(err, data) {
if (err) {
console.log(err, err.stack);
console.log("error................")// an error occurred
reject(err);
} else {
console.log(data); // successful response
resolve(data)
}
});
})
}
The issue here is that you are using the async Lambda handler. So while your updateThingShadow() call is in progress, the Lambda function completes and exits. You need to wait for that call to complete. There are two ways to do that -
Approach 1: (A simpler async-await syntax)
var AWS = require('aws-sdk');
var iotdata = new AWS.IotData({
endpoint: '###########.iot.ap-south-1.amazonaws.com'
});
exports.handler = async (event) => {
var params = {
// Define params
};
try {
const data = await iotdata.updateThingShadow(params).promise();
console.log(data);
} catch (err) {
console.log(err);
}
};
Approach 2: (If you prefer using the callback approach)
var AWS = require('aws-sdk');
var iotdata = new AWS.IotData({
endpoint: '###########.iot.ap-south-1.amazonaws.com'
});
exports.handler = async (event) => {
var params = {
// Define params
};
await new Promise((resolve, reject) => {
iotdata.updateThingShadow(params, function(err, data) {
if (err) {
console.log(err, err.stack); // an error occurred
reject(err); // End the promise with an error
} else {
console.log(data); // successful response
resolve(data); // End the promise with success
}
});
})
};
I am trying to create a lambda function to create a user whenever there is an update in one of the tables of dynamo db.
I have created a dynamodb table with a trigger. I get "adminCreateUser not a function" error when i run the below code in lambda.
lambda function:
exports.handler = function(event, context) {
// TODO implement
cognitoidentityserviceprovider.adminCreateUser(params, function(err, data) {
if (err) console.log(err, err.stack); // an error occurred
else console.log(data); // successful response
});
context.done(null, 'Hello from Lambda');
};
It should be just the code below. Maybe make sure adminCreateUser is in your main AWS SDK, it was only introduced pretty recently.
const AWS = require('aws-sdk');
exports.handler = (event, context, callback) => {
AWS.config.apiVersions = {
cognitoidentityserviceprovider: '2016-04-18'
};
AWS.config.update({accessKeyId: 'akid', secretAccessKey: 'secret'});
var cognito = new AWS.CognitoIdentityServiceProvider({
region: 'us-east-1'
});
params = {};
cognito.adminCreateUser(params, function(err, data) {
if (err) console.log(err, err.stack); // an error occurred
else
console.log(data); // successful response
});
context.done(null, 'Hello from Lambda');
};
I'm using Amazon Simple DB (http://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/SimpleDB.html)
and I'm trying to use putAttributes by writing the following node.js code:
AWS.config = new AWS.Config({accessKeyId: '***', secretAccessKey: '***', region: '***'});
var simpledb = new AWS.SimpleDB();
var params = {
Attributes: [
{
Name: 'firstname',
Value: 'David'
},
],
DomainName: '***', /* required */
ItemName: 'per2', /* required */
};
simpledb.putAttributes(params, function(err, data) {
if (err) console.log(err, err.stack); // an error occurred
else console.log(data); // successful response
});
Unfortunately, I get the following error in console after reading the line:
var simpledb = new AWS.SimpleDB();
try.html?_ijt=no554cohakgtacn421reh33mpr:22 Uncaught TypeError:
AWS.SimpleDB is not a constructor
Do you have any idea what is the problem?