login to [sap] cloud foundry and get api response using nodejs wrapper - node.js

I have a scenario, where I am trying to fetch the API responses of the following host url of my account spaces and orgs in cloudfoundry SAP.
https://api.cf.eu10.hana.ondemand.com
I am using nodejs (wrapper cf-client) script to authenticate but whenever I try to login it provides below error
Error: {"error":"unauthorized","error_description":"{"error":"invalid_grant","error_description":"User authentication failed: INVALID_AUTHORIZATION_HEADER_LENGTH"}"}
Here is my nodejs script
"use-strict";
const endpoint = "https://api.cf.eu10.hana.ondemand.com";
const username = "myusername"; //I have created a trial account
const password = "Password"; //I have created a trial account
const JsonFind = require('json-find');
const fs = require('fs')
const util = require('util');
const dJSON = require('dirty-json');
const CloudController = new (require("cf-client")).CloudController(endpoint);
const UsersUAA = new (require("cf-client")).UsersUAA;
const Apps = new (require("cf-client")).Apps(endpoint);
const Spaces = new (require("cf-client")).Spaces(endpoint);
const Orgs = new (require("cf-client")).Organizations(endpoint);
CloudController.getInfo().then( (result) => {
UsersUAA.setEndPoint(result.authorization_endpoint);
return UsersUAA.login(username, password);
}).then( (result) => {
Orgs.setToken(result);
return Orgs.getOrganizations();
}).then((result) => {
all_orgs = result.resources //returns api
get_orgs=util.inspect(all_orgs, {depth: null});
console.log(get_orgs)
});
What I have seen is when I normaly login with cf client it requires sso passcode along with username password.
how can i provide that here or any idea how can I login here and fetch the data.

Since I did little more research on this and found out that a token generator can be used to overcome this, below code.
"use-strict";
var totp = require('totp-generator');
const endpoint = "https://api.cf.eu10.hana.ondemand.com";
var token = totp('clientsecretidgoeshere');
const username = "myusername"; //I have created a trial account
const password = "Password"+token; //I have created a trial account
const JsonFind = require('json-find');
const fs = require('fs')
const util = require('util');
const dJSON = require('dirty-json');
const CloudController = new (require("cf-client")).CloudController(endpoint);
const UsersUAA = new (require("cf-client")).UsersUAA;
const Apps = new (require("cf-client")).Apps(endpoint);
const Spaces = new (require("cf-client")).Spaces(endpoint);
const Orgs = new (require("cf-client")).Organizations(endpoint);
CloudController.getInfo().then( (result) => {
UsersUAA.setEndPoint(result.authorization_endpoint);
return UsersUAA.login(username, password);
}).then( (result) => {
Orgs.setToken(result);
return Orgs.getOrganizations();
}).then((result) => {
all_orgs = result.resources //returns api
get_orgs=util.inspect(all_orgs, {depth: null});
console.log(get_orgs)
});

Related

Uniswap V3 AlphaRouter - "Failed to get subgraph pools from any providers"

I am trying to swap WETH against MyToken from a previously created Uniswap V3 pool on Arbitrum Rinkeby. When calling AlphaRouter.route, however, I get the following error message
Failed to get subgraph pools from any providers
What is still missing to swap?
What do I need to create?
My target is to swap WETH for a given output of MyToken.
I am trying to simply get a swap on Uniswap V3 with my pool done. Any ideas?
const Web3 = require('web3');
const {
ethers
} = require("ethers");
const HDWalletProvider = require('#truffle/hdwallet-provider');
const {
Token,
CurrencyAmount,
TradeType,
Percent
} = require("#uniswap/sdk-core");
const {
AlphaRouter
} = require('#uniswap/smart-order-router');
const ABI_UNISWAP_POOL_V3 = require("#uniswap/v3-core/artifacts/contracts/interfaces/IUniswapV3Pool.sol/IUniswapV3Pool.json");
const fs = require('fs');
const JSBI = require('JSBI');
const API_ALCHEMY_ARBITRUM_RINKEBY = 'https://arb-rinkeby.g.alchemy.com/v2/<API KEY>';
const POOL_ADDRESS_MYTOKEN_WETH = '0xc69e7AE1073DD8184FcF6dBfc27ba97d1524716A';
const mnemonic = fs.readFileSync("./.mnemonics").toString().trim();
const hdprovider = new HDWalletProvider(mnemonic, API_ALCHEMY_ARBITRUM_RINKEBY);
const provider = new ethers.providers.Web3Provider(hdprovider);
const owner = hdprovider.addresses[0];
var web3 = new Web3(hdprovider);
const Contract = web3.eth.Contract;
const router = new AlphaRouter({
chainId: 421611,
provider: provider
});
async function main() {
const MyPool = new Contract(ABI_UNISWAP_POOL_V3.abi, POOL_ADDRESS_MYTOKEN_WETH);
const [factory, token0, token1, fee, tickSpacing, liquidity, maxLiquidityPerTick] =
await Promise.all([MyPool.methods.factory().call(),
MyPool.methods.token0().call(),
MyPool.methods.token1().call(),
MyPool.methods.fee().call(),
MyPool.methods.tickSpacing().call(),
MyPool.methods.liquidity().call(),
MyPool.methods.maxLiquidityPerTick().call()
]);
const tokenA = new Token(3, token0, 2, "MTK", "MyToken");
const tokenB = new Token(3, token1, 18, "WETH", "Wrapped Ether");
var amountOut = 2000;
amountOut = CurrencyAmount.fromRawAmount(tokenA, JSBI.BigInt(amountOut.toString()));
const slippageTolerance = new Percent(5, 100);
const deadline = Date.now() + 15000;
const route = await router.route(
amountOut,
tokenB,
TradeType.EXACT_OUTPUT, {
recipient: owner,
slippageTolerance: slippageTolerance,
deadline: deadline
}
);
hdprovider.engine.stop();
}
main();
I see two things are not right in this code:
First is the amountOut that you are passing to router.route should be converted to wei
const amountOutInWei=ethers.utils.parseUnits(amountOut.toString(),decimals)
// amountOutInWei should be converted to currentAmount
const currencyAmount= CurrencyAmount.fromRawAmount(tokenA,JSBI.BigInt(amountOutInWei))
currencyAmount should be passed to the router.route(currencyAmount,..)
Second issue deadline must be in seconds.
const deadline=Math.floor(Date.now() / 1000)+10*60 // addded 10 minutes

Node.js E00007 Authorize.net error - User authentication failed due to invalid authentication values

I've been stuck with this issue for a while, looks like generating a token getMerchantDetails is working. However, the second function, createAnAcceptPaymentTransaction, when making a payment doesn't work
E00007 User authentication failed due to invalid authentication values.
I've looked at numerous guides but they all are usually in Java or PHP. A lot of the guides point to ctrl.setEnvironment(SDKConstants.endpoint.production); needing to be set.
The payment works when running the Node API locally, but when running it on the production site it just throws error E00007.
I am using https://sandbox.authorize.net/ - do I have to use a production account to test in production? Even though my sandbox account is set to live mode?
Any suggestions welcome
const ApiContracts = require('authorizenet').APIContracts;
const ApiControllers = require('authorizenet').APIControllers;
const SDKConstants = require('authorizenet').Constants;
async getMerchantDetails() {
const merchantAuthenticationType = new ApiContracts.MerchantAuthenticationType();
merchantAuthenticationType.setName(config.authorizeNet.apiLoginKey);
merchantAuthenticationType.setTransactionKey(config.authorizeNet.transactionKey);
const getRequest = new ApiContracts.GetMerchantDetailsRequest();
getRequest.setMerchantAuthentication(merchantAuthenticationType);
console.log(JSON.stringify(getRequest.getJSON(), null, 2));
const ctrl = new ApiControllers.GetMerchantDetailsController(getRequest.getJSON());
ctrl.setEnvironment(SDKConstants.endpoint.production);
return new Promise(function (resolve, reject) {
ctrl.execute(async () => {
const apiResponse = ctrl.getResponse();
const response = new ApiContracts.GetMerchantDetailsResponse(apiResponse);
console.log(JSON.stringify(response, null, 2));
})
})
}
createAnAcceptPaymentTransaction(setDataValue, checkout) {
const merchantAuthenticationType = new ApiContracts.MerchantAuthenticationType();
merchantAuthenticationType.setName(config.authorizeNet.apiLoginKey);
merchantAuthenticationType.setTransactionKey(config.authorizeNet.transactionKey);
const opaqueData = new ApiContracts.OpaqueDataType();
opaqueData.setDataDescriptor('COMMON.ACCEPT.INAPP.PAYMENT');
opaqueData.setDataValue(setDataValue);
const paymentType = new ApiContracts.PaymentType();
paymentType.setOpaqueData(opaqueData);
const orderDetails = new ApiContracts.OrderType();
orderDetails.setInvoiceNumber(`${checkout?.id?.slice(checkout?.id?.length - 16)}`);
orderDetails.setDescription('Generated by API');
const tax = new ApiContracts.ExtendedAmountType();
tax.setAmount('0');
tax.setName('Base tax');
tax.setDescription('Base tax is set to 0');
const duty = new ApiContracts.ExtendedAmountType();
duty.setAmount('0');
duty.setName('Duty');
duty.setDescription('Duty is set to 0');
let shipping;
if (checkout?.meta?.shippingPrice) {
shipping = new ApiContracts.ExtendedAmountType();
shipping.setAmount(checkout?.meta?.shippingPrice / 100);
shipping.setName(checkout?.meta?.shippingName);
shipping.setDescription(`ShipStation - ${checkout?.meta?.shippingCode}`);
}
const billTo = new ApiContracts.CustomerAddressType();
const name = checkout.billing.fullName.split(' ');
billTo.setFirstName(name.slice(0, name.length - 1).join(' '));
billTo.setLastName(name[name.length]);
// billTo.setCompany()
billTo.setAddress(`${checkout.shipping.streetOne} ${checkout.shipping.streetTwo}`);
billTo.setCity(checkout.shipping.city);
billTo.setState(checkout.shipping.county);
billTo.setZip(checkout.shipping.postcode);
billTo.setCountry(checkout.shipping.country);
const shipTo = new ApiContracts.CustomerAddressType();
const billName = checkout.shipping.fullName.split(' ');
shipTo.setFirstName(billName.slice(0, billName.length - 1).join(' '));
shipTo.setLastName(billName[billName.length]);
shipTo.setAddress(`${checkout.shipping.streetOne} ${checkout.shipping.streetTwo}`);
shipTo.setCity(checkout.shipping.city);
shipTo.setState(checkout.shipping.county);
shipTo.setZip(checkout.shipping.postcode);
shipTo.setCountry(checkout.shipping.country);
const lineItemList = [];
checkout.products.map(product => {
const productLine = new ApiContracts.LineItemType();
productLine.setItemId(product._id);
productLine.setName(AuthorizeNetClass.cutString(product.data.name));
productLine.setDescription(AuthorizeNetClass.cutString(product.data.description));
productLine.setQuantity(product.quantity);
productLine.setUnitPrice(product.data.price / 100);
lineItemList.push(productLine);
});
const lineItems = new ApiContracts.ArrayOfLineItem();
lineItems.setLineItem(lineItemList);
const transactionSetting1 = new ApiContracts.SettingType();
transactionSetting1.setSettingName('duplicateWindow');
transactionSetting1.setSettingValue('120');
const transactionSetting2 = new ApiContracts.SettingType();
transactionSetting2.setSettingName('recurringBilling');
transactionSetting2.setSettingValue('false');
const transactionSettingList = [];
transactionSettingList.push(transactionSetting1);
transactionSettingList.push(transactionSetting2);
const transactionSettings = new ApiContracts.ArrayOfSetting();
transactionSettings.setSetting(transactionSettingList);
const transactionRequestType = new ApiContracts.TransactionRequestType();
transactionRequestType.setTransactionType(
ApiContracts.TransactionTypeEnum.AUTHCAPTURETRANSACTION
);
transactionRequestType.setPayment(paymentType);
transactionRequestType.setAmount(checkout.meta.total / 100);
transactionRequestType.setLineItems(lineItems);
// transactionRequestType.setUserFields(userFields);
transactionRequestType.setOrder(orderDetails);
transactionRequestType.setTax(tax);
transactionRequestType.setDuty(duty);
if (checkout?.meta?.shippingPrice) {
transactionRequestType.setShipping(shipping);
}
transactionRequestType.setBillTo(billTo);
transactionRequestType.setShipTo(shipTo);
transactionRequestType.setTransactionSettings(transactionSettings);
const createRequest = new ApiContracts.CreateTransactionRequest();
createRequest.setMerchantAuthentication(merchantAuthenticationType);
createRequest.setTransactionRequest(transactionRequestType);
//pretty print request
console.log(JSON.stringify(createRequest.getJSON(), null, 2));
const ctrl = new ApiControllers.CreateTransactionController(createRequest.getJSON());
//Defaults to sandbox
ctrl.setEnvironment(SDKConstants.endpoint.production);
return new Promise(function (resolve, reject) {
ctrl.execute(async () => {
const apiResponse = ctrl.getResponse();
const response = new ApiContracts.CreateTransactionResponse(apiResponse);
console.log(JSON.stringify(response, null, 2));
})
})
Your sandbox account and production account are separate and not related in any way. The https://sandbox.authorize.net/ URL is the sandbox environment and you must use your sandbox credentials here. If your code works in the sandbox it won't work in production until you update your credentials to your production credentials and set your code to point to the production URLs.
You can test in production but you need to make sure you are not in live mode or else you will incur fees for any transactions that require connecting to your merchant account (i.e. payments, voids, refunds). Generally speaking it is simpler to test in the sandbox environment and just update your configuration to use the production environment, with the correct credentials, when you are ready to accept transactions.

google-api-nodejs-client is not fetching details

I am using google-api-nodejs-client oauth2.js and console is not showing any errors but no profile details are getting fetched of the signed in user in console. Here, is my code where "Hey there.2" is the last line that is getting displayed in console. Can someone point me the incorrect part?
I have included oauth2.keys.json in the directory.
Edit: I just found that Hey there.3 got displayed but after a very big time interval.
'use strict';
const fs = require('fs');
const path = require('path');
const http = require('http');
const url = require('url');
const opn = require('opn');
const destroyer = require('server-destroy');
const {google} = require('googleapis');
const plus = google.plus('v1');
console.log("Hey there.1");
/**
* To use OAuth2 authentication, we need access to a a CLIENT_ID, CLIENT_SECRET, AND REDIRECT_URI. To get these credentials for your application, visit https://console.cloud.google.com/apis/credentials.
*/
const keyPath = path.join(__dirname, 'oauth2.keys.json');
let keys = {redirect_uris: ['']};
if (fs.existsSync(keyPath)) {
keys = require(keyPath).web;
}
/**
* Create a new OAuth2 client with the configured keys.
*/
const oauth2Client = new google.auth.OAuth2(
keys.client_id,
keys.client_secret,
keys.redirect_uris[0]
);
/**
* This is one of the many ways you can configure googleapis to use authentication credentials.
In this method, we're setting a global reference for all APIs.
Any other API you use here, like google.drive('v3'), will now use this auth client.
You can also override the auth client at the service and method call levels.
*/
google.options({auth: oauth2Client});
/**
* Open an http server to accept the oauth callback.
The only request to our webserver is to /callback?code=<code>
*/
async function authenticate(scopes) {
return new Promise((resolve, reject) => {
// grab the url that will be used for authorization
const authorizeUrl = oauth2Client.generateAuthUrl({
access_type: 'offline',
scope: scopes.join(' '),
});
console.log("Hey there.2");
const server = http
.createServer(async (req, res) => {
try {
console.log("Hey there.3");
if (req.url.indexOf('google') > -1) {
//const qs = querystring.parse(url.parse(req.url).query);
const qs = new url.URL(req.url).searchParams;
res.end('Authentication successful! Please return to the console.');
server.destroy();
//const {tokens} = await oauth2Client.getToken(qs.code);
const {tokens} = await oauth2Client.getToken(qs.get('code'));
oauth2Client.credentials = tokens;
resolve(oauth2Client);
console.log("Hey there.4");
}
} catch (e) {
console.log(e);
reject(e);
}
})
.listen(3000, () => {
// open the browser to the authorize url to start the workflow
opn(authorizeUrl, {wait: false}).then(cp => cp.unref())
;
});
destroyer(server);
});
}
async function runSample() {
// retrieve user profile
const res = await plus.people.get({userId: 'me'});
console.log(res.data);
console.log("Hey there.5");
console.log(userId);
}
const scopes = ['https://www.googleapis.com/auth/plus.login'];
authenticate(scopes)
.then(client => runSample(client))
.catch(console.error);

AWS Lambda TypeError: callback is not a function

I'm trying to make twilio access token in AWS lambda, but I get the error "callback is not a function". How can I fix it?
const AccessToken = require('twilio').jwt.AccessToken;
const VoiceGrant = AccessToken.VoiceGrant;
exports.generateToken = function(identity, callback) {
// Used when generating any kind of tokens
const accountSid = 'xxxxxxxxx';
const apiKey = 'xxxxx';
const apiSecret = 'xxx';
// Used specifically for creating Voice tokens
const pushCredSid = 'xxx';
const outgoingApplicationSid = 'xxxxx';
// Create an access token which we will sign and return to the client,
// containing the grant we just created
const voiceGrant = new VoiceGrant({
outgoingApplicationSid: outgoingApplicationSid,
pushCredentialSid: pushCredSid
});
// Create an access token which we will sign and return to the client,
// containing the grant we just created
const token = new AccessToken(accountSid, apiKey, apiSecret);
token.addGrant(voiceGrant);
token.identity = identity;
console.log('Token:' + token.toJwt());
callback(null, token.toJwt());
};
As Roland Starke said, it's worth changing this exports.generateToken = function(identity, callback) to exports.generateToken = function(event, context, callback) and everything will work fine.

Firebase Functions check if the user id in the database is the current user id

Im working on sending notifications between android devices using Firebase functions. When A-Device sends a message to B-Device, the message will be stored in the firebasedatabase under A-Device Id und B-Device Id like this the problem is the function which i wrote checks always A-Device id therefore it sends the notification always to A-Device. it means when A-Device sends to B-Device the notification will be sent to A-Device
this is my Node.js code. please help me ;(
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
//const mId = firebase.auth().currentUser.getToken();
exports.sendNotification = functions.database.ref('/Messages/{mId}/{uId}/{messageId}').onWrite(event =>{
const mId = event.params.mId; //getting mId
const uId = event.params.uId; //getting uId
const val = event.data.val(); //getting the values from event
const from = val.from; //from value
const type = val.type; //type value
const message = val.message;
console.log("user_name ",user_name);
console.log("user_email ",user_email);
const getDeviceToken = admin.database().ref(`/Users/${uId}/`).once('value');//getting device token function
return getDeviceToken.then(snapshot =>{ //executing the function
const DeviceToken = snapshot.val().DeviceToken;
console.log ("Device Token is ",DeviceToken);
if (from == mId) {
delete DeviceToken;
}
const getName = admin.database().ref(`/Users/${from}/`).once('value');//getting device token function
return getName.then(snapshot =>{ //executing the function
const Name = snapshot.val().Name;
console.log ("Sender is ",Name);
const payload = {
data: {
title: `${Name} sent you a message.`,
body: `${message}`
}
};
return admin.messaging().sendToDevice(DeviceToken,payload).then(response => {
console.log (`Notification has been sent to ${Name}`);
});});
});
});

Resources