CS4521:   Mobile and Topics in Web Programming

Lambda (nodeJS) funciton code for user password verfication -- this code will

  • //STEP 1: make a request from database table using the userId for primary key
  • //STEP 2: compare retrieved password from database with the password specified as input (in the request)
  • //STEP 3: if the same retrurn success
  • //STEP 4: if not the same return failure



First: Have a database table called biker that contains

  • primary key - userId

  • other columns - password, date

Code

 

Basics of a Lambda function / code in NodeJS that will write a new entry (passed as event data) to the AmazonDB database

 

'use strict';
 /*
 This code is used to make request from database table for password of entry with userId specified  Notice that the
format is JSON (java script object notation) which is commonly used for data exchange with web services
input event example
                     "Item"  : {
                     "userId": "lynne123",
                     "date": "Mon Aug 29 2016 23:57:25 GMT+0000 (UTC)",
                     "password": "whateverIspassword123"
                     }
                     
                     TODO: extend this  code to make sure that the event parameters are not null and pass default  values if they 
                     NOTE: date is optional.   Should add processing the fields of firstName, lastName and date to complete all of the
values possible in each entry of the biker database table */ console.log('Loading function');
console.log('Loading function');
 var doc =  require('dynamodb-doc');  //require javascript package for DynamoDB access
 var db = new  doc.DynamoDB();   //create instance of DynamoDB access object
             

//This is the MAIN function that is called by Lambda system, passing event and context
// see above for expected event data attributes that will be processed below to use as data want to enter into our bikers table        
exports.handler = function(event, context, callback) {
 	          var responseCode = 200;
 	          var requestBody, pathParams, queryStringParams, headerParams, stage,
 	          stageVariables, cognitoIdentityId, httpMethod, sourceIp, userAgent,
 	          requestId, resourcePath;
 	          console.log("request: " + JSON.stringify(event));
            // Request Body
 	          requestBody = event.body;
            if (requestBody !== undefined && requestBody !== null) {
                 // Set 'test-status' field in the request to test sending a specific response status code (e.g., 503)
 	               responseCode = JSON.parse(requestBody)['test-status'];
 	          }
            // Path Parameters
 	          pathParams = event.path;
            // Query String Parameters
 	          queryStringParams = event.queryStringParameters;
            // Header Parameters
 	          headerParams = event.headers;
            if (event.requestContext !== null && event.requestContext !== undefined) {
                         var requestContext = event.requestContext;
                         // API Gateway Stage
             	          stage = requestContext.stage;
                         // Unique Request ID
             	          requestId = requestContext.requestId;
                         // Resource Path
             	          resourcePath = requestContext.resourcePath;
                         var identity = requestContext.identity;
                         // Amazon Cognito User Identity
             	          cognitoIdentityId = identity.cognitoIdentityId;
                         // Source IP
             	          sourceIp = identity.sourceIp;
                         // User-Agent
             	          userAgent = identity.userAgent;
 	          }
             // API Gateway Stage Variables
 	          stageVariables = event.stageVariables;
             // HTTP Method (e.g., POST, GET, HEAD)
 	          httpMethod = event.httpMethod;
             //********************************************************************************************
 	          //business logic --read in input and verify is userId specified has password specified in database
var userID; var password;

//IF a PUT method get the JSON data from body and not from event
if(httpMethod !== undefined && (httpMethod == "PUT" || httpMethod =="POST"))
{ requestBody = JSON.parse(requestBody); //expect input in JSON form
userID = requestBody.userId;
password = requestBody.password; }
else if(httpMethod !== undefined && httpMethod == "GET") //if GET method type
{
userID = queryStringParams.userId;
password = queryStringParams.password;
console.log("userid INPUT" + userID + " and method type = " + httpMethod + "and queryParameters= " + JSON.stringify(queryStringParams));
}
else //if a not POST/PUT/GET
{
userID = event.userId; //get userID from event
password = event.password; //get password from event
}
 
 	          //simple log to see what is going on.
 	          console.log(userID  + "," + password );
   
 	          var tableName =  "blindbike-mobilehub-1926030853-biker";  //this is the name of YOUR project's dynamoDB table
   
 	          var params = {
             	          AttributesToGet: [
                           "password"
             	          ],
             	          TableName:tableName, 
   
             	          Key : { 
                           "userId" :  userID
             	          }
             }
             //make request to get the entry from database table with the
 	          // above key specified for user id in the params variable
 	          db.getItem(params, function(err, data) {
 	          if (err) {
             	          console.log(err); // an error occurred
             	          context.fail(new Error("failed to access databse"));
             	          callback(new Error("Failed database retrieveal for verification"));
   
 	          } 
 	          else
 	          {
             	          console.log("success getting item"); console.log(data); // successful response
             	          var returned_password = data.Item.password;
             	          console.log("returned password is: " + returned_password);
   
             	          if(password != returned_password) //fail verification STEP 4
             	           {  console.log("Verification FAILED, passwords not the same");
   
               	          var error_responseBody = {
              	            requestBody : requestBody,
              	            pathParams : pathParams,
              	            queryStringParams : queryStringParams,
              	            headerParams : headerParams,
              	            stage : stage,
              	            stageVariables : stageVariables,
              	            cognitoIdentityId : cognitoIdentityId,
              	            httpMethod : httpMethod,
              	            sourceIp : sourceIp,
              	            userAgent : userAgent,
              	            requestId : requestId,
              	            resourcePath : resourcePath,
              	            userId: userID,
              	            verifiedPassword: password,
              	            verificationPassed: "FAILED"
                           };
   
              	         var error_response = {
                         	          statusCode: responseCode,
 	                                  headers: {
                                       "x-custom-header" : "custom header value"
 	                                  },
 	                                  body: JSON.stringify(error_responseBody)
 	                          };
 	         
                           //context.fail(error_response, "Failed verification, passwords not the same");
 	                         callback(new Error("Failed verification, passwords not the same"), JSON.stringify(error_response));
 	                       }
 	                      else
 	                       {
                         	          console.log("passwords are the same");
                         	          //*******************************************************************************
 	                                  // For demonstration purposes, we'll just echo these values back to the client
 	                                  var responseBody = {
 	                                              requestBody : requestBody,
 	                                              pathParams : pathParams,
 	                                              queryStringParams : queryStringParams,
 	                                              headerParams : headerParams,
 	                                              stage : stage,
 	                                              stageVariables : stageVariables,
 	                                              cognitoIdentityId : cognitoIdentityId,
 	                                              httpMethod : httpMethod,
 	                                              sourceIp : sourceIp,
 	                                              userAgent : userAgent,
 	                                              requestId : requestId,
 	                                              resourcePath : resourcePath,
 	                                              userId: userID,
 	                                              verifiedPassword: password,
 	                                              verificationPassed: "true"
 	                                  };
   
 	                                  var response = {
 	                                              statusCode: responseCode,
 	                                              headers: {
                                                   "x-custom-header" : "custom header value"
 	                                              },
 	                                              body: JSON.stringify(responseBody)
 	                                  };
   
 	                                  console.log("response: " + JSON.stringify(response))
 	                                  context.succeed(response);
 	                                  callback(JSON.stringify(response));
 	                      }// end else passwords the same
 	             }//end else get successfull
 	           
 	          });
   
 console.log(params);


Results running when password is correct (the same as in database)

 

Results running when input password is not the same as in database - verificaiton failed

first lets change input in test data so it is not correct password

 

NOW --> when you integrate into your mobile application you will be processing the returned JSON object and note it has a field errorMessage = "Failed verification,..." which you can process

{

  "errorMessage": "Failed verification, passwords not the same",

  "errorType": "Error",

  "stackTrace": [

    "Response.<anonymous> (/var/task/index.js:159:22)",

    "Request.<anonymous> (/var/runtime/node_modules/aws-sdk/lib/request.js:355:18)",

    "Request.callListeners (/var/runtime/node_modules/aws-sdk/lib/sequential_executor.js:105:20)",

    "Request.emit (/var/runtime/node_modules/aws-sdk/lib/sequential_executor.js:77:10)",

    "Request.emit (/var/runtime/node_modules/aws-sdk/lib/request.js:668:14)",

    "Request.transition (/var/runtime/node_modules/aws-sdk/lib/request.js:22:10)",

    "AcceptorStateMachine.runTo (/var/runtime/node_modules/aws-sdk/lib/state_machine.js:14:12)",

    "/var/runtime/node_modules/aws-sdk/lib/state_machine.js:26:10",

    "Request.<anonymous> (/var/runtime/node_modules/aws-sdk/lib/request.js:38:9)",

    "Request.<anonymous> (/var/runtime/node_modules/aws-sdk/lib/request.js:670:12)"

  ]

}

 

 

 

Example testing if from AWS generated test app -

 

 

© Lynne Grewe