npm package simple-oauth2 404 not found - javascript

I have a weird bug going on with my code.
I'm using the simple-oauth2 library (https://github.com/lelylan/simple-oauth2) and my code works fine on Windows.
When I try to run my code on a linux server (raspberry pi zero), the oauth library keeps on returning 404 Not Found for my oauth request (specifically "Access Token Error Not Found" as per the code below).
What's going on?
Code (working with Yelp API):
var fs = require('fs');
var cID = fs.readFileSync('blahblahblah', 'utf8');
var cSecret = fs.readFileSync('blahblahblah2', 'utf8');
var credentials = {
client: {
id: cID,
secret: cSecret
},
auth: {
tokenHost: 'https://api.yelp.com',
tokenPath: '/oauth2/token'
}
};
var oauth2 = require('simple-oauth2').create(credentials);
var tokenConfig = {};
module.exports.gimmeMuhToken = function(cb) {
oauth2.clientCredentials.getToken(tokenConfig, function(error, result) {
if (error) {
return console.log('Access Token Error', error.message);
}
cb(oauth2.accessToken.create(result).token.access_token); // Return the token
});
};
Thanks

Found the culprit.
It was line endings...

Related

nuxt app deployed to Netlify: fetch to api working locally, but not on deployed site: getting a 404

I have a Nuxt.js app that I'm trying to deploy to Netlify - and everything works on my local machine, but the fetch request to the api returns a 404 when it's deployed to Netlify. I don't know how to make that server route available to my client when it's deployed.
the fetch request in my api-client.js file looks like this:
async fetchInfo(state) {
let response = await fetch(`/api/info/${state}`);
let data = await response.json();
return data;
}
and the api looks like this (in api/index.js file):
const rp = require('request-promise');
const apiKey = process.env.POLICY_API_KEY;
export default function (req, res, next) {
if (req.url.includes("/info")) {
let stateAbbr = req.originalUrl.slice(-2);
rp({
uri: `https://third-party-api-here.com/states/${stateAbbr}/`,
method: 'GET',
headers: {
'token': apiKey,
},
json: true
}).then(function success(response) {
if (response) {
res.setHeader('Content-Type', 'application/json');
res.end(JSON.stringify(response));
return;
}
}).catch(function error(response) {
console.log('error', response.error);
});
return;
}
next();
}
I think this might have something to do with CORS? I'm getting this error in the browser when I try to hit that route in the deployed app:
GET https://my-app-name.netlify.app/api/info/MN 404
SyntaxError: Unexpected token < in JSON at position 0
As mentioned in the comment above, you need to have a Node.js of some sort.
Hence, hosting on Heroku fixed OP's issue (Netlify is only for static files).

Unable to upload a file to box (file storage system)

I am completely new to authentication concepts. The goal is to upload files to box using box-node-sdk (a node pacakge), I was advised to do Oauth with JWT to box in-order to manage my application data on box. But I keep keep getting the following error
err: Error: error:0906D06C:PEM routines:PEM_read_bio:no start line
Following is the code in my back-end. Please help me in learning and understanding this.
All my keys are coming from env.
var BoxSDK = require('box-node-sdk');
var sdk = new BoxSDK({
clientID: process.env.BOX_CLIENT_ID,
clientSecret: process.env.BOX_CLIENT_SECRET,
appAuth: {
keyID: process.env.BOX_PUBLIC_KEY_ID,
privateKey: process.env.BOX_PRIVATE_KEY,
passphrase: process.env.BOX_PASSPHRASE,
expirationTime: 60,
verifyTimestamp: false,
},
enterpriseID: process.env.BOX_ENTERPRISE_ID
});
var fs = require('fs');
var path = require('path');
// Get an app user client
var client = sdk.getAppAuthClient('user', process.env.BOX_APP_USER_ID);
var fileData = fs.createReadStream('hello_world.png')
client.files.uploadFile('71331215581', 'hello_world.png', fileData,
function(err, file) {
if (err) {
console.log('err: ' + err);
} else {
console.log('file uploaded: ' + file);
}
})

Missing ; before statement (Jira Addon - oAuth)

I get the error:
[WARNING] File encoding has not been set, using platform encoding windows-1252, i.e. build is platform dependent!
[INFO] Compiling javascript using YUI
[ERROR] missing ; before statement let privateKeyData = fs.readFileSync('location','utf-8');
As shown I have put the ; before let. I don't understand the error. I am creating an add-on for Jira. I started the JS file via cmd and it worked. However when I want to package the project I get that error. Please help.
jQuery(function($) {
var initmyConfluenceMacro = function() {
$(".myConfluenceMacro").each(function() {
const request = require('request');
const fs = require('fs');
let privateKeyData = fs.readFileSync('filelocation', 'utf-8');
const oauth = {
consumer_key: 'mykey',
consumer_secret: privatkey,
token: 'mytoken',
token_secret: 'tokensecret',
signature_method: 'signaturemethod'
};
request.get({
url: 'thelink',
oauth: oauth,
qs: null,
json: true
}, function(e, r, user) {
console.log(user)
});
var html = "output";
$(this).html(html);
});
};
$(document).ready(function() {
initmyConfluenceMacro();
});
});
The problem for the error is
const fs = require('fs');
fs is for (as on their page) security reasons removed from Atlassian and cannot be used. My workaround was to use the velocity template, in order to import the file, and then to parse it to the js file.
I hope this helps. If someone has other ideas please let me know.

Node.js + Express not writing to file using FS

I have a file that I am trying to write to from a post. Currently, the FS does not error nor does it write to file. However, when taking the same code from the deployed build and running it locally, it works. I even kept the file path consistent since it was throwing no permissions error at first. I ensured this file wrote to the same directory so each Filewrite Stream process would look at the same directory and file.
Local build:
var fs = require('fs');
const path = require('path');
var user_name = 'Password';
var password = 'test';
var errSTR = ""
fs.writeFile('C:\\hi.txt', 'Content to write', { flag: 'w' }, function(err) {
if (err)
return console.error(err);
fs.readFile('C:\\hi.txt', 'utf-8', function (err, data) {
if (err)
return console.error(err);
console.log(data);
});
});
Deployed Build:
app.route('/test')
.get(function(req, res) {
res.send('GET test');
})
.post(function(req, res) { // Start Post
var boolTry = false;
try {
boolTry = true;
var bool = false
var user_name = "Password"//req.body.user;
var password = "test"//req.body.password;
var errSTR = ""
fs.writeFile('C:\\hi.txt', user_name + password, { flag: 'w' }, function(err) {
if (err)
return console.error(err);
fs.readFile('C:\\hi.txt', 'utf-8', function (err, data) {
if (err)
return console.error(err);
res.send(500 + err);
console.log(data);
});
})
} catch (error) {
bool = true
errSTR = error
}
res.send('POST test' + " " + boolTry + " " + bool + " " + errSTR + ";")
})//END POST
.put(function(req, res) {
res.send('PUT test');
});
The local build will properly write to the file, while the dev build appears to do nothing. It should be noted by booleans were being used to understand how the file writer works but here is the server response from build: successful response POST test true false ;
Using:
IISNODE for iis: 7.x
Express: 4.16.2
node.js: v8.9.4
cors: 2.8.4
body-parser: 1.17.2
Sidenote: If you are confused by the writing portion of code, the intention was to write, check error then read, check error for assurance.
Update
Reoccurring error based on certain filewrite methods Error: EPERM: operation not permitted, open. Yes, all permissions for the directory are enabled along with ensuring read and write are checked.

Can't Upload APK to Google Play Developer via Publisher API

i'm creating script using nodejs to upload my APK to Google Play Developer via Publishing API, however it failed. I think, it's nothing wrong with APK file, because it's good file. so any idea to solve this ?
i also try multipart upload, but return error ( i will attach here soon )
Below are the Error message :
Upload successful! Server responded with: {
"error": {
"errors": [
{
"domain": "androidpublisher",
"reason": "apkInvalidFile",
"message": "Invalid APK file."
}
],
"code": 403,
"message": "Invalid APK file."
}
}
My Source Code
var https = require('https');
var request = require('request');
https.post = require('https-post');
var fs = require('fs');
var tokens = process.argv[2];
var formData = {
my_file: fs.createReadStream('example_file.apk')
}
if (tokens != '')
{
var url_create_listing = 'https://www.googleapis.com/androidpublisher/v2/applications/com.example.apps/edits?access_token='+tokens;
request.post( url_create_listing, function (error, response, body) {
var str_body = JSON.parse (body);
var listing_id = str_body.id;
var url_upload = 'https://www.googleapis.com/upload/androidpublisher/v2/applications/com.example.apps/edits/'+listing_id+'/apks?uploadType=media&access_token='+tokens;
var options = {
url: url_upload,
headers: {
'Content-Type': 'application/vnd.android.package-archive'
}
};
request.post( options, function optionalCallback(err, httpResponse, body)
{
if (err) {
return console.error('upload failed:', err);
}
console.log('Upload successful! Server responded with:', body);
}).pipe(fs.createReadStream('example_file.apk'));
});
}
I think you have a misunderstanding of how NodeJS streams works.
In the sample code you have shown above you are trying to pipe the result of request.post into fs.createReadStream which doesn't make sense and that's reason for the error as you are not sending any apk file. Instead it should be done like the following. (I am not sure how androidpublisher api works, I assume your sample shows the correct usage.)
var url_create_listing = 'https://www.googleapis.com/androidpublisher/v2/applications/com.example.apps/edits?access_token='+tokens;
request.post( url_create_listing, function (error, response, body) {
var str_body = JSON.parse (body);
var listing_id = str_body.id;
var url_upload = 'https://www.googleapis.com/upload/androidpublisher/v2/applications/com.example.apps/edits/'+listing_id+'/apks?uploadType=media&access_token='+tokens;
// request module is capable of auto detecting the Content-Type header
// based on the file extension.
var options = {
url: url_upload
};
fs.createReadStream('example_file.apk')
.pipe(request.post(options, function optionalCallback(err, httpResponse, body){
if (err) {
return console.error('upload failed:', err);
}
console.log('Upload successful! Server responded with:', body);
}));
According to https://developers.google.com/games/services/publishing/ :
The Google Play games services Publishing API allows you to automate
frequent tasks having to do (...)
Are you under the absolute constraint to use JS & node.js for this task ? If not, you may find useful this Google management-tools code example.
In this repository you can find tools to help you publish, manage, and
test your Play Games services apps
In my opinion, it is always better to install Python (and re-use official code) to do this.
(Google Devs apparently prefer python for this kind of task)
Have you looked at fastlane.tools? Full scripting of publishing, uploading, taking screenshots, slack notifications, and a lot more for both Android and iOS.

Categories

Resources