How to validate HMAC the shopify webhook - nodejs Lambda - node.js

I cannot able to validate the webhook response from the shopify by using the "crypto-js" package.
i am using: "Node.js, AWS-Lambda , crypto-js" and the following code to validate
var CryptoJS = require("crypto-js");
var getRawBody = require("raw-body");
var Buffer = require('buffer/').Buffer // note: the trailing slash is important!
exports.handler = async (event, context) => {
let hmac = event.hmac;
const bodyString = Buffer.from(event.body, "utf8").toString();
var bodyForVerification = bodyString.replace('/\\/g', '\\\\');
let firma = CryptoJS.HmacSHA256(bodyForVerification, "****");
var hashInBase64 = CryptoJS.enc.Base64.stringify(firma);
let calculatedHmacBase = hashInBase64.toString(CryptoJS.enc.hex);
if(hmac == calculatedHmacBase {
console.log("verificado");
}
};
The HMAC is different..

I use this middleware for my public and private apps on Shopify,
using crypto, it is deprecated but works fine for my code.
const crypto = require('crypto');
const verify = function (req, res, next) {
if (req.query.shop) {
if (!req.query.signature) {
return false;
}
console.log(req.query);
const signature = req.query.signature;
const sharedSecret = process.env.SHOPIFY_SHARED_SECRET;
const def = req.query;
delete def.signature;
const sortedQuery = Object.keys(def).map(key => `${key}=${Array(def[key]).join(',')}`).sort().join('');;
const calculatedSignature = crypto.createHmac('sha256', sharedSecret).update(sortedQuery).digest('hex');
if (calculatedSignature === signature) {
console.log('validated');
return next();
}
console.log('not validated');
return false;
}
};
module.exports = verify;

Related

caching query with redis

i need to cache a query with redis and node js , the database is aws s3 ,the problem here as a noob ,i will recive the query as a string, i need to encode the keys in the body request so when i will later try to fetsch the data i will use one of those keys(they need to be seperated with '/') can anyone help me with that and bunch of thanks.
here is what i' tried to do:
const { default: axios } = require('axios');
const express = require('express');
const redisClient = require('./helper/Client')
const app = express();
const port = process.env.PORT || 3000
app.use(express.json());
async function fetchApi(species){
const apiResponse = await axios.get(`https://www.fishwatch.gov/api/species/${species}`)
console.log('request sent successfully');
return apiResponse.data
}
async function getSpeciesData(req, res) {
const species = req.body;
const keys = Object.keys(species);
const encodedParams = {};
for (const key of keys) {
const encodedKey = Buffer.from(key).toString('base64');
encodedParams[encodedKey] = species[key];
}
const key = JSON.stringify(encodedParams);
let resultat;
let isCached = false;
const cachedResponse = await redisClient.get(key);
if (cachedResponse) {
isCached = true;
const decodedResponse = Buffer.from(cachedResponse, 'base64').toString('utf-8');
resultat = JSON.parse(decodedResponse);
res.send({
fromCache: isCached,
data: resultat
});
console.log(cachedResponse);
} else {
const responseData = await fetchApi(keys.join('/'));
const encodedResponseData = Buffer.from(JSON.stringify(responseData)).toString('base64');
redisClient.SETEX(key, 3600, encodedResponseData);
res.send(responseData);
}
}
app.post("/fish", getSpeciesData);
app.listen(port, () => {
console.log(`Listening on ${port}`);
});

Ethersjs Call Rever Exception

I'm trying to interact with a BSC Smartcontract using Ethersjs and here is my code:
require("dotenv").config();
const { ethers } = require("ethers");
const pk = process.env.PRIVATE_KEY;
const bsc_jsonRPC_testnet = "https://data-seed-prebsc-1-s1.binance.org:8545/" // json RPC url
const provider = new ethers.providers.JsonRpcProvider(bsc_jsonRPC_testnet);
let wallet = new ethers.Wallet(pk, provider);
const CONTRACT_ABI = require('./abis/vino.json'); // set ABI
const CONTRACT_ADDRESS = '0x21f59c8D31EF2E3E472793b28CAc4553aac7a72a';
let contract = new ethers.Contract(CONTRACT_ADDRESS, CONTRACT_ABI, provider);
var numberOfDecimals = 18;
const activeProvider = contract.provider.connection.url;
const methods = contract.functions
console.log(methods.name().then((res) => {
console.log(res)
}).catch((e) => {
console.log(e)
}));
console.log('URL PROVIDER: ', activeProvider);
And here what I'm getting from console:
I tried changing chains and providers but no success.

Firebase function testes with local emulators, Firestore collection snapshot persists of claiming being emtpy

Trying to test "locally" a firebase function with
firebase emulators:start --inspect-functions on http:// 127 .0.0.1:5000.
When debugging it step by step, the snapshot doesn't exist...but it's not. What I can possibly do wrong ?
const BotDetector = require("device-detector-js/dist/parsers/bot");
const fs = require("fs");
const DEBUG_BOT = true;
const functions = require("firebase-functions");
const admin = require("firebase-admin");
admin.initializeApp();
const db = admin.firestore();
// Main firebase function called on firebase.json rewrites rules
exports.dynamicMetaTagsUpdate = functions.https.onRequest(async (request, response) => {
let html = fs.readFileSync("../web/index.html", "utf8");
const botDetector = new BotDetector();
const userAgent = request.headers["user-agent"].toString();
const bot = botDetector.parse(userAgent);
if (bot || DEBUG_BOT) {
try {
const { postID } = request.query;
const postUrl = 'http://localhost:5000/blog/post?postID=' + postID;
const docRef = db.collection("posts").doc(postID);
const postData = docRef.get().then((snapshot) => {
if (snapshot.exists()) {
const object = {
postUrl: postUrl,```

ReferenceError: name is not defined

I have a code in Controller
const getLocalDatabaseResule = async (searchURL, reqBody) => {
commonCode(reqBody);
console.log(name);
});
function commonCode(reqBody) {
var name = reqBody.name;
var phone= reqBody.phone;
var email = reqBody.email;
}
Any idea how to add common function in controller
You need to return the body from commonCode
const getLocalDatabaseResule = async (searchURL, reqBody) => {
const {name,phone,email} = commonCode(reqBody);
console.log(name);
};
function commonCode(reqBody) {
const name = reqBody.name;
const phone= reqBody.phone;
const email = reqBody.email;
return {name,phone,email}
}
getLocalDatabaseResule("searchURL", {name:"User",phone:"111", email:"mail#mail.com"})
Also this is possible
const getLocalDatabaseResule = async (searchURL, reqBody) => {
var x = commonCode(reqBody);
console.log(x.name);
});
function commonCode(reqBody) {
this.name = reqBody.name;
this.phone= reqBody.phone;
this.email = reqBody.email;
}

Promisify is not a function

I am working on lex and I am trying to store user data in DynamoDB while using NodeJS
Here is my code:
'use strict';
const uuidV1 = require('uuid/v1');
const AWS = require('aws-sdk');
const promisify = require('es6-promisify');
const dynamo = new AWS.DynamoDB.DocumentClient();
module.exports.saveBookingToDatabase = function(Arrival_city, Departure_city, Flight_type, Phone_number){
console.log('saveBookingToDatabase');
const item = {};
item.bookingId = uuidV1();
item.arrivalCity = Arrival_city;
item.departureCity = Departure_city;
item.classType = Flight_type;
item.phone = Phone_number;
const params = {
TableName: 'airstallion',
Item: item
};
const putAsync = promisify(dynamo.put, dynamo);
return putAsync(params).then(() => {
console.log(`Saving ticket ${JSON.stringify(item)}`);
return item;
})
.catch(error => {
Promise.reject(error);
});
}
When i run the program is returning the following error
Since aws-sdk library supports promise, its not necessary to use es6-promisify library. Using node.js async/await we shall achieve the same use case.
'use strict';
const uuidV1 = require('uuid/v1');
const AWS = require('aws-sdk');
const dynamo = new AWS.DynamoDB.DocumentClient();
module.exports.saveBookingToDatabase = async function(Arrival_city, Departure_city, Flight_type, Phone_number){
console.log('saveBookingToDatabase');
const item = {};
item.bookingId = uuidV1();
item.arrivalCity = Arrival_city;
item.departureCity = Departure_city;
item.classType = Flight_type;
item.phone = Phone_number;
const params = {
TableName: 'airstallion',
Item: item
};
try {
let result = await dynamo.put(params)
console.log(`Saving ticket ${JSON.stringify(item)}`);
return item;
} catch(e) {
throw (e)
}
}

Resources