How can i send server to client '''user''' in this code? - javascript

I am using this code for get Facebook user profile but i cant send client this user variable. How can i do it ?
Daha neler yazayım derdim bu kadar işte. Facebook kullanıcı bilgilerini client tarafına dönemedim. Ne yapmalıyım ?
Here is my code :
router.post('/fbLogin', async function (ctx, next) {
var user;
console.log(ctx.request.body.token);
var options = {
host: 'graph.facebook.com',
port: 443,
path: '/v2.11/me?fields=id,first_name,last_name,email',
method: 'GET',
headers: { 'Authorization': 'Bearer ' + ctx.request.body.token }
};
const req = https.request(options, async function (res) {
res.setEncoding('utf8');
res.on('data', async function (d) {
var fbJsonObject = JSON.parse(d);
user = await db.collection('users').findOne({ facebookId: fbJsonObject.id });
if (!user) {
var uname = fbJsonObject.first_name.toString() + '_' + fbJsonObject.last_name.toString().substring(0, 1);
console.log(uname);
var count = await db.collection('users').find({ username: /uname/ }).count();
if (count != 0) {
uname = uname + count.toString();
}
var pass = customPassword();
await db.collection('users').insertOne({
method: 'facebook',
email: fbJsonObject.email,
username: uname,
password: phash.generate(pass),
friends: [],
facebookId: fbJsonObject.id
});
user = await db.collection('users').findOne({ facebookId: fbJsonObject.id });
console.log("Kayıt başarılı");
console.log(user);
}
})
});
req.end();
});
and client side code :
async loginWithFB() {
await this.facebook.login(['email', 'public_profile']).then((response: FacebookLoginResponse) => {
this.facebook.api('me?fields=id,name,email,first_name,last_name,picture.width(720).height(720).as(picture_large)', []).then(profile => {
//this.userData = { id: profile['id'] }
this.fb(response.authResponse.accessToken);
})
})
}
async fb(token2) {
var resp = await this.http.post('http://api.suma.nopsmart.com:3000/fbLogin', {
token: token2
}).toPromise();
var x = resp.json();
console.log(x);
}

Related

Fetch function for ExactOnline with multiple request fails on zapier and n8n

I've been working on a script that creates and updates stuff with the ExactOnline API.
when I run the script locally everything works fine but when I try to use it on a platform such as Zapier or n8n it doesn't work as intended.
on Zapier it only runs just before it does a fetch request
this my code that I use in zapier:
var token = 'token';
var divisionid = 'divisionid';
var AMRelatieData = {
"Name": "company name",
"City": "city name",
"Website": "website.com"
};
var AMContactData = {
"FirstName": "firstname",
"LastName": "lastname",
"City": "name city"
};
var testrlid;
async function actionHandeler(actionValue) {
var action = actionValue;
if (action == "cp_maken_&_relatie_maken") {
var maakRelatieWaarde = await maakRelatie(AMRelatieData);
var POSTrelatieID = maakRelatieWaarde;
AMContactData.Account = POSTrelatieID;
var maakContactwaarde = await maakContact(AMContactData);
var POSTcontactID = maakContactwaarde;
testcpid = POSTcontactID;
testrlid = POSTrelatieID;
return ('maakContactwaarde succes');
}
//functions
async function updateRelatie(updateData, relatieId) {
var UpdateRelatiePUT = await PUTreq(1, updateData, relatieId);
console.log(UpdateRelatiePUT);
return ("updateRelatie succes");
}
async function maakRelatie(createData) {
var relatieId;
console.log('maakRelatie: ');
var maakRelatiePOST = await POSTreq(1, createData);
console.log('maakRelatieFunc:' + JSON.stringify(maakRelatiePOST));
return await maakRelatiePOST.d.ID;
}
async function maakContact(createData) {
var contactId;
var maaktcontactPOST = await POSTreq(2, createData);
console.log('maaktcontactFunc:' + JSON.stringify(maaktcontactPOST));
var jsonData = {
MainContact: maaktcontactPOST.d.ID
};
var relatieIdUpdate = createData.Account;
await updateRelatie(jsonData, relatieIdUpdate);
}
async function POSTreq(type, DATA) {
console.log('postreq');
var POSTendpoint = 'https://start.exactonline.nl/api/v1/'+ divisionid +'/crm/';
if (type == 1) {
POSTendpoint += 'Accounts';
}
if (type == 2) {
POSTendpoint += 'Contacts';
}
var outputPOST;
console.log(DATA);
await fetch(POSTendpoint, {
method: "POST",
headers: {
'Accept': 'application/json',
'Authorization': 'Bearer ' + token,
'Content-Type': 'application/json'
},
body: JSON.stringify(DATA)
}).then(response => {
return response.json();
}).then(jsonResponse => {
var responseOut = jsonResponse;
outputPOST = responseOut;
}).catch(error => {
console.log(error);
});
return outputPOST;
}
async function PUTreq(type, DATA, id) {
var PUTendpoint = 'https://start.exactonline.nl/api/v1/'+ divisionid +'/crm/';
console.log('put data');
console.log(id);
console.log('data' + DATA);
console.log(type);
if (type == 1) {
PUTendpoint += "Accounts(guid'" + id + "')";
}
if (type == 2) {
PUTendpoint += "Contacts(guid'" + id + "')";
}
console.log(PUTendpoint);
console.log(PUTendpoint);
await fetch(PUTendpoint, {
method: 'PUT',
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer ' + token
},
body: JSON.stringify(DATA)
});
}
}
async function actionHandlerFunc(){
console.log("begin");
await actionHandeler("cp_maken_&_relatie_maken");
return ("done did sum stuff");
};
output = [actionHandlerFunc()]

auth.getAccessToken() is not a function - Azure AD PowerBI + NodeJS integration

Still am able to get the accessToken successfully but don't understand why I'm getting auth.getAccessToken is not a function
index.js
$.ajax({
type: "GET",
url: "/getSingRpt",
dataType: "json",
success: function (embedData) {
let reportLoadConfig = {
type: "report",
tokenType: models.TokenType.Embed,
accessToken: embedData.accessToken,
embedUrl: embedData.embedUrl[0].embedUrl
};
tokenExpiry = embedData.expiry;
let report = powerbi.embed(reportContainer, reportLoadConfig);
report.off("loaded");
report.on("loaded", function () {
console.log("Report load successful");
});
report.off("rendered");
report.on("rendered", function () {
console.log("Report render successful");
});
report.off("error");
report.on("error", function (event) {
let errorMsg = event.detail;
console.error(errorMsg);
return;
});
},
error: function (err) {
let errorContainer = $(".error-container");
$(".embed-container").hide();
errorContainer.show();
let errMsg = JSON.parse(err.responseText)['error'];
let errorLines = errMsg.split("\r\n");
let errHeader = document.createElement("p");
let strong = document.createElement("strong");
let node = document.createTextNode("Error Details:");
let errContainer = errorContainer.get(0);
strong.appendChild(node);
errHeader.appendChild(strong);
errContainer.appendChild(errHeader);
errorLines.forEach(element => {
let errorContent = document.createElement("p");
let node = document.createTextNode(element);
errorContent.appendChild(node);
errContainer.appendChild(errorContent);
});
}
});
Server.js
app.get('/getSingRpt', async (req, res) => {
try {
await embedToken.getEmbedParamsForSingleReport().then((result) => {
console.log(result);
res.status(200).send({ success: true, data: result });
})
} catch (e) {
console.error(e);
res.status(400).send({ success: false, message: 'problem in getting report' });
}
});
embedSConfigService.js
async function getEmbedParamsForSingleReport(workspaceId, reportId, additionalDatasetId) {
const reportInGroupApi = `https://api.powerbi.com/v1.0/myorg/groups/${workspaceId}/reports/${reportId}`;
const headers = await getRequestHeader();
const result = await fetch(reportInGroupApi, {
method: 'GET',
headers: headers,
})
console.log('result', result);
if (!result.ok) {
throw result;
}
const resultJson = await result.json();
const reportDetails = new PowerBiReportDetails(resultJson.id, resultJson.name, resultJson.embedUrl);
const reportEmbedConfig = new EmbedConfig();
reportEmbedConfig.reportsDetail = [reportDetails];
let datasetIds = [resultJson.datasetId];
if (additionalDatasetId) {
datasetIds.push(additionalDatasetId);
}
reportEmbedConfig.embedToken = await getEmbedTokenForSingleReportSingleWorkspace(reportId, datasetIds, workspaceId);
return reportEmbedConfig;
}
async function getRequestHeader() {
let tokenResponse;
let errorResponse;
try {
tokenResponse = await auth.getAccessToken();
} catch (err) {
if (err.hasOwnProperty('error_description') && err.hasOwnProperty('error')) {
errorResponse = err.error_description;
} else {
errorResponse = err.toString();
}
return {
'status': 401,
'error': errorResponse
};
}
const token = tokenResponse;
console.log('TOKEN==>', tokenResponse)
return {
'Content-Type': "application/json",
'Authorization': utils.getAuthHeader(token)
};
}
Auth.js
const adal = require('adal-node');
const config = require(__dirname + '/../config/config.json');
const getAccessToken = () => {
return new Promise((resolve, reject) => {
try {
const authMode = config.authenticationMode.toLowerCase();
const AuthenticationContext = adal.AuthenticationContext;
let authorityUrl = config.authorityUri;
if (authMode === 'masteruser') {
new AuthenticationContext(
authorityUrl,
).acquireTokenWithUsernamePassword(
config.scope,
config.pbiUsername,
config.pbiPassword,
config.clientId,
(err, token) => {
if (err) reject(err);
resolve(token);
},
);
} else if (authMode === 'serviceprincipal') {
authorityUrl = authorityUrl.replace('common', config.tenantId);
new AuthenticationContext(
authorityUrl,
).acquireTokenWithClientCredentials(
config.scope,
config.clientId,
config.clientSecret,
(err, token) => {
if (err) reject(err);
resolve(token);
},
);
} else {
reject(new Error('Unknown auth mode'));
}
} catch (err) {
console.error(err);
reject(err);
}
});
};
getAccessToken()
.then((token) => console.log(token))
.catch((err) => console.error(err));
updated
utilities.js
let config = require(__dirname + "/../config/config.json");
function getAuthHeader(accessToken) {
// Function to append Bearer against the Access Token
return "Bearer ".concat(accessToken);
}

Spotify Web API OAuth Error 400: Error using Axios and Async/Await

I want to use the Spotify Web API, and I'm using the authorization_code example from their their web-api-auth-examples repository.
I wanted to use the axios library (with async/await) instead of the request library since request was deprecated earlier this year.
So I tried modifying the app.get() method for the /callback route, but I'm getting a 400 error (Bad Request) from my getAuth() function in the post request.
Been stuck on this one for several hours now and I can't seem to figure out what I'm doing wrong.
app.js:
const express = require('express');
const axios = require('axios');
const cors = require('cors');
const querystring = require('querystring');
const cookieParser = require('cookie-parser');
const dotenv = require('dotenv');
dotenv.config({ path: './config.env' });
const client_id = `${process.env.CLIENT_ID}`;
const client_secret = `${process.env.CLIENT_SECRET}`;
const redirect_uri = 'http://localhost:8888/callback';
...
const app = express();
...
app.get('/callback', function (req, res) {
const code = req.query.code || null;
const state = req.query.state || null;
const storedState = req.cookies ? req.cookies[stateKey] : null;
if (state === null || state !== storedState) {
res.redirect(
'/#' +
querystring.stringify({
error: 'state_mismatch',
})
);
} else {
res.clearCookie(stateKey);
const postHeaders = {
Accept: 'application/json',
'Content-Type': 'application/x-www-form-urlencoded',
Authorization: `Basic ${Buffer.from(
`${client_id}:${client_secret}`
).toString('base64')}`,
};
const postStringHeaders = querystring.stringify(postHeaders);
const getAuth = async () => {
try {
let response = await axios({
url: 'https://accounts.spotify.com/api/token',
method: 'post',
params: {
grant_type: 'authorization_code',
code,
redirect_uri,
},
postStringHeaders,
});
if (response.status === 200) {
const access_token = response.data.access_token;
const refresh_token = response.data.refresh_token;
const getUrl = 'https://api.spotify.com/v1/me';
const getHeaders = {
Accept: 'application/json',
'Content-Type': 'application/x-www-form-urlencoded',
Authorization: `Bearer ${access_token}`,
};
const getStringHeaders = querystring.stringify(getHeaders);
try {
let getRes = await axios({
method: 'get',
getUrl,
getStringHeaders,
params: {
access_token,
refresh_token,
},
});
if (getRes.status === 200) {
console.log(body);
}
res.redirect(
'/#' +
querystring.stringify({
access_token: access_token,
refresh_token: refresh_token,
})
);
} catch (err) {
console.log(err);
}
} else {
res.redirect(
'/#' +
querystring.stringify({
error: 'invalid_token',
})
);
}
} catch (err) {
console.log(err);
}
};
getAuth();
}
});
I was able to get the requests to succeed by modifying my code for the app.get() method as shown below!
app.get('/callback', async function (req, res) {
const code = req.query.code || null;
const state = req.query.state || null;
const storedState = req.cookies ? req.cookies[stateKey] : null;
if (state === null || state !== storedState) {
res.redirect(
'/#' +
querystring.stringify({
error: 'state_mismatch',
})
);
} else {
res.clearCookie(stateKey);
const postHeaders = {
Accept: 'application/json',
'Content-Type': 'application/x-www-form-urlencoded',
};
try {
let response = await axios({
url: 'https://accounts.spotify.com/api/token',
method: 'post',
params: {
client_id,
client_secret,
grant_type: 'authorization_code',
code,
redirect_uri,
},
postHeaders,
});
if (response.status === 200) {
const access_token = response.data.access_token;
const refresh_token = response.data.refresh_token;
const getUrl = 'https://api.spotify.com/v1/me';
const getHeaders = {
Accept: 'application/json',
'Content-Type': 'application/x-www-form-urlencoded',
};
try {
let getRes = await axios({
method: 'get',
url: getUrl,
getHeaders,
params: {
access_token,
refresh_token,
},
});
if (getRes.status === 200) {
console.log('LOGIN SUCCESSFUL!', getRes.data);
}
res.redirect(
'/#' +
querystring.stringify({
access_token: access_token,
refresh_token: refresh_token,
})
);
} catch (err) {
console.log(err);
}
} else {
res.redirect(
'/#' +
querystring.stringify({
error: 'invalid_token',
})
);
}
} catch (err) {
console.log(err.response);
}
}
});

Request_BadRequest in O365

I am trying to send a email with the help of O365. I have configured everything but I am getting a error
GraphError { statusCode: 405, code: 'Request_BadRequest',
message: 'Specified HTTP method is not allowed for the request
target.', requestId: '34f321-57de-4483-b97d-5957f8786ecb', date:
2019-09-16T00:17:53.000Z, body:
'{"code":"Request_BadRequest","message":"Specified HTTP method is not
allowed for the request
target.","innerError":{"request-id":"34f803b1-57de-4483-b97d-5957f8786ecb","date":"2019-09-16T05:47:51"}}'
}
Code
const APP_ID = "XXXXXXXXXXXXXXXXXX";
const APP_SECERET = "XXXXXXXXXXXXXX";
const TENANT_ID = "XXXXXXXXXXXXXXXX";
const TOKEN_ENDPOINT = "https://login.microsoftonline.com/XXXXXXXXXXXXXXXXXXXXX/oauth2/v2.0/token";
const MS_GRAPH_SCOPE = "https://graph.microsoft.com/.default";
const GRANT_TYPE = "client_credentials";
const graphScopes = ["User.Read", "Mail.Send"]; // An array of graph scopes
const request = require("request");
const endpoint = TOKEN_ENDPOINT;
const requestParams = {
grant_type: GRANT_TYPE,
client_id: APP_ID,
client_secret: APP_SECERET,
scope: MS_GRAPH_SCOPE
};
request.post({
url: endpoint,
form: requestParams
}, function(err, response, body) {
if (err) {
console.log("error");
} else {
// console.log(response);
// console.log("Body=" + body);
let parsedBody = JSON.parse(body);
if (parsedBody.error_description) {
console.log("Error=" + parsedBody.error_description);
} else {
console.log("Access Token=" + parsedBody.access_token);
// testGraphAPI(parsedBody.access_token);
let accessToken = parsedBody.access_token;
getMe(accessToken);
}
}
});
function getMe(accessToken) {
require("isomorphic-fetch");
const fs = require("fs");
const MicrosoftGraph = require("#microsoft/microsoft-graph-client").Client;
const options = {
defaultVersion: "v1.0",
debugLogging: true,
authProvider: (done) => {
done(null, accessToken);
},
};
// https://github.com/microsoftgraph/msgraph-sdk-javascript/blob/dev/samples/node/main.js
// https://learn.microsoft.com/en-us/graph/overview
const client = MicrosoftGraph.init(options);
// send an email
const sendMail = {
message: {
subject: "Test o365 api from node",
body: {
contentType: "Text",
content: "Testing api."
},
toRecipients: [{
emailAddress: {
address: "test#abc.com"
}
}],
ccRecipients: [{
emailAddress: {
address: "test#abc.com"
}
}]
},
saveToSentItems: "false"
};
client.api('/users/test1#abc.onmicrosoft.com ').post(sendMail).then((res) => {
console.log(res);
}).catch((err) => {
console.log(err);
});
}
Can someone tell me where I am going wrong. Please help me out
I had the same error and it was a malformed url when sending to the users.
I think your url should be /users/test1#abc.onmicrosoft.com/sendMail

Cognito AmazonWebService authentication issue

I'm doing an user management with the AmazonWebService cognito and I having some difficulties to authenticate me to my user pool.
Do am I logged in if I just do:
login: function(username, password, _poolData) {
var deferred = $q.defer();
var authenticationData = {
Username : username,
Password : password,
};
var userPool = new AWSCognito.CognitoIdentityServiceProvider.CognitoUserPool(_poolData);
var userData = {
Username : username,
Pool : userPool
};
cognitoUser = new AWSCognito.CognitoIdentityServiceProvider.CognitoUser(userData);
var authenticationDetails = new AWSCognito.CognitoIdentityServiceProvider.AuthenticationDetails(authenticationData);
cognitoUser.authenticateUser(authenticationDetails, {
onSuccess: function (result) {
console.log('access token + ' + result.getAccessToken().getJwtToken());
console.log('idToken + ' + result.idToken.jwtToken)
deferred.resolve('successfully logged in.');
},
onFailure: function(err) {
console.log(error);
alert(err);
deferred.reject('login failled.');
},
});
return deferred.promise;
},
Because I can not get my user attributes after using this login method.
Like this:
getCognitoUserAttr: function(username, _poolData) {
var userPool = new AWSCognito.CognitoIdentityServiceProvider.CognitoUserPool(_poolData);
var userData = {
Username : username,
Pool : userPool
};
cognitoUser = new AWSCognito.CognitoIdentityServiceProvider.CognitoUser(userData);
cognitoUser.getUserAttributes(function(err, result) {
if (err) {
alert(err);
return;
}
for (var i = 0; i < result.length; i++) {
console.log('attribute ' + result[i].getName() + ' has value ' + result[i].getValue());
}
});
}
I always have the error message:
Error: User is not authenticated
Note that the login method is from :https://docs.aws.amazon.com/fr_fr/cognito/latest/developerguide/using-amazon-cognito-user-identity-pools-javascript-examples.html
What I have to do?
Here you go. I made a function called getUserAttributes() then used the same code as seen in isAuthenticated.
getUserAttributes(){
let cognitoUser = this.getCurrentUser();
if (cognitoUser != null) {
cognitoUser.getSession(function (err, session) {
cognitoUser.getUserAttributes(function(err, result) {
if (err) {
console.log(err);
return;
}
for (let i = 0; i < result.length; i++) {
console.log('attribute ' + result[i].getName() + ' has value ' + result[i].getValue());
}
});
});
}
}
this is the login function i use
authenticate(username: string, password: string, callback: CognitoCallback) {
let authenticationData = {
Username : username,
Password : password,
};
let authenticationDetails = new AWSCognito.CognitoIdentityServiceProvider.AuthenticationDetails(authenticationData);
let poolData = {
UserPoolId : CognitoUtil._USER_POOL_ID,
ClientId : CognitoUtil._CLIENT_ID
};
let userPool = new AWSCognito.CognitoIdentityServiceProvider.CognitoUserPool(poolData);
let userData = {
Username : username,
Pool : userPool
};
let cognitoUser = new AWSCognito.CognitoIdentityServiceProvider.CognitoUser(userData);
cognitoUser.authenticateUser(authenticationDetails, {
onSuccess: function (result) {
AWS.config.credentials = new AWS.CognitoIdentityCredentials({
IdentityPoolId : CognitoUtil._IDENTITY_POOL_ID,
Logins : {
'cognito-idp.REGION.amazonaws.com/POOLID':result.getIdToken().getJwtToken()
}
});
callback.cognitoCallback('loginSuccess', null);
},
onFailure: function (err) {
callback.cognitoCallback(err.message, null);
}
});
}

Categories