How should I pass variables from my external routes to a javascript controller in Node.js asynchronously?2019 Community Moderator ElectionHow do I remove a property from a JavaScript object?How do you check if a variable is an array in JavaScript?How do I pass command line arguments to a Node.js program?JavaScript, Node.js: is Array.forEach asynchronous?How do I remove a particular element from an array in JavaScript?In Node.js, how do I “include” functions from my other files?How to get GET (query string) variables in Express.js on Node.js?How do I completely uninstall Node.js, and reinstall from beginning (Mac OS X)How do I return the response from an asynchronous call?How to pass variables and data from PHP to JavaScript?

What do the pedals on grand pianos do?

How to deny access to SQL Server to certain login over SSMS, but allow over .Net SqlClient Data Provider

Accessing something inside the object when you don't know the key

Easy code troubleshooting in wordpress

How to speed up a process

What is better: yes / no radio, or simple checkbox?

Compare four integers, return word based on maximum

Where is this triangular-shaped space station from?

What is this waxed root vegetable?

What is the wife of a henpecked husband called?

Canadian citizen, on US no-fly list. What can I do in order to be allowed on flights which go through US airspace?

Can we carry rice to Japan?

Has the Isbell–Freyd criterion ever been used to check that a category is concretisable?

Do authors have to be politically correct in article-writing?

What to do when being responsible for data protection in your lab, yet advice is ignored?

Is there any relevance to Thor getting his hair cut other than comedic value?

Make me a metasequence

How can I be pwned if I'm not registered on that site?

What does 'open position for bachelor project' actually mean?

Linear regression when Y is bounded and discrete

Where was Karl Mordo in Infinity War?

Did Amazon pay $0 in taxes last year?

I can't die. Who am I?

What if I store 10TB on azure servers and then keep the vm powered off?



How should I pass variables from my external routes to a javascript controller in Node.js asynchronously?



2019 Community Moderator ElectionHow do I remove a property from a JavaScript object?How do you check if a variable is an array in JavaScript?How do I pass command line arguments to a Node.js program?JavaScript, Node.js: is Array.forEach asynchronous?How do I remove a particular element from an array in JavaScript?In Node.js, how do I “include” functions from my other files?How to get GET (query string) variables in Express.js on Node.js?How do I completely uninstall Node.js, and reinstall from beginning (Mac OS X)How do I return the response from an asynchronous call?How to pass variables and data from PHP to JavaScript?










0















My external routes is setup so that a POST form sends data to my server and my server file validates the input. It then takes this input and passes it to another file which will then perform authentication. I have a few questions regarding this, which are:



1) Do I need to pass the data asynchronously?
2) Is the way I am currently passing synchronous? Should it be changed
3) If I want to pass my variables into this file and it uses an async waterfall, (I believe I can't pass variables into the first function) should I create a main function which has two sub functions (one for storing the variables and one for executing the async waterfall)?



I am new to Node.js so have only just started learning the concept of asynchronous functionality. Any tips, help or questions, please let me know. If i have left something out please ask



My Server function is as such:



//Route for POST requests to Login
//First Sanitise input!
app.route('/login').post([
//ACCOUNTTYPE CHECKS -------------------------------------------------------------------------------
check('accountType').exists()
.trim()
.isAlpha()
.isLength(
min: 8,
max: 10
)
.matches(/(Production|Internal)/).withMessage('Must be either 'Production' or 'Internal'!')
.escape(),

//CUSTOMERID CHECKS --------------------------------------------------------------------------------
check('customerID').exists()
.trim()
.isNumeric()
.isInt()
.isLength(
max: 40
)
.escape(),

//CLIENTID CHECKS ---------------------
check('clientID').exists()
.trim()
.isAlphanumeric()
.isLength(
max: 40
)
.escape(),

//CLIENTSECRET CHECKS ---------------------
check('clientSecret').exists()
.trim()
.isAlphanumeric()
.isLength(
min: 0,
max: 45
)
.escape(),

//USERNAME CHECKS ---------------------
check('username').exists()
.trim()
.isEmail()
.isLength(
min: 0,
max: 100
)
.escape(),

//PASSWORD CHECKS ---------------------
check('password').exists()
.trim()
.isLength(
min: 0,
max: 100
)
.escape()
], urlencodedParser, (req, res) =>
let now = new Date().toString(),
log = `$now: $req.method $req.url`,
sess = req.session;

console.log(req.body);
fs.appendFile('server-requests.log', log + 'n', (err) =>
if (err)
console.log('Unable to append to server-requests.log!');

);

// Finds the validation errors in this request and wraps them in an object with handy functions
const errors = validationResult(req);
if (!errors.isEmpty())
//return a bad status and array of errors
//if the validation fails
// return res.status(422).json(
// errors: errors.array()
// );
//OR:
return res.render('login.hbs',
currentYear: new Date().getFullYear(),
//This does not work realtime - FIX TODO
currentTime: moment().format('MMMM Do YYYY - h:mm:ss a'),
data: ,
errors: errors.mapped()
);
// If there aren't any errors, proceed to save variable data and use 2.0
else
//Handle with event emiitters and make asynchronous - TODO
const data = matchedData(req);
console.log('Data stored in session:')
console.log('Sanitised:', data);

//Store Form Data in session variables
sess.accountType = data.accountType,
sess.customerID = data.customerID,
sess.clientID = data.clientID,
sess.clientSecret = data.clientSecret,
sess.username = data.username,
sess.password = data.password;


console.log('Sanitised POST Form! Now initialising request.');
req.flash('success', 'Successful POST request, proceeding to authorisation...)');

//Make asynchronous?
//use each function and get variables
auth.saveVariables(sess.accountType, sess.customerID, sess.clientID, sess.clientSecret, sess.username, sess.password);
auth.asyncWaterfall(callback)

res.redirect('/index');

//Or alternatively should it redirect with a query string?
// const url = require('url');
// app.get('/index', function (req, res)
// res.redirect(url.format(
// pathname: "/",
// query:
// "acccountType": 1,
// "customerID": 2,
// "clientID": 3,
// "clientSecret": 4,
// "username": 5,
// "password": 6
//
// ));
// );

)


Here is the start of my auth controller code:



 const saveVariables = (accountType, customerID, clientID, clientSecret, username, password, callback) => 

const test = (array) =>
array.forEach((field) =>
let errorString;
if (field.type() !== String)
errorString += `The field $field is not a String. Type: $field.`

return errorString;
)


//This const creates the auth URL and auth code grant URL. It also assigns the host URL.
const createAuthURL = (callback) =>
//If the paramter test passes then proceed
if (accountType === "Production")
try
let authURL = `https://$prodURL$url1`,
authCodeURL = `https://$prodURL$url2`,
host = prodURL;
catch (e)
console.log(`Error occurred when assigning url variables (Production). Error: $e`);
console.error('Error occurred when assigning url variables (Production). Error:', e);

else if (accountType === "Internal")
try
let authURL = `https://$internURL$url1`,
authCodeURL = `https://$internURL$url2`,
host = internURL;
catch (e)
console.log(`Error occurred when assigning url variables (Internal). Error: $e`);
console.error('Error occurred when assigning url variables (Internal). Error:', e);


else
console.log(`Bad String Input into auth URL! Entry: $accountType`);
console.error('Bad String Input into auth URL: ', accountType);



const asyncWaterfall = (req, res) =>
//Asynchronous Waterfall Call of 'Getting Access Tokens' (Stages 1-3)
async.waterfall([
getCookieData,
getAuthCode,
getAccessToken
], (err, result) =>
if (err)
alert('Something is wrong!');

return alert('Done!');
);

//STAGE 1 - USE CUSTOMER DETAILS TO RETRIEVE COOKIE AND CSRF SESSION DATA
getCookieData = async (callback) =>
//For testing purposes - Remove after development
console.log(`The type of account used is: $accountType`);
console.log(`The customerID used is: $customerID`);
console.log(`The clientID used is: $clientID`);
console.log(`The client secret used is: $clientSecret`);
console.log(`The username used is: $username`);
console.log(`The password used is: $password`);
console.log(`Making a URL request to: $authURL`);

//If the paramter test passes then proceed
var options =
//Type of HTTP request
method: 'POST',
//URI String
uri: authURL,
//HTTP Query Strings
qs:
'client_id': clientID
,
//HTTP Headers
headers:
'cache-control': 'no-cache',
'Accept': 'application/json',
'Host': host,
'Content-Type': 'application/json'
,
//HTTP Body
body:
'username': username,
'password': password
,
json: true // Automatically stringifies the body to JSON
//resolveWithFullResponse: true // Get the full response instead of just the body
//simple: false // Get a rejection only if the request failed for technical reasons
;
console.log(`Beginning HTTP POST Request to $authURL...`);

//await literally makes JavaScript wait until the promise settles, and then go on with the result.
await rp(options)
.then((parsedBody) =>
//POST Succeeded...
Console.log('Successful HTTP POST!');
try
let csrf = response.body('csrftoken'),
ses = response.body('session'),
sesk = `session=$ses`;
catch (e)
console.log(`STAGE 1 - Error occurred when assigning url variables. Error: $e`);
console.error('STAGE 1 - Error occurred when assigning url variables. Error:', e);

console.log(`Successful grab of the cookie: $ses and csrf token: $csrf. Getting authorisation code now!`);
//Asynchronous callback for the next function - return = defensive architecture
return callback(null, authCodeURL, customerID, clientID, csrf, sesk);
)
.catch((err) =>
if (res.statusCode == 400)
console.log(`Error Message: $res.body.message. Status: $res.body.status`);
console.error('Error Message:', res.body.message, 'Status:', res.body.status);
else if (res.statusCode == 401)
console.log(`Error Message: $res.body.message. Status: $res.body.status`);
console.error('Error Message:', res.body.message, 'Status:', res.body.status);
else
console.log(`Failed to retrieve the cookie data! Error: $error`);
console.error('Failed to retrieve the cookie data! Error:', error);

);
,

//STAGE 2 - USE COOKIES AND CSRF TOKEN TO GET AUTH CODE
//Is the word async needed? it is not asyncchronous but sequential
getAuthCode = async (authCodeURL, customerID, clientID, csrf, sesk, callback) => ,

//STAGE 3 - USE AUTH CODE TO GET ACCESS TOKEN
//ASYNC NEEDED?
getAccessToken = async (swapURL, clientID, clientSecret, authCode, callback) => authCode !== String)
let fields = [swapURL, clientSecret, clientID, authCode];
test(fields);


//If successful, proceed:
var options =
method: 'POST',
uri: swapURL,
qs:
'client_id': clientID,
'grant_type': 'authorization_code',
'client_secret': clientSecret,
'code': authCode
,
json: true // Automatically stringifies the body to JSON
;
console.log(`Beginning HTTP POST Request to $swapURL...`);

//await literally makes JavaScript wait until the promise settles, and then go on with the result.
await rp(options)
.then((parsedBody) =>
//POST Succeeded...
Console.log('Successful HTTP POST!');
try
let accessToken = response.body('access_token'),
refreshToken = response.body('refresh_token');
catch (e)
console.log(`STAGE 3 - Error occurred when assigning url variables. Error: $e`);
console.error('STAGE 3 - Error occurred when assigning url variables. Error:', e);

console.log(`The access Token is $accessToken and the refreshToken which is $refreshToken! These are only valid for 2 hours!`);
//Asynchronous callback for the waterfall - return = defensive architecture
return callback(null, 'done');
)
.catch((err) =>
console.log(`Failed to retrieve the access/refresh Token! Error: $error`);
console.error('Failed to retrieve the access/refresh Token! Error:', error);
);










share






















  • Why not using EventEmitter?

    – Cristian Traìna
    52 secs ago















0















My external routes is setup so that a POST form sends data to my server and my server file validates the input. It then takes this input and passes it to another file which will then perform authentication. I have a few questions regarding this, which are:



1) Do I need to pass the data asynchronously?
2) Is the way I am currently passing synchronous? Should it be changed
3) If I want to pass my variables into this file and it uses an async waterfall, (I believe I can't pass variables into the first function) should I create a main function which has two sub functions (one for storing the variables and one for executing the async waterfall)?



I am new to Node.js so have only just started learning the concept of asynchronous functionality. Any tips, help or questions, please let me know. If i have left something out please ask



My Server function is as such:



//Route for POST requests to Login
//First Sanitise input!
app.route('/login').post([
//ACCOUNTTYPE CHECKS -------------------------------------------------------------------------------
check('accountType').exists()
.trim()
.isAlpha()
.isLength(
min: 8,
max: 10
)
.matches(/(Production|Internal)/).withMessage('Must be either 'Production' or 'Internal'!')
.escape(),

//CUSTOMERID CHECKS --------------------------------------------------------------------------------
check('customerID').exists()
.trim()
.isNumeric()
.isInt()
.isLength(
max: 40
)
.escape(),

//CLIENTID CHECKS ---------------------
check('clientID').exists()
.trim()
.isAlphanumeric()
.isLength(
max: 40
)
.escape(),

//CLIENTSECRET CHECKS ---------------------
check('clientSecret').exists()
.trim()
.isAlphanumeric()
.isLength(
min: 0,
max: 45
)
.escape(),

//USERNAME CHECKS ---------------------
check('username').exists()
.trim()
.isEmail()
.isLength(
min: 0,
max: 100
)
.escape(),

//PASSWORD CHECKS ---------------------
check('password').exists()
.trim()
.isLength(
min: 0,
max: 100
)
.escape()
], urlencodedParser, (req, res) =>
let now = new Date().toString(),
log = `$now: $req.method $req.url`,
sess = req.session;

console.log(req.body);
fs.appendFile('server-requests.log', log + 'n', (err) =>
if (err)
console.log('Unable to append to server-requests.log!');

);

// Finds the validation errors in this request and wraps them in an object with handy functions
const errors = validationResult(req);
if (!errors.isEmpty())
//return a bad status and array of errors
//if the validation fails
// return res.status(422).json(
// errors: errors.array()
// );
//OR:
return res.render('login.hbs',
currentYear: new Date().getFullYear(),
//This does not work realtime - FIX TODO
currentTime: moment().format('MMMM Do YYYY - h:mm:ss a'),
data: ,
errors: errors.mapped()
);
// If there aren't any errors, proceed to save variable data and use 2.0
else
//Handle with event emiitters and make asynchronous - TODO
const data = matchedData(req);
console.log('Data stored in session:')
console.log('Sanitised:', data);

//Store Form Data in session variables
sess.accountType = data.accountType,
sess.customerID = data.customerID,
sess.clientID = data.clientID,
sess.clientSecret = data.clientSecret,
sess.username = data.username,
sess.password = data.password;


console.log('Sanitised POST Form! Now initialising request.');
req.flash('success', 'Successful POST request, proceeding to authorisation...)');

//Make asynchronous?
//use each function and get variables
auth.saveVariables(sess.accountType, sess.customerID, sess.clientID, sess.clientSecret, sess.username, sess.password);
auth.asyncWaterfall(callback)

res.redirect('/index');

//Or alternatively should it redirect with a query string?
// const url = require('url');
// app.get('/index', function (req, res)
// res.redirect(url.format(
// pathname: "/",
// query:
// "acccountType": 1,
// "customerID": 2,
// "clientID": 3,
// "clientSecret": 4,
// "username": 5,
// "password": 6
//
// ));
// );

)


Here is the start of my auth controller code:



 const saveVariables = (accountType, customerID, clientID, clientSecret, username, password, callback) => 

const test = (array) =>
array.forEach((field) =>
let errorString;
if (field.type() !== String)
errorString += `The field $field is not a String. Type: $field.`

return errorString;
)


//This const creates the auth URL and auth code grant URL. It also assigns the host URL.
const createAuthURL = (callback) =>
//If the paramter test passes then proceed
if (accountType === "Production")
try
let authURL = `https://$prodURL$url1`,
authCodeURL = `https://$prodURL$url2`,
host = prodURL;
catch (e)
console.log(`Error occurred when assigning url variables (Production). Error: $e`);
console.error('Error occurred when assigning url variables (Production). Error:', e);

else if (accountType === "Internal")
try
let authURL = `https://$internURL$url1`,
authCodeURL = `https://$internURL$url2`,
host = internURL;
catch (e)
console.log(`Error occurred when assigning url variables (Internal). Error: $e`);
console.error('Error occurred when assigning url variables (Internal). Error:', e);


else
console.log(`Bad String Input into auth URL! Entry: $accountType`);
console.error('Bad String Input into auth URL: ', accountType);



const asyncWaterfall = (req, res) =>
//Asynchronous Waterfall Call of 'Getting Access Tokens' (Stages 1-3)
async.waterfall([
getCookieData,
getAuthCode,
getAccessToken
], (err, result) =>
if (err)
alert('Something is wrong!');

return alert('Done!');
);

//STAGE 1 - USE CUSTOMER DETAILS TO RETRIEVE COOKIE AND CSRF SESSION DATA
getCookieData = async (callback) =>
//For testing purposes - Remove after development
console.log(`The type of account used is: $accountType`);
console.log(`The customerID used is: $customerID`);
console.log(`The clientID used is: $clientID`);
console.log(`The client secret used is: $clientSecret`);
console.log(`The username used is: $username`);
console.log(`The password used is: $password`);
console.log(`Making a URL request to: $authURL`);

//If the paramter test passes then proceed
var options =
//Type of HTTP request
method: 'POST',
//URI String
uri: authURL,
//HTTP Query Strings
qs:
'client_id': clientID
,
//HTTP Headers
headers:
'cache-control': 'no-cache',
'Accept': 'application/json',
'Host': host,
'Content-Type': 'application/json'
,
//HTTP Body
body:
'username': username,
'password': password
,
json: true // Automatically stringifies the body to JSON
//resolveWithFullResponse: true // Get the full response instead of just the body
//simple: false // Get a rejection only if the request failed for technical reasons
;
console.log(`Beginning HTTP POST Request to $authURL...`);

//await literally makes JavaScript wait until the promise settles, and then go on with the result.
await rp(options)
.then((parsedBody) =>
//POST Succeeded...
Console.log('Successful HTTP POST!');
try
let csrf = response.body('csrftoken'),
ses = response.body('session'),
sesk = `session=$ses`;
catch (e)
console.log(`STAGE 1 - Error occurred when assigning url variables. Error: $e`);
console.error('STAGE 1 - Error occurred when assigning url variables. Error:', e);

console.log(`Successful grab of the cookie: $ses and csrf token: $csrf. Getting authorisation code now!`);
//Asynchronous callback for the next function - return = defensive architecture
return callback(null, authCodeURL, customerID, clientID, csrf, sesk);
)
.catch((err) =>
if (res.statusCode == 400)
console.log(`Error Message: $res.body.message. Status: $res.body.status`);
console.error('Error Message:', res.body.message, 'Status:', res.body.status);
else if (res.statusCode == 401)
console.log(`Error Message: $res.body.message. Status: $res.body.status`);
console.error('Error Message:', res.body.message, 'Status:', res.body.status);
else
console.log(`Failed to retrieve the cookie data! Error: $error`);
console.error('Failed to retrieve the cookie data! Error:', error);

);
,

//STAGE 2 - USE COOKIES AND CSRF TOKEN TO GET AUTH CODE
//Is the word async needed? it is not asyncchronous but sequential
getAuthCode = async (authCodeURL, customerID, clientID, csrf, sesk, callback) => ,

//STAGE 3 - USE AUTH CODE TO GET ACCESS TOKEN
//ASYNC NEEDED?
getAccessToken = async (swapURL, clientID, clientSecret, authCode, callback) => authCode !== String)
let fields = [swapURL, clientSecret, clientID, authCode];
test(fields);


//If successful, proceed:
var options =
method: 'POST',
uri: swapURL,
qs:
'client_id': clientID,
'grant_type': 'authorization_code',
'client_secret': clientSecret,
'code': authCode
,
json: true // Automatically stringifies the body to JSON
;
console.log(`Beginning HTTP POST Request to $swapURL...`);

//await literally makes JavaScript wait until the promise settles, and then go on with the result.
await rp(options)
.then((parsedBody) =>
//POST Succeeded...
Console.log('Successful HTTP POST!');
try
let accessToken = response.body('access_token'),
refreshToken = response.body('refresh_token');
catch (e)
console.log(`STAGE 3 - Error occurred when assigning url variables. Error: $e`);
console.error('STAGE 3 - Error occurred when assigning url variables. Error:', e);

console.log(`The access Token is $accessToken and the refreshToken which is $refreshToken! These are only valid for 2 hours!`);
//Asynchronous callback for the waterfall - return = defensive architecture
return callback(null, 'done');
)
.catch((err) =>
console.log(`Failed to retrieve the access/refresh Token! Error: $error`);
console.error('Failed to retrieve the access/refresh Token! Error:', error);
);










share






















  • Why not using EventEmitter?

    – Cristian Traìna
    52 secs ago













0












0








0








My external routes is setup so that a POST form sends data to my server and my server file validates the input. It then takes this input and passes it to another file which will then perform authentication. I have a few questions regarding this, which are:



1) Do I need to pass the data asynchronously?
2) Is the way I am currently passing synchronous? Should it be changed
3) If I want to pass my variables into this file and it uses an async waterfall, (I believe I can't pass variables into the first function) should I create a main function which has two sub functions (one for storing the variables and one for executing the async waterfall)?



I am new to Node.js so have only just started learning the concept of asynchronous functionality. Any tips, help or questions, please let me know. If i have left something out please ask



My Server function is as such:



//Route for POST requests to Login
//First Sanitise input!
app.route('/login').post([
//ACCOUNTTYPE CHECKS -------------------------------------------------------------------------------
check('accountType').exists()
.trim()
.isAlpha()
.isLength(
min: 8,
max: 10
)
.matches(/(Production|Internal)/).withMessage('Must be either 'Production' or 'Internal'!')
.escape(),

//CUSTOMERID CHECKS --------------------------------------------------------------------------------
check('customerID').exists()
.trim()
.isNumeric()
.isInt()
.isLength(
max: 40
)
.escape(),

//CLIENTID CHECKS ---------------------
check('clientID').exists()
.trim()
.isAlphanumeric()
.isLength(
max: 40
)
.escape(),

//CLIENTSECRET CHECKS ---------------------
check('clientSecret').exists()
.trim()
.isAlphanumeric()
.isLength(
min: 0,
max: 45
)
.escape(),

//USERNAME CHECKS ---------------------
check('username').exists()
.trim()
.isEmail()
.isLength(
min: 0,
max: 100
)
.escape(),

//PASSWORD CHECKS ---------------------
check('password').exists()
.trim()
.isLength(
min: 0,
max: 100
)
.escape()
], urlencodedParser, (req, res) =>
let now = new Date().toString(),
log = `$now: $req.method $req.url`,
sess = req.session;

console.log(req.body);
fs.appendFile('server-requests.log', log + 'n', (err) =>
if (err)
console.log('Unable to append to server-requests.log!');

);

// Finds the validation errors in this request and wraps them in an object with handy functions
const errors = validationResult(req);
if (!errors.isEmpty())
//return a bad status and array of errors
//if the validation fails
// return res.status(422).json(
// errors: errors.array()
// );
//OR:
return res.render('login.hbs',
currentYear: new Date().getFullYear(),
//This does not work realtime - FIX TODO
currentTime: moment().format('MMMM Do YYYY - h:mm:ss a'),
data: ,
errors: errors.mapped()
);
// If there aren't any errors, proceed to save variable data and use 2.0
else
//Handle with event emiitters and make asynchronous - TODO
const data = matchedData(req);
console.log('Data stored in session:')
console.log('Sanitised:', data);

//Store Form Data in session variables
sess.accountType = data.accountType,
sess.customerID = data.customerID,
sess.clientID = data.clientID,
sess.clientSecret = data.clientSecret,
sess.username = data.username,
sess.password = data.password;


console.log('Sanitised POST Form! Now initialising request.');
req.flash('success', 'Successful POST request, proceeding to authorisation...)');

//Make asynchronous?
//use each function and get variables
auth.saveVariables(sess.accountType, sess.customerID, sess.clientID, sess.clientSecret, sess.username, sess.password);
auth.asyncWaterfall(callback)

res.redirect('/index');

//Or alternatively should it redirect with a query string?
// const url = require('url');
// app.get('/index', function (req, res)
// res.redirect(url.format(
// pathname: "/",
// query:
// "acccountType": 1,
// "customerID": 2,
// "clientID": 3,
// "clientSecret": 4,
// "username": 5,
// "password": 6
//
// ));
// );

)


Here is the start of my auth controller code:



 const saveVariables = (accountType, customerID, clientID, clientSecret, username, password, callback) => 

const test = (array) =>
array.forEach((field) =>
let errorString;
if (field.type() !== String)
errorString += `The field $field is not a String. Type: $field.`

return errorString;
)


//This const creates the auth URL and auth code grant URL. It also assigns the host URL.
const createAuthURL = (callback) =>
//If the paramter test passes then proceed
if (accountType === "Production")
try
let authURL = `https://$prodURL$url1`,
authCodeURL = `https://$prodURL$url2`,
host = prodURL;
catch (e)
console.log(`Error occurred when assigning url variables (Production). Error: $e`);
console.error('Error occurred when assigning url variables (Production). Error:', e);

else if (accountType === "Internal")
try
let authURL = `https://$internURL$url1`,
authCodeURL = `https://$internURL$url2`,
host = internURL;
catch (e)
console.log(`Error occurred when assigning url variables (Internal). Error: $e`);
console.error('Error occurred when assigning url variables (Internal). Error:', e);


else
console.log(`Bad String Input into auth URL! Entry: $accountType`);
console.error('Bad String Input into auth URL: ', accountType);



const asyncWaterfall = (req, res) =>
//Asynchronous Waterfall Call of 'Getting Access Tokens' (Stages 1-3)
async.waterfall([
getCookieData,
getAuthCode,
getAccessToken
], (err, result) =>
if (err)
alert('Something is wrong!');

return alert('Done!');
);

//STAGE 1 - USE CUSTOMER DETAILS TO RETRIEVE COOKIE AND CSRF SESSION DATA
getCookieData = async (callback) =>
//For testing purposes - Remove after development
console.log(`The type of account used is: $accountType`);
console.log(`The customerID used is: $customerID`);
console.log(`The clientID used is: $clientID`);
console.log(`The client secret used is: $clientSecret`);
console.log(`The username used is: $username`);
console.log(`The password used is: $password`);
console.log(`Making a URL request to: $authURL`);

//If the paramter test passes then proceed
var options =
//Type of HTTP request
method: 'POST',
//URI String
uri: authURL,
//HTTP Query Strings
qs:
'client_id': clientID
,
//HTTP Headers
headers:
'cache-control': 'no-cache',
'Accept': 'application/json',
'Host': host,
'Content-Type': 'application/json'
,
//HTTP Body
body:
'username': username,
'password': password
,
json: true // Automatically stringifies the body to JSON
//resolveWithFullResponse: true // Get the full response instead of just the body
//simple: false // Get a rejection only if the request failed for technical reasons
;
console.log(`Beginning HTTP POST Request to $authURL...`);

//await literally makes JavaScript wait until the promise settles, and then go on with the result.
await rp(options)
.then((parsedBody) =>
//POST Succeeded...
Console.log('Successful HTTP POST!');
try
let csrf = response.body('csrftoken'),
ses = response.body('session'),
sesk = `session=$ses`;
catch (e)
console.log(`STAGE 1 - Error occurred when assigning url variables. Error: $e`);
console.error('STAGE 1 - Error occurred when assigning url variables. Error:', e);

console.log(`Successful grab of the cookie: $ses and csrf token: $csrf. Getting authorisation code now!`);
//Asynchronous callback for the next function - return = defensive architecture
return callback(null, authCodeURL, customerID, clientID, csrf, sesk);
)
.catch((err) =>
if (res.statusCode == 400)
console.log(`Error Message: $res.body.message. Status: $res.body.status`);
console.error('Error Message:', res.body.message, 'Status:', res.body.status);
else if (res.statusCode == 401)
console.log(`Error Message: $res.body.message. Status: $res.body.status`);
console.error('Error Message:', res.body.message, 'Status:', res.body.status);
else
console.log(`Failed to retrieve the cookie data! Error: $error`);
console.error('Failed to retrieve the cookie data! Error:', error);

);
,

//STAGE 2 - USE COOKIES AND CSRF TOKEN TO GET AUTH CODE
//Is the word async needed? it is not asyncchronous but sequential
getAuthCode = async (authCodeURL, customerID, clientID, csrf, sesk, callback) => ,

//STAGE 3 - USE AUTH CODE TO GET ACCESS TOKEN
//ASYNC NEEDED?
getAccessToken = async (swapURL, clientID, clientSecret, authCode, callback) => authCode !== String)
let fields = [swapURL, clientSecret, clientID, authCode];
test(fields);


//If successful, proceed:
var options =
method: 'POST',
uri: swapURL,
qs:
'client_id': clientID,
'grant_type': 'authorization_code',
'client_secret': clientSecret,
'code': authCode
,
json: true // Automatically stringifies the body to JSON
;
console.log(`Beginning HTTP POST Request to $swapURL...`);

//await literally makes JavaScript wait until the promise settles, and then go on with the result.
await rp(options)
.then((parsedBody) =>
//POST Succeeded...
Console.log('Successful HTTP POST!');
try
let accessToken = response.body('access_token'),
refreshToken = response.body('refresh_token');
catch (e)
console.log(`STAGE 3 - Error occurred when assigning url variables. Error: $e`);
console.error('STAGE 3 - Error occurred when assigning url variables. Error:', e);

console.log(`The access Token is $accessToken and the refreshToken which is $refreshToken! These are only valid for 2 hours!`);
//Asynchronous callback for the waterfall - return = defensive architecture
return callback(null, 'done');
)
.catch((err) =>
console.log(`Failed to retrieve the access/refresh Token! Error: $error`);
console.error('Failed to retrieve the access/refresh Token! Error:', error);
);










share














My external routes is setup so that a POST form sends data to my server and my server file validates the input. It then takes this input and passes it to another file which will then perform authentication. I have a few questions regarding this, which are:



1) Do I need to pass the data asynchronously?
2) Is the way I am currently passing synchronous? Should it be changed
3) If I want to pass my variables into this file and it uses an async waterfall, (I believe I can't pass variables into the first function) should I create a main function which has two sub functions (one for storing the variables and one for executing the async waterfall)?



I am new to Node.js so have only just started learning the concept of asynchronous functionality. Any tips, help or questions, please let me know. If i have left something out please ask



My Server function is as such:



//Route for POST requests to Login
//First Sanitise input!
app.route('/login').post([
//ACCOUNTTYPE CHECKS -------------------------------------------------------------------------------
check('accountType').exists()
.trim()
.isAlpha()
.isLength(
min: 8,
max: 10
)
.matches(/(Production|Internal)/).withMessage('Must be either 'Production' or 'Internal'!')
.escape(),

//CUSTOMERID CHECKS --------------------------------------------------------------------------------
check('customerID').exists()
.trim()
.isNumeric()
.isInt()
.isLength(
max: 40
)
.escape(),

//CLIENTID CHECKS ---------------------
check('clientID').exists()
.trim()
.isAlphanumeric()
.isLength(
max: 40
)
.escape(),

//CLIENTSECRET CHECKS ---------------------
check('clientSecret').exists()
.trim()
.isAlphanumeric()
.isLength(
min: 0,
max: 45
)
.escape(),

//USERNAME CHECKS ---------------------
check('username').exists()
.trim()
.isEmail()
.isLength(
min: 0,
max: 100
)
.escape(),

//PASSWORD CHECKS ---------------------
check('password').exists()
.trim()
.isLength(
min: 0,
max: 100
)
.escape()
], urlencodedParser, (req, res) =>
let now = new Date().toString(),
log = `$now: $req.method $req.url`,
sess = req.session;

console.log(req.body);
fs.appendFile('server-requests.log', log + 'n', (err) =>
if (err)
console.log('Unable to append to server-requests.log!');

);

// Finds the validation errors in this request and wraps them in an object with handy functions
const errors = validationResult(req);
if (!errors.isEmpty())
//return a bad status and array of errors
//if the validation fails
// return res.status(422).json(
// errors: errors.array()
// );
//OR:
return res.render('login.hbs',
currentYear: new Date().getFullYear(),
//This does not work realtime - FIX TODO
currentTime: moment().format('MMMM Do YYYY - h:mm:ss a'),
data: ,
errors: errors.mapped()
);
// If there aren't any errors, proceed to save variable data and use 2.0
else
//Handle with event emiitters and make asynchronous - TODO
const data = matchedData(req);
console.log('Data stored in session:')
console.log('Sanitised:', data);

//Store Form Data in session variables
sess.accountType = data.accountType,
sess.customerID = data.customerID,
sess.clientID = data.clientID,
sess.clientSecret = data.clientSecret,
sess.username = data.username,
sess.password = data.password;


console.log('Sanitised POST Form! Now initialising request.');
req.flash('success', 'Successful POST request, proceeding to authorisation...)');

//Make asynchronous?
//use each function and get variables
auth.saveVariables(sess.accountType, sess.customerID, sess.clientID, sess.clientSecret, sess.username, sess.password);
auth.asyncWaterfall(callback)

res.redirect('/index');

//Or alternatively should it redirect with a query string?
// const url = require('url');
// app.get('/index', function (req, res)
// res.redirect(url.format(
// pathname: "/",
// query:
// "acccountType": 1,
// "customerID": 2,
// "clientID": 3,
// "clientSecret": 4,
// "username": 5,
// "password": 6
//
// ));
// );

)


Here is the start of my auth controller code:



 const saveVariables = (accountType, customerID, clientID, clientSecret, username, password, callback) => 

const test = (array) =>
array.forEach((field) =>
let errorString;
if (field.type() !== String)
errorString += `The field $field is not a String. Type: $field.`

return errorString;
)


//This const creates the auth URL and auth code grant URL. It also assigns the host URL.
const createAuthURL = (callback) =>
//If the paramter test passes then proceed
if (accountType === "Production")
try
let authURL = `https://$prodURL$url1`,
authCodeURL = `https://$prodURL$url2`,
host = prodURL;
catch (e)
console.log(`Error occurred when assigning url variables (Production). Error: $e`);
console.error('Error occurred when assigning url variables (Production). Error:', e);

else if (accountType === "Internal")
try
let authURL = `https://$internURL$url1`,
authCodeURL = `https://$internURL$url2`,
host = internURL;
catch (e)
console.log(`Error occurred when assigning url variables (Internal). Error: $e`);
console.error('Error occurred when assigning url variables (Internal). Error:', e);


else
console.log(`Bad String Input into auth URL! Entry: $accountType`);
console.error('Bad String Input into auth URL: ', accountType);



const asyncWaterfall = (req, res) =>
//Asynchronous Waterfall Call of 'Getting Access Tokens' (Stages 1-3)
async.waterfall([
getCookieData,
getAuthCode,
getAccessToken
], (err, result) =>
if (err)
alert('Something is wrong!');

return alert('Done!');
);

//STAGE 1 - USE CUSTOMER DETAILS TO RETRIEVE COOKIE AND CSRF SESSION DATA
getCookieData = async (callback) =>
//For testing purposes - Remove after development
console.log(`The type of account used is: $accountType`);
console.log(`The customerID used is: $customerID`);
console.log(`The clientID used is: $clientID`);
console.log(`The client secret used is: $clientSecret`);
console.log(`The username used is: $username`);
console.log(`The password used is: $password`);
console.log(`Making a URL request to: $authURL`);

//If the paramter test passes then proceed
var options =
//Type of HTTP request
method: 'POST',
//URI String
uri: authURL,
//HTTP Query Strings
qs:
'client_id': clientID
,
//HTTP Headers
headers:
'cache-control': 'no-cache',
'Accept': 'application/json',
'Host': host,
'Content-Type': 'application/json'
,
//HTTP Body
body:
'username': username,
'password': password
,
json: true // Automatically stringifies the body to JSON
//resolveWithFullResponse: true // Get the full response instead of just the body
//simple: false // Get a rejection only if the request failed for technical reasons
;
console.log(`Beginning HTTP POST Request to $authURL...`);

//await literally makes JavaScript wait until the promise settles, and then go on with the result.
await rp(options)
.then((parsedBody) =>
//POST Succeeded...
Console.log('Successful HTTP POST!');
try
let csrf = response.body('csrftoken'),
ses = response.body('session'),
sesk = `session=$ses`;
catch (e)
console.log(`STAGE 1 - Error occurred when assigning url variables. Error: $e`);
console.error('STAGE 1 - Error occurred when assigning url variables. Error:', e);

console.log(`Successful grab of the cookie: $ses and csrf token: $csrf. Getting authorisation code now!`);
//Asynchronous callback for the next function - return = defensive architecture
return callback(null, authCodeURL, customerID, clientID, csrf, sesk);
)
.catch((err) =>
if (res.statusCode == 400)
console.log(`Error Message: $res.body.message. Status: $res.body.status`);
console.error('Error Message:', res.body.message, 'Status:', res.body.status);
else if (res.statusCode == 401)
console.log(`Error Message: $res.body.message. Status: $res.body.status`);
console.error('Error Message:', res.body.message, 'Status:', res.body.status);
else
console.log(`Failed to retrieve the cookie data! Error: $error`);
console.error('Failed to retrieve the cookie data! Error:', error);

);
,

//STAGE 2 - USE COOKIES AND CSRF TOKEN TO GET AUTH CODE
//Is the word async needed? it is not asyncchronous but sequential
getAuthCode = async (authCodeURL, customerID, clientID, csrf, sesk, callback) => ,

//STAGE 3 - USE AUTH CODE TO GET ACCESS TOKEN
//ASYNC NEEDED?
getAccessToken = async (swapURL, clientID, clientSecret, authCode, callback) => authCode !== String)
let fields = [swapURL, clientSecret, clientID, authCode];
test(fields);


//If successful, proceed:
var options =
method: 'POST',
uri: swapURL,
qs:
'client_id': clientID,
'grant_type': 'authorization_code',
'client_secret': clientSecret,
'code': authCode
,
json: true // Automatically stringifies the body to JSON
;
console.log(`Beginning HTTP POST Request to $swapURL...`);

//await literally makes JavaScript wait until the promise settles, and then go on with the result.
await rp(options)
.then((parsedBody) =>
//POST Succeeded...
Console.log('Successful HTTP POST!');
try
let accessToken = response.body('access_token'),
refreshToken = response.body('refresh_token');
catch (e)
console.log(`STAGE 3 - Error occurred when assigning url variables. Error: $e`);
console.error('STAGE 3 - Error occurred when assigning url variables. Error:', e);

console.log(`The access Token is $accessToken and the refreshToken which is $refreshToken! These are only valid for 2 hours!`);
//Asynchronous callback for the waterfall - return = defensive architecture
return callback(null, 'done');
)
.catch((err) =>
console.log(`Failed to retrieve the access/refresh Token! Error: $error`);
console.error('Failed to retrieve the access/refresh Token! Error:', error);
);








javascript node.js asynchronous





share












share










share



share










asked 2 mins ago









aidan22aidan22

168




168












  • Why not using EventEmitter?

    – Cristian Traìna
    52 secs ago

















  • Why not using EventEmitter?

    – Cristian Traìna
    52 secs ago
















Why not using EventEmitter?

– Cristian Traìna
52 secs ago





Why not using EventEmitter?

– Cristian Traìna
52 secs ago












0






active

oldest

votes











Your Answer






StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");

StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);

else
createEditor();

);

function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);



);













draft saved

draft discarded


















StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55002002%2fhow-should-i-pass-variables-from-my-external-routes-to-a-javascript-controller-i%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown

























0






active

oldest

votes








0






active

oldest

votes









active

oldest

votes






active

oldest

votes















draft saved

draft discarded
















































Thanks for contributing an answer to Stack Overflow!


  • Please be sure to answer the question. Provide details and share your research!

But avoid …


  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55002002%2fhow-should-i-pass-variables-from-my-external-routes-to-a-javascript-controller-i%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







這個網誌中的熱門文章

Runtime problems in TestNG asserts2019 Community Moderator ElectionHow do you assert that a certain exception is thrown in JUnit 4 tests?differences between 2 JUnit Assert classesHow do I use Assert to verify that an exception has been thrown?Best practice for Python assertWhat is the “assert” function?What does the Java assert keyword do, and when should it be used?What is the use of “assert” in Python?PHPUnit assert that an exception was thrown?What is “assert” in JavaScript?Asserting in testng using containing

(unchecked) unchecked cast required: OnSuccessListener found: Uri2019 Community Moderator ElectionHow do I address unchecked cast warnings?Android AlarmManager for periodical sensor readingWhy don't Java's +=, -=, *=, /= compound assignment operators require casting?I am trying to set alarm on specific time using alarm manager but alarm initiated instantly?setText on button from another activity androidget around of error 'can not resolve symbol'Saving ToggleButton state in ListView by using SharedPreferencesAdding Social Media Share Logic From Firebase in Androidjava.lang.NullPointerException when invoking onLoadFinished()Search Firestore query don't show data in RecycleView

1