User Not receiving temporary password in email - amazon-web-services

Users are not receiving temporary passwords in email.
I'm trying to create user in cognito with lambda function.
'use strict'
const AWS= require('aws-sdk');
exports.handler = (event, context, callback) => {
console.log("event is ",event)
var cognitoidentityserviceprovider = new AWS.CognitoIdentityServiceProvider({apiVersion: '2016-04-18'});
var params = {
UserPoolId: process.env.userpool,
Username: event.queryStringParameters.username,
DesiredDeliveryMediums: ['EMAIL'],
ForceAliasCreation: false,
MessageAction: 'SUPPRESS',
TemporaryPassword: '******',
UserAttributes: [
{
Name: 'email_verified',
Value: "true"
},
{
Name: 'email',
Value: event.queryStringParameters.email
},
{
Name: 'name',
Value: event.queryStringParameters.name
}
]
};
cognitoidentityserviceprovider.adminCreateUser(params, function(err, data) {
if (err) console.log(err, err.stack); // an error occurred
else console.log(data); // successful response
var response = {
"statusCode": 200,
"headers": {
"User": "Created successful",
"x-custom-header" : "my custom header value",
"Access-Control-Allow-Origin": "*"
},
"body": JSON.stringify(data),
"isBase64Encoded": false
};
callback(null, response);
});
};

This is because you are using MessageAction: 'SUPPRESS'. Remove that and the proper email will be sent.

Related

API Gateway - Return XML or JSON

I have a node API Gateway stack and a Node Lambda. I've been trying to get API gateway to return content-type: application/xml OR application/json depending on the request (returnType=xml or returnType=json).
I have tried adding response models and that didn't work. BinaryTypes didn't work either. I have gotten it to do either application/json OR application/xml but I can't get it to do both. Is what I'm trying to do even possible? or should I create two separate endpoints?
This example always returns application/json.
Here is my lambda:
exports.handler = async function (event, context, callback) {
var format = event.format;
if (!format) {
callback(Error("[BadRequest] missing parameters"));
}
const promise = new Promise(function (resolve, reject) {
https
.get("exampleendpoint.com", (res) => {
let body = "";
res.on("data", (chunk) => {
body += chunk;
});
res.on("end", () => {
var results = JSON.parse(body);
if (format && format.toUpperCase() === "XML") {
var response = {
statusCode: 200,
headers: { "content-type": "application/xml" },
body:
'<?xml version="1.0" encoding="UTF-8"?><result>' +
OBJtoXML(results) +
"</result>",
};
resolve(response);
} else {
var response = {
statusCode: 200,
headers: { "content-type": "application/json" },
body: JSON.stringify(results),
};
resolve(response);
}
});
})
.on("error", (e) => {
var response = {
statusCode: 500,
body: "",
errorMessage: "Error from example.com",
};
resolve(response);
});
});
return promise;
};
Here is my api gateway code:
const epqApi = new gateway.RestApi(this, "restApi", {
restApiName: "resultsApi",
cloudWatchRole: true,
description: "Calls the service for the app",
endpointTypes: [gateway.EndpointType.REGIONAL],
deployOptions: {
stageName: "prod",
loggingLevel: gateway.MethodLoggingLevel.OFF,
dataTraceEnabled: false,
},
});
const epqResource = epqApi.root.addResource("v1");
const epqIntegration: gateway.LambdaIntegration =
new gateway.LambdaIntegration(generatePqsResultFunction, {
proxy: false,
allowTestInvoke: true,
passthroughBehavior: gateway.PassthroughBehavior.NEVER,
contentHandling: gateway.ContentHandling.CONVERT_TO_TEXT,
requestTemplates: {
"application/json": `{
"format":"$input.params(\'format\')"
}`,
},
integrationResponses: [
{
statusCode: "200",
responseParameters: {
"method.response.header.Access-Control-Allow-Origin": "'*'",
},
responseTemplates: {
"application/json": "$input.path('$.body')",
"application/xml": "$input.path('$.body')",
},
},
{
statusCode: "400",
selectionPattern: "^\\[BadRequest\\].*",
responseParameters: {
"method.response.header.Access-Control-Allow-Origin": "'*'",
},
responseTemplates: {
"application/javascript":
"#set($inputRoot = $input.path('$')) {\"errorMessage\" : \"$input.path('$.errorMessage')\"}",
},
},
],
});
epqResource.addMethod("GET", epqIntegration, {
requestParameters: {
//all params need to be in here, even if they are not required
"method.request.querystring.x": false,
"method.request.querystring.y": false,
"method.request.querystring.units": false,
"method.request.querystring.format": false,
"method.request.querystring.wkid": false,
"method.request.querystring.includeDate": false,
},
methodResponses: [
// Successful response from the integration
{
statusCode: "200",
responseParameters: {
"method.response.header.Access-Control-Allow-Origin": true,
},
},
{
statusCode: "400",
responseParameters: {
"method.response.header.Access-Control-Allow-Origin": true,
},
},
],
});
}

Postman pre-request script login with Query Params

I want to create a pre-script in postman to login so that i can get tokens.
pm.sendRequest({
url: 'https://localhost/api/login',
method: 'POST',
header: {
'Content-Type': 'multipart/form-data',
},
body: {
mode: 'formdata',
formdata: [
{key: "email", value: "myemail#mydoman.com", disabled: false, description: {content:"", type:"text/plain"}},
{key: "password", value: "mypass", disabled: false, description: {content:"", type:"text/plain"}},
{key: "action", value: "login", disabled: false, description: {content:"", type:"text/plain"}}
]
}
}, function(err, response) {
pm.environment.set("access_token");
});
I'm still no get token with those pre-script, help needed
const loginRequest = {
url: pm.environment.get('my_url') +"/api/login",
method: 'POST',
header: 'Content-Type: application/json',
body: {
mode: 'application/json',
raw: JSON.stringify({
"email": "myemail#mydoman.com",
"password":"mypass"
})
}
};
pm.sendRequest(loginRequest, function (err, response) {
pm.environment.set("access_token", response.json().token);
});

AWS Lambda updating object in DynamoDB

I'm trying to update object from DynamoDB for hours and I can't get it to work. I'm using DocumentClient library and its method update(). When I tested it with API Gateway, I got this error:
{
"errorType": "TypeError",
"errorMessage": "Cannot read property '_id' of undefined",
"trace": [
"TypeError: Cannot read property '_id' of undefined",
" at Runtime.exports.handler (/var/task/index.js:20:44)",
" at Runtime.handleOnce (/var/runtime/Runtime.js:66:25)"
]
}
Here is my code:
exports.handler = (event, context, callback) => {
console.log(event);
const id = event.listId;
const params = {
Key: {
"ListId": id
},
ExpressionAttributeNames: {
"#name": "Name",
"#shop": "Shop"
},
ExpressionAttributeValues: {
":name": event.listName,
":shop": {
"_id": event.listShop._id,
"name": event.listShop.name,
"address": event.listShop.address,
"city": event.listShop.city
}
},
TableName: "mk-lists",
UpdateExpression: "SET #name = :name, #shop = :shop"
};
dynamodb.update(params, (err, data) => {
if(err) {
console.log(err);
callback(err);
} else {
console.log(data);
callback(null, data);
}
});
};
I have Shop field in Lists table which is an object. Also, it is working when I test it in Lambda function. Can someone help me with this? Thanks in advance.
Here is my request body:
{
"listName": "Lista 13131",
"listShop": {
"_id": "933c836c-6868-4f56-a769-d59f5cbb231e",
"name": "DIS",
"address": "Podrinska 12",
"city": "Uzice"
}
}

AWS Lambda test does not return data from DynamoDB table

I am trying to get data from my DynamoDB table called dashboard so I am testing out the Lambda function with a sample from the table.
But all I am getting back from the test is :
Response:
{
"statusCode": 200,
"body": "\"Hello from Lambda!\""
}
It should just return the data from the table that matches it based on the ID as that is what I use to partition the table.
Dashboard example data which is also the test I made
{
"batteryLevel": 35,
"deviceId": "yxftd9pnitd-156xhref9g69a",
"eventId": "c07e3f9f-f6bb-4792-be6f-a9be95cdff38",
"id": 12345,
"location": {
"accuracy": 35.369,
"latitude": 55.8256671,
"longitude": 37.5962931
},
"tags": [
{
"accelX": 0.012,
"accelY": -0.004,
"accelZ": 1.008,
"createDate": "2020-08-11T18:51:58+0300",
"dataFormat": 5,
"defaultBackground": 2,
"favorite": true,
"humidity": 32.8425,
"id": "E5:F1:98:34:C0:0F",
"measurementSequenceNumber": 62865,
"movementCounter": 21,
"name": "Kitchen",
"pressure": 98702,
"rssi": -43,
"temperature": 25.58,
"txPower": 4,
"updateAt": "2020-08-18T19:57:48+0300",
"voltage": 3.013
}
],
"time": "2020-08-18T19:57:48+0300"
}
Lambda Function
"use strict";
const AWS = require("aws-sdk");
AWS.config.update({ region: "ap-southeast-1" });
exports.handler = async (event, context) => {
const ddb = new AWS.DynamoDB({ apiVersion: "2012-10-08" });
const documentClient = new AWS.DynamoDB.DocumentClient({ region: "ap-southeast-1"});
const params = {
TableName: "dashboard",
Key: {
id: 12345
}
};
try {
const data = await documentClient.get(params);
console.log(data);
} catch (err) {
console.log(err);
}
};
Based on the comments.
The issue was caused by not deploying the function after adding new code. Subsequently, the previously deployed version (i.e. "Hello from Lambda") was being executed.
The solution was to deploy the new function.

aws api gateway and lamda - how to get event.body

I'm new to aws and I have a strange problem of getting the body of event inside my lamda handler function.
exports.handler = async (event) => {
const response = {
statusCode: 200,
body: event.body
};
return response;
};
When I run test I get
Response:
{
"statusCode": 200
}
However when I only return event
exports.handler = async (event) => {
const response = {
statusCode: 200,
body: event <=====
};
return response;
};
I get
Response:
{
"statusCode": 200,
"body": {
"key1": "value1",
"key2": "value2",
"key3": "value3"
}
}
I'm using node 8.10. Does anybody knows what I'm doing wrong here?
The test event in to Lambda console is exactly what you get as the event parameter in your Lambda handler. When you put {"a":1}, you get {"a":1}.
You can simulate a different event types of AWS service (SNS, S3, API Gateway) selecting a template from the combobox.
As you are returning a HTTP response, you want probably to simulate an API Gateway event, it could look like this:
{
"body": "{\"a\":1}",
"pathParameters": {
"id": "XXX"
},
"resource": "/myres",
"path": "/myres",
"httpMethod": "GET",
"isBase64Encoded": true,
"requestContext": {
"authorizer": {
"tenantId": "TEST"
},
"accountId": "123456789012",
"resourceId": "123456",
"stage": "test",
"requestId": "test-request-id",
"requestTime": "09/Apr/2015:12:34:56 +0000",
"requestTimeEpoch": 1428582896000,
"path": "/myres",
"resourcePath": "/myres,
"httpMethod": "GET",
"apiId": "1234567890",
"protocol": "HTTP/1.1"
}
}
Then you will get the body in event.body as JSON string - you can convert it into an object by JSON.parse(event.body).
When returning, you have to serialize the response body with JSON.stringify:
return {
statusCode: 200,
body: JSON.stingify({your:'object'})
};
Change
exports.handler = async (event) => {
const response = {
statusCode: 200,
body: event.body
};
return response;
};
to
exports.handler = async (event) => {
const response = {
statusCode: 200,
body: JSON.stringify(event.body)
};
return response;
};
The body you return in API Gateway must be stringified, otherwise it doesn't know how to deal with the response.