How to extract a parsed email address from a LinkedIn API response? - javascript

I'm trying to setup a custom Auth0 LinkedIn Connection.
This is what I have for the Fetch User Profile Script:
function fetchUserProfile(accessToken, context, callback) {
//Create the profile object
const profile = {
user_id: '',
given_name: '',
family_name: '',
email: '',
};
// Call the Linkedin Primary Contact API
request.get(
{
url: 'https://api.linkedin.com/v2/me',
headers: {
'Authorization': 'Bearer ' + accessToken,
}
},
(err, resp, body) => {
if (err) {
return callback(err);
}
if (resp.statusCode !== 200) {
return callback(new Error(body));
}
let bodyParsed;
try {
bodyParsed = JSON.parse(body);
} catch (jsonError) {
return callback(new Error(body));
}
profile.user_id = bodyParsed.id;
profile.given_name = bodyParsed.localizedFirstName;
profile.family_name = bodyParsed.localizedLastName;
}
);
// Call the Linkedin Profile API
request.get(
{
url: 'https://api.linkedin.com/v2/clientAwareMemberHandles?q=members&projection=(elements*(primary,type,handle~))',
headers: {
'Authorization': 'Bearer ' + accessToken,
}
},
(err, resp, body) => {
if (err) {
return callback(err);
}
if (resp.statusCode !== 200) {
return callback(new Error(body));
}
let bodyParsed;
try {
bodyParsed = JSON.parse(body);
} catch (jsonError) {
return callback(new Error(body));
}
console.log(body);
profile.email = bodyParsed.elements.handle~.emailAddress;
}
);
//Send the profile object to the callback
callback(null, profile);
}
It works (almost) but I'm having trouble putting emailAddress into the profile object.
The console.log(body); returns something like this (email redacted):
{
"elements":[
{
"handle":"urn:li:emailAddress:102319820",
"type":"EMAIL",
"handle~":{
"emailAddress":"REDACTED#gmail.com"
},
"primary":true
}
]
}
The problem is that profile.email = bodyParsed.elements.handle~.emailAddress; gives an error because it uses the ~ symbol.
So how do I access emailAddress and insert it into the profile object?

Related

How to delete a forge bucket from Autodesk forge

I am successfully creating Bucket and uploadFile successfully using sample.
https://github.com/Autodesk-Forge/forge-extensions
I added the delete function
But when I delete the bucket I get an error.
----oss.js---
router.post('/buckets', async (req, res, next) => {
let payload = new PostBucketsPayload();
payload.bucketKey = config.credentials.client_id.toLowerCase() + '-' + req.body.bucketKey;
payload.policyKey = 'transient'; // expires in 24h
try {
// Create a bucket using [BucketsApi](https://github.com/Autodesk-Forge/forge-api-nodejs-client/blob/master/docs/BucketsApi.md#createBucket).
//Bucket createBucket(postBuckets, opts, oauth2client, credentials)
await new BucketsApi().createBucket(payload, {}, req.oauth_client, req.oauth_token);
res.status(200).end();
} catch(err) {
next(err);
}
});
router.delete('/buckets/delete', async (req, res, next) => {
const encoded_bucketKey = encodeURI(req.bucketKeyID);
try {
// Delete a bucket using
await new BucketsApi().deleteBucket(encoded_bucketKey, req.oauth_client, req.oauth_token);
res.status(200).end();
} catch(err) {
next(err);
}
});
-----------ForgeTree.js -------
function createNewBucket() {
var bucketKey = $('#newBucketKey').val();
var policyKey = $('#newBucketPolicyKey').val();
jQuery.post({
url: '/api/forge/oss/buckets',
contentType: 'application/json',
data: JSON.stringify({ 'bucketKey': bucketKey, 'policyKey': policyKey }),
success: function (res) {
$('#appBuckets').jstree(true).refresh();
$('#createBucketModal').modal('toggle');
},
error: function (err) {
if (err.status == 409)
alert('Bucket already exists - 409: Duplicated')
console.log(err);
}
});
}
function deleteBucket() {
var node = $('#appBuckets').jstree(true).get_selected(true)[0];
switch (node.type) {
case 'bucket':
jQuery.ajax({
url: '/api/forge/oss/buckets/delete',
type:'delete',
contentType: 'application/json',
data: JSON.stringify({ 'bucketKey': node.text , 'bucketKeyID' : node.id}),
success: function (res) {
$('#appBuckets').jstree(true).refresh();
},
error: function (err) {
alert('Bucket delete error:')
console.log(err);
}
});
break;
}
console.log("Delete Bucket=%j", node)
}
I checked the config.js in the sample, it doesn't include bucket:delete scope when acquiring the token by default. Have you added the scope in your code?
Also inside delete route,
const encoded_bucketKey = encodeURI(req.bucketKeyID);
should be
const encoded_bucketKey = encodeURI(req.body.bucketKeyID);
Otherwise, you'll have undefined as encoded_bucketKey.

Async/Await Method Issue

I am working on MERN Stack Application(Mean,Express,ReactJS,NodeJS). I have one issue is that I have many more methods in mlcontroller.js page and I call some methods on REST API so I call that methods under that API from mlrouter.js but all that API is Async so currently API takes data slots vise means I give u an example that in one time take 100 data from first method and then pass to another method and pass from all methods again come to first method and take next 100 data and repeat same process again but I need to take all data in one time means untill one method will not complete not move on another method how's that possible with node js?
I place my code here :
mlrouter.js
ensureApiAuthenticated,
authController.checkReadOnlyUser,
mlController.getAPIData,
mlController.getData,
mlController.getCRCDetails,
mlController.getDetails,
mlController.uploadData
)
MlController.js
async function getAPIData(req, res, next) {
try {
let loanboardapi = " ", dealersocket = " ";
loanboardapi = {
url: "https://loanboard.houstondirectauto.com/api/User/GetAuthorizationToken?username=amin#houstondirectauto.com&password=test#123",
method: "GET"
};
dealersocket = {
url: 'https://idms.dealersocket.com/api/authenticate/GetUserAuthorizationToken?username=ankur#houstondirectauto.com&password=H5d465#!ddfdd45dsfd688&InstitutionID=105815',
method: 'GET'
};
request(loanboardapi,
(err, res, body) => {
console.log("res = ", res);
console.log("body =", body);
loantoken = JSON.parse(body).token;
console.log(loantoken);
});
request(dealersocket,
(err, res, body) => {
console.log("res = ", res);
console.log("body =", body);
dealertoken = JSON.parse(body).Token;
console.log(dealertoken);
next();
});
}
catch (e) {
req.error = e;
next();
}
}
function getData(req, res, next) {
try {
let result;
request.get('https://idms.dealersocket.com/api/account/getaccountlist?token=' + dealertoken + '&LayoutID=2002313&PageNumber=1&accounttype=i&accountstatus=a,c,b,o,r,s,x',
(err, res, body) => {
console.log("res = ", res);
console.log("body =", body);
result = JSON.parse(body);
console.log(result);
totalpage = parseInt(result.TotalPages);
let resultdata = Object.assign({}, result.Data);
console.log(resultdata);
//getSSN(totalpage, dealertoken, next);
next();
})
}
catch (e) {
req.error = e;
next();
}
}
async function getCRCDetails(req,res,next) {
async.eachSeries(ssn, async (item) => {
let CBCOptions = {
method: "POST",
url: "https://loanboard.houstondirectauto.com/api/Report",
headers: {
"Content-Type": "application/json",
Cookie: "ci_session=udmojmlc5tfl3epbrmtvgu6nao2f031p",
},
body: JSON.stringify({
token: loantoken,
action: "CBCReport",
variables: {
ssn: item,
},
}),
};
let EMpInfoption = {
method: "POST",
url: "https://loanboard.houstondirectauto.com/api/Report",
headers: {
"Content-Type": "application/json",
Cookie: "ci_session=udmojmlc5tfl3epbrmtvgu6nao2f031p",
},
body: JSON.stringify({
token: loantoken,
action: "getEmployerInfo",
variables: {
ssn: item,
},
}),
};
try {
let resultCBCOptions = await requestpromise(CBCOptions);
let EmployerInfoOptions = await requestpromise(EMpInfoption);
console.log(resultCBCOptions)
console.log(EmployerInfoOptions)
CRCOptions.push(resultCBCOptions);
EmpOption.push(EmployerInfoOptions);
} catch (error) {
console.log(error);
}
},
() => {
next();
}
);
}
async function getDetails(req,res,next) {
for(let i =0;i<CRCOptions.length;i++){
for(let j=0;j<EmpOption.length;j++){
let resdata = JSON.parse(CRCOptions[i]);
console.log(resdata);
result = resdata.data.DigifiResponse;
console.log(result);
let bodydata = JSON.parse(EmpOption[i]).data;
let crcssn = JSON.parse(CRCOptions[i]).ssn;
let empssn = JSON.parse(EmpOption[i]).ssn;
console.log("CRCSSN=",crcssn);
console.log("EMPSSN=",empssn);
if(crcssn == empssn)
{
for(let r=0;r<result.length;r++){
let crcdata = result[r];
console.log(crcdata);
for(let b=0;b<bodydata.length;b++) {
let annual_income;
console.log(bodydata[b]);
let mergedata = Object.assign(crcdata, bodydata[b]);
console.log("merge", mergedata);
if (mergedata["IncomeFrequency"] == "Monthly") {
annual_income = (parseInt(mergedata["Income"]) * 12).toString();
console.log(annual_income);
}
else {
annual_income = mergedata["Income"];
}
let binary = {
"accounts_opened": mergedata["total_number_of_open_accounts"],
"bankruptcies": mergedata["total_number_of_bankruptcies"],
"collections": mergedata["total_number_of_collections"],
"credit_inquiries_last_6_months": mergedata["total_number_of_inquires_in_the_last_6_months"],
"past_due_accounts": mergedata["total_number_of_accounts_currently_past_due"],
"open_accounts": mergedata["total_number_of_open_accounts"],
"high_credit_limit": mergedata["total_credit_limit_amount"],
"annual_income": annual_income
}
console.log(binary);
let arraybinary = Object.assign({},binary);
console.log(arraybinary);
binarydata.push(arraybinary);
console.log(binarydata);
let categorical = {
"bankruptcies_last_18_months": mergedata["count_of_bankruptcies_last_24_months"],
"credit_inquiries_last_6_months": mergedata["count_of_auto_loan_inquiries_last_9_months"],
"months_since_most_recent_inquiry": mergedata["total_number_of_inquires_in_the_last_6_months"],
"ninety_plus_delinquencies_last_18_months": mergedata["total_number_of_accounts_with_90180_day_delinquencies"],
"number_of_accounts_currently_30dpd": mergedata["total_number_of_accounts_with_3059_day_delinquencies"],
"open_credit_accounts": mergedata["total_number_of_open_auto_accounts"],
"pre_loan_debt_to_income": mergedata["total_amount_of_credit_debt"],
"total_current_balance": mergedata["total_account_balance"],
"total_high_credit_limit": mergedata["total_credit_limit_amount"],
"annual_income": annual_income
}
console.log(categorical);
let arraycategory = Object.assign({},categorical);
console.log(arraycategory);
categoricaldata.push(arraycategory);
let Linear = {
"bankruptcies_last_18_months": mergedata["count_of_bankruptcies_last_24_months"],
"credit_inquiries_last_6_months": mergedata["count_of_auto_loan_inquiries_last_9_months"],
"months_since_most_recent_inquiry": mergedata["total_number_of_inquires_in_the_last_6_months"],
"ninety_plus_delinquencies_last_18_months": mergedata["total_number_of_accounts_with_90180_day_delinquencies"],
"number_of_accounts_currently_30dpd": mergedata["total_number_of_accounts_with_3059_day_delinquencies"],
"open_credit_accounts": mergedata["total_number_of_open_auto_accounts"],
"pre_loan_debt_to_income": mergedata["total_amount_of_credit_debt"],
"total_current_balance": mergedata["total_account_balance"],
"total_high_credit_limit": mergedata["total_credit_limit_amount"],
"annual_income": annual_income
}
console.log(Linear);
let arraylinear = Object.assign({},Linear);
console.log(arraylinear);
Lineardata.push(arraylinear);
}
}
}
break;
}
}
console.log(binarydata.length);
console.log(binarydata);
converter.json2csv(binarydata,(err,csv) => {
if(err)throw err;
console.log(csv);
file.writeFileSync('/home/rita_gatistavam/Downloads/CSV/binarydata.csv',csv);
console.log('File Written');
})
converter.json2csv(Lineardata,(err,csv) => {
if(err)throw err;
console.log(csv);
file.writeFileSync('/home/rita_gatistavam/Downloads/CSV/lineardata.csv',csv);
console.log('File Written');
})
converter.json2csv(categoricaldata,(err,csv) => {
if(err)throw err;
console.log(csv);
file.writeFileSync('/home/rita_gatistavam/Downloads/CSV/categorydata.csv',csv);
console.log('File Written');
})
next();
}
async function uploadData(req,res,next){
let moduletype = sessionStorage.getItem('moduletype');
console.log(moduletype);
req.params.id = sessionStorage.getItem('modelid');
console.log(req.params.id);
try {
res.status(200).send({
status: 200,
timeout: 10000,
type: 'success',
text: 'Changes saved successfully!',
successProps: {
successCallback: 'func:window.createNotification',
},
responseCallback: 'func:this.props.reduxRouter.push',
pathname: `/ml/models/${req.params.id}/training/historical_data_${moduletype}`,
});
} catch (e) {
periodic.logger.warn(e.message);
res.status(500).send({ message: 'Error updating model type.', });
}
}```
Cannot understand your question, but I assume you want to get all the async request in one go.
You can achieve this with Promise.all, all the results will be returned as an array, and all the request will run at the same time.
const results = await Promise.all([asyncRequest1, asyncRequest2, asyncRequest3])
getting resulsts sequentially.
await asyncRequest1();
await asyncRequest2();
await asyncRequest3();

Promise returns undefined json in Express post request

I have a promise within a selectRecipientData function that returns some user data from an api.
export async function selectRecipientData({ email }) {
engage.selectRecipientData({
listId: listId,
email: email,
returnContactLists: false,
}, function(err, result) {
if(err) {
console.log(err);
} else {
let recipient = JSON.stringify(result);
// this logs successfully
console.log('Recipient details: ' + recipient );
return recipient;
}
});
}
When I call this function within a post request. The data is logged within the promise but is undefined when returned as per below:
server.post('/api/v1/public/selectrecipientdata', async (req, res) => {
formData = req.body;
let { email } = formData;
if (!email) {
res.json({ error: 'Email is required' });
return;
}
try {
let recipientData = await selectRecipientData({ email });
// why is this undefined?
console.log('This is Undefined: '+ JSON.stringify(recipientData) );
res.json({recipientData});
} catch (err) {
res.json({ error: err.message || err.toString() });
}
});
Anyone tell me why? Thanks
You've written selectRecipientData as a callback style function, but you're calling it as an async/await style. If engage.selectRecipientData returns a promise, you could do something like:
export async function selectRecipientData({email}) {
const result=await engage.selectRecipientData({
listId: listId,
email: email,
returnContactLists: false,
});
const recipient=JSON.stringify(result);
console.log('Recipient details: ' + recipient );
return recipient;
}
Otherwise, to convert it to a promise you could do something like:
export function selectRecipientData({email}) {
return new Promise((resolve,reject)=>{
engage.selectRecipientData({
listId: listId,
email: email,
returnContactLists: false,
}, function(err, result) {
if (err) {
reject(err);
}
else {
let recipient = JSON.stringify(result);
console.log('Recipient details: ' + recipient);
resolve(recipient);
}
});
});
}

When I'm testing create script in auth0 it use get user script. Why?

When I'm trying to use create script(button try in custom DB connection or try connection) Auth0 use get user script. Examples:
enter image description here
And then Auth0 use get user script.
Here is my create script:
function create(user, callback) {
var request = require('request');
var API_ENDPOINT = configuration.ENDPOINT_LOCAL + "/api/create/account/";
user.user_metadata = user.user_metadata || {};
request.post({
url: API_ENDPOINT,
json: {
email: user.email,
password: user.password,
nickname: user.user_metadata.nickname,
employee_id: user.user_metadata.employee_id,
company_code: user.user_metadata.company_code,
email_verified: false
}
}, function (err, response, body) {
if (err) {
return callback(err);
}
if (response.statusCode != 200 && response.statusCode != 201) {
return callback(new Error('Forbidden'));
}
callback(null);
});
}
and Here is my get user script:
function getByEmail(email, callback) {
var request = require('request');
var IDP_ENDPOINT = configuration.ENDPOINT_LOCAL + "/api/account";
request.get({
url: IDP_ENDPOINT + '?email=' + email
}, function (err, response, body) {
if (err) {
return callback(err);
}
if (response.statusCode != 200) {
return callback(new Error('Forbidden'));
}
callback(null, JSON.parse(body));
});
}
I really don't know why because two days before all were working.

How to make wordpress.com login connect work with meteor

I'm following these tutorial:
https://developer.wordpress.com/docs/oauth2/
https://developer.wordpress.com/docs/wpcc/
https://github.com/Automattic/wpcom-connect-examples/blob/master/express.js/app.js
So I setup Meteor.loginWithWordpresscom with the following code:
Accounts.oauth.registerService('wordpresscom');
if (Meteor.isClient) {
Meteor.loginWithWordpresscom = function(options, callback) {
// support a callback without options
if (! callback && typeof options === "function") {
callback = options;
options = null;
}
var credentialRequestCompleteCallback = Accounts.oauth.credentialRequestCompleteHandler(callback);
Wordpresscom.requestCredential(options, credentialRequestCompleteCallback);
};
} else {
Accounts.addAutopublishFields({
forLoggedInUser: ['services.wordpresscom'],
forOtherUsers: ['services.wordpresscom.username']
});
}
And then I request credential with the following code:
Wordpresscom = {};
Wordpresscom.requestCredential = function (options, credentialRequestCompleteCallback) {
if (!credentialRequestCompleteCallback && typeof options === 'function') {
credentialRequestCompleteCallback = options;
options = {};
}
var config = ServiceConfiguration.configurations.findOne({service: 'wordpresscom'});
if (!config) {
credentialRequestCompleteCallback && credentialRequestCompleteCallback(
new ServiceConfiguration.ConfigError());
return;
}
var credentialToken = Random.secret();
var loginStyle = OAuth._loginStyle('wordpresscom', config, options);
var loginUrl =
'https://public-api.wordpress.com/oauth2/authorize' +
'?client_id=' + config.clientId +
'&redirect_uri=http://localhost:3000/connected' +
'&response_type=token' +
'&grant_type=authorization_code' +
'&scope=global'
OAuth.launchLogin({
loginService: "wordpresscom",
loginStyle: loginStyle,
loginUrl: loginUrl,
credentialRequestCompleteCallback: credentialRequestCompleteCallback,
credentialToken: credentialToken,
popupOptions: {width: 900, height: 450}
});
};
At the server, I request accessToken and identity with following code:
Wordpresscom = {};
OAuth.registerService('wordpresscom', 2, null, function(query) {
var accessToken = getAccessToken(query);
var identity = getIdentity(accessToken);
return {
serviceData: {
id: identity.ID,
accessToken: OAuth.sealSecret(accessToken),
email: identity.email,
username: identity.username,
displayName: identity.display_name,
avatar: identity.avatar_URL
},
options: {profile: {
name: identity.display_name,
displayName: identity.display_name,
avatar: identity.avatar_URL
}}
};
});
var getAccessToken = function (query) {
var config = ServiceConfiguration.configurations.findOne({service: 'wordpresscom'});
if (!config)
throw new ServiceConfiguration.ConfigError();
var response;
try {
response = HTTP.post(
"https://public-api.wordpress.com/oauth2/token", {
params: {
code: query.code,
client_id: config.clientId,
client_secret: OAuth.openSecret(config.secret),
redirect_uri: 'http://localhost:3000/connected',
grant_type: 'authorization_code'
}
});
} catch (err) {
throw _.extend(new Error("Failed to complete OAuth handshake with WordPress.com. " + err.message),
{response: err.response});
}
if (response.data.error) { // if the http response was a json object with an error attribute
throw new Error("Failed to complete OAuth handshake with WordPress.com. " + response.data.error);
} else {
console.log('getAccessToken');
return response.data.access_token;
}
};
var getIdentity = function (accessToken) {
console.log('getIdentity');
try {
return HTTP.get(
"https://public-api.wordpress.com/rest/v1/me", {
headers: {
/*"User-Agent": userAgent,*/
"Authorization": 'Bearer ' + accessToken
},
params: {access_token: accessToken}
}).data;
} catch (err) {
throw _.extend(new Error("Failed to fetch identity from WordPress.com. " + err.message),
{response: err.response});
}
};
Wordpresscom.retrieveCredential = function(credentialToken, credentialSecret) {
return OAuth.retrieveCredential(credentialToken, credentialSecret);
};
When I fire Meteor.loginWithWordpresscom popup window show up to ask user whether to approve or deny my app with this link http://localhost:3000/connected?code=a8kiRGwRPC
I get code a8kiRGwRPC to request access_token
After I approve, it redirect to http://localhost:3000/connected#access_token=w%5EQ7CFcvZQx3t%28OjspIs84v13BsbyUGROzrYh3%23aiLJQ%25NB%2AZ7jMjNX2%29m7%23t5J4&expires_in=1209600&token_type=bearer&site_id=0
Just like that. No new user stored in Meteor.users database
Any help would be appreciated
Thanks

Categories

Resources