I am trying to follow the instructions here to identify as an app with JWT to api.github.com:
https://developer.github.com/apps/building-github-apps/authenticating-with-github-apps/
I don't know what I'm doing wrong but I always get "bad credentials".
Can anyone look at my code here and figure it out? (Node JS)
var fs = require('fs');
var jwt = require('jsonwebtoken');
var privateKey = fs.readFileSync('doronsaartestapp.pem');
var token = jwt.sign(
{
iat: new Date().getTime() / 1000,
exp: new Date().getTime() / 1000 + 10*60,
iss: 'Iv1.5a751653c88a7cd2'//84487
},
privateKey,
{algorithm: 'RS256'}
);
console.log('token: ' + token);
var http = require('https');
var options = {
host: 'api.github.com',
path: '/repos/doronsaar/panther-proxy/hooks',
headers: {
'Accept': 'application/vnd.github.v3.raw+json',
'Authorization': 'Bearer ' + token,
'User-Agent': 'Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/85.0.4183.121 Safari/537.36'
}
};
callback = function(response) {
console.log("response status code: " + response.statusCode);
var str = '';
//another chunk of data has been received, so append it to `str`
response.on('data', function (chunk) {
console.log(chunk.toString());
});
//the whole response has been received, so we just print it out here
response.on('end', function () {
console.log("--end--");
});
}
http.request(options, callback).end();
Related
const fs = require('fs');
//var base64 = require('base64-stream');
//const getStream = require('get-stream');
var text = "Microsoft Speech Service Text-to-Speech API"
function texttospeech(text) {
var request = require('request');
var options = {
'method': 'POST',
'url': 'https://southeastasia.tts.speech.microsoft.com/cognitiveservices/v1',
'headers': {
'Authorization': 'Bearer eyJhbGciOiJodHRwOi8vd3d3LnczLm9yZy8yMDAxLzA0L3htbGRzaWctbW9yZSNobWFjLXNoYTI1NiIsInR5cCI6IkpXVCJ9.eyJyZWdpb24iOiJzb3V0aGVhc3Rhc2lhIiwic3Vic2NyaXB0aW9uLWlkIjoiZDI3YWM4ZWZlZDEyNDQ4ZTk1YmFhNWQ2MTMxODliZmUiLCJwcm9kdWN0LWlkIjoiU3BlZWNoU2VydmljZXMuRjAiLCJjb2duaXRpdmUtc2VydmljZXMtZW5kcG9pbnQiOiJodHRwczovL2FwaS5jb2duaXRpdmUubWljcm9zb2Z0LmNvbS9pbnRlcm5hbC92MS4wLyIsImF6dXJlLXJlc291cmNlLWlkIjoiL3N1YnNjcmlwdGlvbnMvMjgzZjZiOGMtMzQzOC00Yjk1LTkwOTYtOWMwZjMwNTFhMDYzL3Jlc291cmNlR3JvdXBzL3ByYWNiaXotcG9jLXJnL3Byb3ZpZGVycy9NaWNyb3NvZnQuQ29nbml0aXZlU2VydmljZXMvYWNjb3VudHMvdGV4dHNwZWVjaGV4Iiwic2NvcGUiOiJzcGVlY2hzZXJ2aWNlcyIsImF1ZCI6InVybjptcy5zcGVlY2hzZXJ2aWNlcy5zb3V0aGVhc3Rhc2lhIiwiZXhwIjoxNjUzMzYyODQ1LCJpc3MiOiJ1cm46bXMuY29nbml0aXZlc2VydmljZXMifQ.I79ZqJX3GP7gwtdx8FXFENOswQIHAAbVwPP07SEKS6g',
'Content-type': 'application/ssml+xml',
'X-Microsoft-OutputFormat': 'audio-16khz-32kbitrate-mono-mp3',
'User-Agent': 'texttospeech',
'Cookie': 'ARRAffinity=0f0eac9025c535aa027b3d037b337eec6b27b4947463810f5ef9458235c67a5d; ARRAffinitySameSite=0f0eac9025c535aa027b3d037b337eec6b27b4947463810f5ef9458235c67a5d'
},
body: '<speak version=\'1.0\' xml:lang=\'en-US\' xmlns:mstts="https://www.w3.org/2001/mstts">\r\n<voice xml:lang=\'en-US\' xml:gender=\'Male\' name=\'en-US-JennyNeural\'>\r\n<mstts:express-as role="YoungAdultFemale" style="calm" styledegree="2">\r\n<mstts:silence type="Sentenceboundary" value="200ms"/>\r\n Hi, Welcome to iNextLabs <break time="1000ms" /> \r\n <lang xml:lang="fr-FR">\r\n How can i help you?\r\n </lang>\r\n </mstts:express-as>\r\n</voice></speak>'
};
request(options, function (error, response) {
if (error) throw new Error(error);
console.log(response.body);
//var encoder = new base64.Base64Encode();
//var b64s = request(options).pipe(encoder);
//var strBase64 = yield getStream(b64s);
const fs = require('fs');
const wavUrl = 'data:audio/wav;base64,' + response.body;
const buffer = Buffer.from(wavUrl.split('base64,')[1], // only use encoded data after "base64,"
'base64');
fs.writeFileSync('./response13.mp3', buffer);
});
}
texttospeech()
I have usedtext to speech. Followed this document to get the text to speech. while running through postman the response clip was playing. But when im putting it in my code and encoding it the voice is not supporting.
Is there a way that we can upload files to shared drive using POST Method? I don't know how to call the Drive ID of the shared drive and target it to the URL fetch function, is this possible?
This is my code:
var DriveScope = 'https://www.googleapis.com/auth/drive';
var ServiceAccountPrivateKey ="-----BEGIN PRIVATE KEY----"
var ServiceAccountEmail = "drive-uploads#xxxxxxx.com";
function testinRest(){
var service = getDriveService();
var driveID = "XXXXXXXX";
var APIKey = "XXXXXXXXXXXXX";
var resumeBlob = Utilities.newBlob('Hire me!', 'text/plain', 'resume.txt');
var formData = {
'name': 'Bob Smith',
'email': 'bob#example.com',
'resume': resumeBlob
};
var url = 'https://www.googleapis.com/drive/v3/drives';
var output = UrlFetchApp.fetch(url, {
method: 'get',
headers: { 'Authorization': 'Bearer ' + service.getAccessToken() },
contentType: 'application/json'
}).getContentText();
var response= JSON.parse(output);
for(var i=0; i < response.drives.length; i++){
if(driveID == response.drives[i].id){
service.reset()
if (service.hasAccess()) {
var newPresentationName = "RJ POGI";
var url = 'https://www.googleapis.com/upload/drive/v3/files?supportsAllDrives=true&key=' + APIKey;
var body = {
"name": newPresentationName,
"parents": [driveID]
};
var params = {
headers: {
Authorization: 'Bearer ' + service.getAccessToken(),
Referer:'https://explorer.apis.google.com'
},
method: 'post',
payload: formData,//JSON.stringify(body),
contentType: 'application/json',
muteHttpExceptions: true
};
var response = UrlFetchApp.fetch(url, params).getContentText();
Logger.log('response: ' + response);
var id = JSON.parse(response).id;
return id;
}
}
}
}
function getDriveService(){
var service = OAuth2.createService('drive').setTokenUrl('https://accounts.google.com/o/oauth2/token').setPrivateKey(ServiceAccountPrivateKey).setClientId(ServiceAccountEmail).setPropertyStore(PropertiesService.getUserProperties()).setScope(DriveScope);
//console.log("Service::" + service);
//console.log('Service Has Access::' + service.hasAccess());
if (!service.hasAccess()) {
Logger.log('Authentication error: %s', service.getLastError());
return;
}else{
return service;
}
}
function reset() {
var service = getDriveService();
service.reset();
}
On this example, I want the resumeBlob to be inserted on the targeted DriveID. Any help will be appreciated. Thanks!
Your problem needs to be divided in three steps:
Create a file on the drive with UrlFetchApp
Pass a content to the file
Insert the file into a shared drive
Now, you original question - 3. is easy to solve, you just need to specify in your requestsupportsTeamDrives=true.
More difficult is the combination of 1. and 2..
The Files: create method offers either an URI for media upload only requests, or for metadata-only.
The workaround would be to perform a resumable Upload, which allows you to post the metadata first, and add the file contents later.
The URI you need to use would be "https://www.googleapis.com/upload/drive/v3/files?supportsTeamDrives=true&uploadType=resumable".
Sample:
function uploadToSharedDrive(){
var url = "https://www.googleapis.com/upload/drive/v3/files?supportsTeamDrives=true&uploadType=resumable";
var resumeBlob = Utilities.newBlob('Hire me!');
var formData = {
'name': 'Bob Smith',
'mimeType': 'text/plain',
'parents': [
"ID of the shared drive"
]
};
params = {
headers: {
Authorization: 'Bearer ' + service.getAccessToken()
},
contentType: 'application/json',
method: 'post',
payload: JSON.stringify(formData),
}
var response = UrlFetchApp.fetch(url, params);
Logger.log(response.getContentText());
data = resumeBlob.getBytes();
var params2 = {
method: "put",
payload: data,
muteHttpExceptions: true,
};
var location = response.getHeaders().Location;
var response = UrlFetchApp.fetch(location, params2);
Logger.log(response.getContentText())
}
https://instance.service-now.com/sys_report_template.do?CSV&jvar_report_id=xxxxx
This URL will only download report for which id is mentioned without mentioning the report_id how can i get all the reports?
This is some rough nodejs code, but should get you started;
var https = require('https');
var username = '';
var password = '';
var url = 'dev32369.service-now.com';
var auth = 'Basic ' + new Buffer(username + ':' + password).toString('base64');
https.request({
host: url,
port: 443,
path: '/api/now/table/sys_report?sysparm_query=field_listISNOTEMPTY&sysparm_fields=sys_id,title,filter,field,table,field_list&sysparm_limit=2',
method: 'GET',
headers: {
'Authorization': auth,
'Accept': 'application/json',
'Content-Type': 'application/json'
}
}, function (reportResponse) {
console.log('STATUS: ' + reportResponse.statusCode);
// console.log('HEADERS: ' + JSON.stringify(res.headers));
var reportResponseBody = '';
reportResponse.setEncoding('utf8');
reportResponse.on('data', function (chunk) {
reportResponseBody += chunk;
// console.log('BODY: ' + chunk);
});
reportResponse.on('end', function () {
var reports = JSON.parse(reportResponseBody).result;
console.log(reports);
if (reports[0].field_list != '') {
for (var x = 0; x < reports.length; x++) {
var report = reports[x];
var path = '';
path += '/api/now/table/' + report.table;
path += '?sysparm_fields=' + report.field_list;
path += '&sysparm_query=' + encodeURIComponent(report.filter);
path += '&sysparm_display_value=true';
path += '&sysparm_exclude_reference_link=true';
// path += '&sysparm_limit=2';
console.log(path);
var optionsCSV = {
host: url,
port: 443,
path: path,
method: 'GET',
headers: {
'Authorization': auth,
'Accept': 'application/json',
'Content-Type': 'application/json'
}
};
console.log(optionsCSV);
https.request(optionsCSV, function (csvResponse) {
try {
var csvResponseBody = '';
csvResponse.on('data', function (chunk) {
console.log('downloading report[' + report.title + ']...');
csvResponseBody += chunk;
});
csvResponse.on('end', function () {
//console.log(csvResponseBody);
var csvResponseObj = JSON.parse(csvResponseBody).result;
console.log(csvResponseObj);
//this is a json obj but you can rewriet is csv here
});
csvResponse.on('error', function (err) {
console.log(err);
});
} catch (e) {
console.log(e);
}
}).end();
}
}
});
}).end();
I have setup steps before running my e2e test in which I have to create users before I execute my test. I am using Protractor's Request API to make REST API POST calls but I'm not sure how can I pass data (body) and headers in the request. My request should look like this:
URL : 'rest/users', Headers : {'Content-Type' : 'application/json'}, body: {"userName": "user1", "domain": "1", "password": "password1", "userID": "1"}
I am trying to do something like this:
var request = require('request');
function createuser(url){
console.log("complete url = ", browser.baseUrl+url);
request({
method: 'POST',
uri: browser.baseUrl+url,
multipart: [
{'Content-Type': 'application/json'},
{body: {
'userName': 'test3',
'tenantKey': '0',
'password': 'Test3',
'userID': '3'}
}
],
function(error, response, body) {
if (error) {
return console.error('User Creation failed:', error);
}
console.log('User Creation successful! Server responded with:', body);
}
})
};
createuser('rest/1.0/dev/users');
It's throwing the following error (I'm not sure what am I doing wrong):
Error: Body attribute missing in multipart.
Stack:
Error: Body attribute missing in multipart.
at C:\code\ui\dgui\node_modules\request\lib\multipart.js:35:36
at Array.forEach (native)
at Multipart.isChunked (C:\code\ui\dgui\node_modules\request\lib\multipart.js:33:11)
at Multipart.onRequest (C:\code\ui\dgui\node_modules\request\lib\multipart.js:104:22)
at Request.multipart (C:\code\ui\dgui\node_modules\request\request.js:1176:19)
at Request.init (C:\code\ui\dgui\node_modules\request\request.js:424:10)
at new Request (C:\code\ui\dgui\node_modules\request\request.js:142:8)
at request (C:\code\ui\dgui\node_modules\request\index.js:55:10)
at createuser (C:\code\ui\dgui\tests\e2e\TestSuites\_BVT\_CreateNewUsers2.js:36:2)
at Suite.<anonymous> (C:\code\ui\dgui\tests\e2e\TestSuites\_BVT\_CreateNewUsers2.js:49:3)
I am able to achieve this using 'superagent', this is how I am using:
CallRestAPI:
var request = require( "superagent" );
var PostUrl = browser.baseUrl + 'rest/1.0/dev/users';
exports.CreateUsers = function(body){
console.log("Executing CreateUsers");
var data = '{' +body + '}';
console.log("Send data in post request = ", data);
request.post( PostUrl ).set('Content-Type', 'application/json').send(data).end(function(err,res){
if(err){
console.log("CreateUsers post error= ", err )
} else{
console.log("CreateUsers post response = ", res.status)
}
});
};
Using this Function as:
var Common = require('../.././helpers/CallRestAPI');
Common.CreateUsers('"userName": "test1", "tenantKey": "0", "password": "Test1", "userID": "1"');
Have managed it in my code with request validation when eg. access token is wrong or app do not respond. Imo it's better approach because your proposition always passes test what can give false positive.
exports.authorize = function (login, pass) {
var action = function () {
return getToken().then(function (token) {
var dfd = protractor.promise.defer();
req.post(getBackendUrl() + '/authorize/authenticate')
.set('Content-Type', 'application/json').set('RequestId', uuid.v4()).set('Authorization', token)
.send({"login": login, "pass": pass})
.end(function (err, res) {
if (err) {
dfd.reject(res)
} else {
dfd.fulfill(res.body);
}
});
return dfd.promise;
})
};
return browser.controlFlow().execute(action);
};
Endpoint authorize returns 200 status code for both - valid and not valid credentials so in specific test it can be distincted by simple jasmine expect like:
var Initialize = require('..initialize');
var successResponse = {status: 'success'};
expect(Initialize.authorize('some_login', 'some_password')).toEqual(successResponse);
var request = require('request');
var options = {
method: 'POST',
url: 'https://sbx-office-api.b2bcloud.com/rmi/v1/books/list?type=fetchall',
headers: {
'Accept': 'application/json, text/plain, */*',
'Authorization': 'Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsImtpZCI6IlFrTTFRemt6UlVJNE5UazNSVVJGTUVVNU5rTXlNVVpFT0RJek5EQTNPRFkyTVVaRVFrVXdSZyJ9.eyJodHRwczovL21hcnZlbC5zaGFycC5jb20vdGVuYW50aWQiOiJkNTA4Yjc3NC01NjBlLTRlNTktYTk3Yy1mODQxYjhmYjVkN2QiLCJodHRwczovL21hcnZlbC5zaGFycC5jb20vY29ubmVjdGlvbiI6InNoYXJwc29mdHdhcmVkZXYtd2FhZCIsImh0dHBzOi8vbWFydmVsLnNoYXJwLmNvbS9lbWFpbCI6InJhbWVzaHRAU2hhcnBzb2Z0d2FyZWRldi5vbm1pY3Jvc29mdC5jb20iLCJodHRwczovL21hcnZlbC5zaGFycC5jb20vbmFtZSI6IlJhbWVzaCBUIiwiaHR0cHM6Ly9tYXJ2ZWwuc2hhcnAuY29tL3JvbGUiOiJCQSB1c2VyIiwiaXNzIjoiaHR0cHM6Ly9zYnguYXV0aDAuY29tLyIsInN1YiI6IndhYWR8VGVFbVNzNGpnRGpXeTRVX0ItWlo4SDRobFZielVUdzM4djNmb2MzNXVzWSIsImF1ZCI6WyJodHRwczovL3NieC5hdXRoMC5jb20vYXBpL3YyLyIsImh0dHBzOi8vc2J4LmF1dGgwLmNvbS91c2VyaW5mbyJdLCJpYXQiOjE1NjY5NzY4MzIsImV4cCI6MTU2Njk4NDAzMiwiYXpwIjoiQW1zeU9UbHI3akg5eFU5azZlem15ODJNZDV4NDUyZFIiLCJzY29wZSI6Im9wZW5pZCBwcm9maWxlIn0.D5MoBVJ2lWZ7b3FCZtMQkmdMxJot8SCR1-Oso-wponPtF2y6kLxKK5dUftI_yzydvaJsZ9mwjVvZIAHESlrwkjVizYGXTFchjasT81hMZtJgt6iW8sA7Nu5qx7MVsc2z7UAS0mGhV2a_NEvZaYQ1A0dC19wG2A6bNJIMNEy46oJXlUe8nxb1ezkh4CkO3jUnVIPBo4rney_uwcXj-wc5hiE3a6m7jeHphyy70zDBFD_YRiizZaXzI-LTPGvhuRb7UtfcZuOomQqOuH6xebaoe3OzX9aA7CfWCHIJDhjQJwC-5BR5HQ9k7FCae3L4pWfmUVUOTZEFViJtxazLxOjM_w',
'Content-Type':'application/json',
'Sec-Fetch-Mode': 'cors',
'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.87 Safari/537.36'
},
body: '{ "headers":{"normalizedNames":{},"lazyUpdate":null}}'
};
it('Should reach testsite', done => {
request(options, function (error, response, body) {
console.log('error:', error);
console.log('statusCode:', response && response.statusCode);
console.log('body:', body);
done();
});
});
I'm trying to authenticate user in facebook:
var querystring = require('querystring');
var http = require('http');
var fs = require('fs');
getCookies(function(cookies){
logIn(cookies);
});
function logIn(cookies) {
var post_data = querystring.stringify({
'email': 'email#domain',
'pass': 'password'
});
var post_options = {
host: 'www.facebook.com',
port: '80',
path: '/login.php?login_attempt=1',
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Content-Length': post_data.length,
'user-agent': 'Mozilla/5.0',
'set-cookie': cookies[0]
}
};
var post_req = http.request(post_options, function(res) {
res.setEncoding('utf8');
console.log(res.statusCode);
var data = '';
res.on('data', function (chunk) {
data += chunk;
});
res.on('end', function () {
fs.writeFile("C:\\Users\\user\\Desktop\\fb.html", data, function(err) {
if(err) {
console.log(err);
} else {
console.log("The file was saved!");
}
});
});
});
post_req.write(post_data);
post_req.end();
}
function getCookies(callback){
var get_options = {
host: 'www.facebook.com',
port: '80',
path: '/',
method: 'GET',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'user-agent': 'Mozilla/5.0'
}
};
var get_req = http.request(get_options, function(res) {
var cookies = res.headers['set-cookie'];
res.on('end', function (chunk) {
callback(cookies);
});
});
get_req.write('');
get_req.end();
}
But the response is that cookies in my browser are not enabled. Please don't suggest using existing libraries for connecting to facebook, I'm learning... Thanks for help in advance
Facebook uses OAuth authentication to authenticate an user. I have used oAuth module to get access to the Linkedin APIs at http://nabaruns.blogspot.in/2013/01/linkedin-api-call-using-nodejs-oauth.html. You can try the same and see if you can call graph facebook apis.
Hope this helps