node-bigcommerce Get and Post Routes - npm

I'm using the npm package, 'node bigcommerce', and I have all my API's setup but whenever I try to make a GET route, the error, Error: Request returned error code: 404 and body: The route is not found, check the URL, shows up. I don't know how or where to specify the url to find. Also, I have the same problem with POST Routes. The code is here. Thanks ahead!
var express = require('express'),
BigCommerce = require('node-bigcommerce');
var bigCommerce = new BigCommerce({
clientId: '* Client ID *',
secret: '* Secret *',
callback: 'https://store-xxi13.mybigcommerce.com',
responceType: 'json',
accessToken: '* Access Token *',
storeHash: 'xxi13'
});
bigCommerce.get('/happy', (data) =>{
console.log(data);
});

The path supplied in your get request, '/happy' is not a BigCommerce API endpoint--that's why you're getting a 404 not found. If you made a request to /products for example, it should work to pull product data.
Also, the callback would usually be a path on your app, not the store URL. For example, callback: 'https://myapplication.com/auth', would be the path on your app where you want the BigCommerce auth service to send your temporary code and Oauth token during the installation flow:
https://developer.bigcommerce.com/api/#app-installation-and-update-sequence
You can find examples of configuring the client and making requests in the README for the node-bigcommerce client:
https://github.com/getconversio/node-bigcommerce

Related

Sync Token in Postman

A fresher to postman, currently working on API project where I need to delivery to the API and Token the client to integrate with them system, good is I successfully configure the Authorization as OAuth Type as Password Credentials and receiving perfect response as 200.
The issue/confusion is Token is getting expire every hour, I need to Get new Access Token every time.
So, the question is, is it anyway I can overcome this issue?
that no need to get new/refresh token.
can provide the one fix token to client.
You can do it like here. You can get the token in the pre-request field of the collection or request.
https://stackoverflow.com/a/73911458/10126763
EDIT
We can adapt it like this:
Take this and paste it in the "pre-request" field of the collection or the request you will use directly. Create an "environment" value named "accessToken". When each request is run, this method will run first and send the token value to the value in the environment.
// Set refresh and access tokens
const loginRequest = {
url: "exampleurl.com/etc/etc", //YOUR URL
method: 'GET',
header: {
'content-type': 'application/json',
'Accept': "*/*"
} //Since you will be using GET, I deleted the body. If you are sending value you can get the body field from the other example in the link.
};
pm.sendRequest(loginRequest, function (err, res) {
pm.environment.set("accessToken", res.json().accessToken); //The token returned in the response and the environment value to which the value will be sent
});

jwksError: Not Found thrown by jwks-rsa module during GET request with auth bearer token to protected api

An error - “jwksError: Not Found” is thrown when I make a get request with the correct bearer token in the request header to my protected API. I’ve followed the start up guide to create the jwtCheck helper function that I pass to all my routes to protect them. I need help clarifying what this error actually means thanks!
Here I define the helper function jwtCheck which will be used to secure all routes.
var jwtCheck = jwt({
secret: jwksClient.expressJwtSecret({
cache: true,
rateLimit: true,
jwksRequestsPerMinute: 5,
jwksUri: https://${auth0Domain}/.well-known/jwks.json,
}),
algorithms: ['RS256'],
issuer: https://${auth0Domain}/,
audience: auth0ApiIdentifier,
});
Then I protect my api using jwtCheck defined above like so. After which the api will throw an Unauthorized Error if one tries to send http requests to it without a header in the request with the auth bearer token.
const app = express();
...
app.use(jwtCheck);
...
I get new Bearer tokens by sending a POST request to auth0apiIdentifier/oauth/token and putting the following in the req body:
{
"client_id":id,
"client_secret":secret,
"audience":auth0apiIdentifier,
"grant_type":"client_credentials"
}
After sending the get request via postman with the appropriate bearer token in place, rwks-rsa module throws the subsequent error:
JwksError: Not found.
at ../server/node_modules/jwks-rsa/lib/JwksClient.js:119:23
at ../server/node_modules/jwks-rsa/lib/wrappers/request.js:36:12
at processTicksAndRejections (internal/process/task_queues.js:93:5)
Img 1 - POST request to get new auth Bearer token from Auth0
Img 2 - GET request sent with postman and corresponding error thrown by jwks-rsa module.
I've fixed it! The error was way too ambiguous but after desperation set in, I checked my configs again and I found that I included a "/" at the end of my auth0apiIdentifier, this allowed a "//" in the jwksUri which caused the issue. Solving this typo was my fix.
Check your code guys! Peace!

Shopify API Cross Domain Ajax Request

I am using the below code to get the customer details from shopify. I have redirected my domain to the other domain from the shopify admin.
function setEmailWithLoggedInUser(callback) {
$.ajax({
url: 'https://new-website-shopify.myshopify.com/admin/customers/'+__st.cid+'.json',
crossDomain: true,
beforeSend: function(xhr) {
xhr.setRequestHeader("Authorization", "Basic XXXXXXXXXXXX")
}, success: function(data){
console.log(data);
if(callback)
callback();
}
})
I have done a lot of work around but unable to find the solution.
I am getting this error:
Failed to load resource: the server responded with a status of 404
(Not Found)
XMLHttpRequest cannot load
https://new-website-shopify.myshopify.com/admin/customers/7094124372.json.
Response to preflight request doesn't pass access control check:
No 'Access-Control-Allow-Origin' header is present on the requested
resource. Origin 'https://www.beirutshopping.com' is therefore not
allowed access. The response had HTTP status code 404.
I will save you some headaches with this answer. You cannot call /admin from the front-end of a store, as that exposes your access token to the public. Instead, if you want to access the API from the front-end, use the App Proxy pattern, allowing you to securely make Ajax calls to accomplish your goals.
As it is, you are almost certain to fail, and any success you hack into existence will quickly expose your shop to horrors. Like being replaced with sad pandas, or otherwise being reckd.
var cors = require('cors');
router.use(cors({
origin: '*'
}));
//var config = require('../config/config.json');
//testing /* GET home page. */
router.get('/', function (req, res, next) {
res.setHeader("Content-Type", "application/liquid");
res.setHeader("Access-Control-Allow-Origin", "*");
res.render('index', {
title: 'Store Locator'
});
});

Not able to redirect to client side with token from server(express) side route

I am using 'googleapis' npm package to do token based google authentication.
I am redirected to '/api/auth/success/google' route inside express after google provided authentication and redirects us to the uri stated in google app credentials.
The problem I am facing is that ,I have retrieved the tokens on server side,but I am unable to send those tokens to client side for them to be saved in cookies.
The problem I am facing is because,'/api/auth/success/google' is redirected from google side and not an ajax call from client side.So if I send the tokens back in res,where will it redirect.Also please suggest a way to redirect from server side to client side,along with access_token.
server side code.
//Route reached after google successful login/authentication
app.get('/api/auth/success/google',function(req,res){
console.log("inside redirect");
var code = req.query.code;
oauth2Client.getToken(code, function(err, tokens) {
// Now tokens contains an access_token and an optional refresh_token. Save them.
if(!err) {
oauth2Client.setCredentials(tokens);
}
res.sendFile('./index.html');
});
})
Client side call
//Google login requested from this function
googleLogin(){
event.preventDefault();
$.ajax({
type : 'POST',
url : baseURL + 'api/authenticate/google',
success: (function(data) {
if (data.redirect) {
document.location.href = data.redirect;
}
}).bind(this)
});
}
//Route handling request of google access
app.post('/api/authenticate/google',function(req,res){
// generate a url that asks permissions for Google+ and Google Calendar scopes
var scopes = [
googlecredentials.SCOPE[0],
googlecredentials.SCOPE[1]
];
var url = oauth2Client.generateAuthUrl({
access_type: 'offline', // 'online' (default) or 'offline' (gets refresh_token)
scope: scopes // If you only need one scope you can pass it as string
});
res.send({ redirect: url });
})
//Google App Credentials
var OAuth2 = google.auth.OAuth2;
var oauth2Client = new OAuth2(googlecredentials.CLIENT_ID, googlecredentials.CLIENT_SECRET, googlecredentials.REDIRECT_URL);
googlecredentials.CLIENT_ID - 858093863410-j9ma1i7lgapupip1ckegc61plrlledtq.apps.googleusercontent.com
REDIRECT_URL - http://localhost:3000/api/auth/success/google where localhost:3000 runs server side
If you send the redirect URL back in the res, the client-side should be able to check for the presence of the redirect URL in the response, and if it exists, push your user to that URL.

KeystoneJS Signup via Rest request

Using sydjs as book to get everything working
I'm trying to signup users via POST request via api:
/api/app/signup-email
Whenever I send data with only email&pass - everything works. If I try to add name parameter - it always fails.
Registration on front-end works as it should
Sending data as:
let parameters = [
"email": "\(email)",
"password": "\(password)",
"name": [
"first": "\(firstname)",
"last": "\(lastname)"
]
]
Maybe anyone has any idea why it doesn't work with name included? Thx.
It won't work because login request in Keystone need a _CSRF token validation, you need to provide it as parameter.
One example is first make a GET request to your login page (The CSRF Token will be in the HEADER response), save it and then make your login request passing the CSRF token obtained in the previous request.
This will be helpful KeystoneJS signin
I implemented a login against the REST-API of keystone (v4.0.0-beta.5). On the client-side I chose npm request. I enabled request's cookie-functionality (config option request.defaults({ jar: true });).
The login consisted of two separate-requests:
A simple GET-request against: https://www.yourkeystoneapp.com/keystone/session/signin
npm request will receive a cookie containing the CSRF token. There is nothing else you need to do with it. npm request will use the received cookie for all subsequent http-requests.
A POST-request containing a simple JSON body with your credentials:
{
email: 'user#yourkeystoneapp.com',
password: 'yourpassword'
}
The POST-request will be answered by Keystone with a valid user-object, if the credentials were correct.
All subsequent http-requests will be part of a valid session, as long as the CSRF-token is valid.
Code examples:
// enable cookies
request.defaults({
jar: true
});
// first request to obtain the cookie
request('https://www.yourkeystoneapp.com/signin', {/* some options */});
// second request to POST your credentials
var loginOptions = {
method: 'POST',
url: 'https://www.yourkeystoneapp.come/api/session/signin',
headers: {
'content-type': 'application/json',
'accept': 'application/json'
},
body: JSON.stringify({
email: 'user#yourkeystoneapp.com',
password: 'yourpassword
})
};
// issue POST request.
request(loginOptions);
// You are now logged in
If you are using npm request, as I did, you have to take a couple of measures to sync the requests you issue, as npm request works asynchronously. Making use of npm request's API and its callback-functions is mandatory.