3
\$\begingroup\$

This is the entire code for a Lambda function that registers a new user in Amazon Cognito.

The email, username, and password are passed to the Lambda function. The client ID is stored in an environment variable to be removed from the code.

const AWS = require("aws-sdk");
const cognitoidentityserviceprovider = new AWS.CognitoIdentityServiceProvider();

const clientID1 = process.env.client_id;

function registerUser(client, password, username, email){
  var params = {
   ClientId: client, /* required */
   Password: password, /* required */
   Username: username, /* required */
   UserAttributes: [
     {
       Name: 'email',
       Value: email
     }
   ]
  };
  cognitoidentityserviceprovider.signUp(params, function(err, data) {
   if (err) console.log(err, err.stack); // an error occurred
   else{
    console.log(data);           // successful response
    return data;
   }
  });
}


function verifyInput(e){
 let data = {};
 try{
  data.password = e.password;
  data.username = e.username;
  data.email = e.email;
 } catch (e) {
   console.error(e);
   return false;
 }
 if (data.password === undefined) return false;
 if (data.username === undefined) return false;
 if (data.email === undefined) return false;
 return data;
}

exports.handler = (event, context, callback) => {
   let check = verifyInput(event);
   if (check === false) return callback(null, "Registration Failed");
   let data = registerUser(clientID1, event.password, event.username, event.email);
   callback(null, "Registration Successful");
};

Note: I am aware that returning the data object from the verifyInput function is currently useless. I left it in for now as I thought there may need to still be some checks on the parameters at this stage.

Why I am using Lambda for the login? I have created a login system a couple of times (not sure how well) but would like to start using Cognito. For implementing on websites the JavaScript SDK seems to be best supported/documented. For simple/small/static sites I'd prefer not to implement a JavaScript backend but AWS PHP SDK doesn't seem to be well supported or documented and without working examples for a Cognito login. So I figured I could use NodeJS Lambda Functions to use the well supported JavaScript SDK then have PHP access them through an Amazon API Gateway.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.