Authenticate to JIRA using node-jira module - node.js

I need to connect my application to JIRA API, and I found module node-jira, that should help me with that.
However, I'm having problem with authentication.
Here's what I done (nothing special, but for some reason, it doesn't work):
var JiraApi = require('jira').JiraApi;
var jira = new JiraApi('https', '[url to my jira project]', 443, '[username]', '[password]', '2.0.alpha1');
jira.getCurrentUser(function(error, issue) {
if(error){
console.log(error);
return;
}
console.log('success');
});
I receive:
401: Error while getting current user
Any ideas what could go wrong?

After digging into source code, looks like mentioned method isn't making request properly.
It does this.request instead of this.doRequest. I'll submit it to github repo.

This may give you some ideas; it's not a call to get an issue from JIRA, but it shows how to set up an Atlassian API call (from Google Sheets). You just need to plug in the right URL and Endpoint (for a JIRA issue as an example).
function showAtlassian() {
var html = HtmlService.createHtmlOutputFromFile('atlassianform')
.setWidth(200)
.setHeight(200);
SpreadsheetApp.getUi().showModalDialog(html, 'Atlassian Login');
}
function processAtlassian(myForm) {
var username = myForm.un;
var userpw = myForm.pw;
var myencoded = Utilities.base64Encode(username+":"+userpw);
var headers = {"Authorization" : "Basic " + myencoded};
var options = {
'method': 'get',
"contentType" : "application/json",
"headers": headers,
'muteHttpExceptions': false
}
var ui = SpreadsheetApp.getUi();
url = 'https://---your domain --/wiki/rest/api/user/current';
try {
var response = UrlFetchApp.fetch(url, options);
var data = JSON.parse(response)
var result = ui.alert( 'got valid connection userkey ' + data.userKey );
} catch(error) {
var result = ui.alert( 'invalid user or password: url: '+ url +' err: ' + error.toString());
getatlassian();
}
}
function getatlassian() {
var ui = SpreadsheetApp.getUi();
showAtlassian()
}

Related

EJS page not rendering /redirecting after req.getValidationResult() method

Ajax request has the following code:
function validate_referral(e){
// stop default action
e.preventDefault();
const button = this.children[this.children.length-1];
//Form Handling with ajax
$.ajax({
url : '/validatereferral',
method : 'GET',
data : $(this).serialize(),
dataType : 'json',
beforeSend : function(http){
button.style.opacity = '0.7';
button.innerText = 'Submitting';
button.setAttribute("disabled", "true");
},
});
}
Now i am validating in the DB if the code exists and if so i would like to render/redirect to a different web page. But render/redirection is failing. Any help is much appreciated.
router.get('/validatereferral',function(req,res){
var referralCode = req.body.referralcode;
if(referralCode == ""){
data = {msg:"Referral Code is required.",param:"",success:false};
}else {
var validation = req.checkBody('referralcode', 'Referral code already exist. Please enter a unique code').isExist_referralcodegen();
req.getValidationResult()
.then(function(result) {
var error = result.array();
var data;
if (!(error.length == 0)) {
data = {msg: "This is an invalid referral code.", success: false};
res.send(data);
}
console.log("validgen");
//res.redirect("http://localhost:3000/signup")
res.render('signup',{title:"Community Network | Sign Up",header:false,navbar:false});
})
}
});
You are sending an AJAX request. In AJAX response, redirect or render will not be reflected on your website. Instead your server should response the url and client have to change browser url.
$.ajax({
url : '/validatereferral',
method : 'GET',
data : $(this).serialize(),
dataType : 'json',
beforeSend : function(http){
button.style.opacity = '0.7';
button.innerText = 'Submitting';
button.setAttribute("disabled", "true");
},
}).done(function(data) {
location.href = data;
});
In server,
res.send("http://localhost:3000/signup")

Access denied, SharePoint app. Copy file to another site collection

UPDATE: I understand now that by installing an app in web scope, it only gets access to the hostweb and appweb. So I tried to batchinstall the app - and now the APP works.
However, the App Part isnt available other than in the App Catalog.
Does Anyone know a way to give the App Part permissions to other site collections, or batch install the App Part so its available in other places than app catalog?
have this code that I'm using for downloading a file from one sitecollection, and trying to upload it to another, in sharepoint online.
I'm getting a 403 that im not allowed to upload the file. The DOWNLOAD is fine.
Does anyone have any clues?
var web;
var hostweburl;
var appweburl;
$(document).ready(function () {
sharePointReady();
});
function sharePointReady() {
hostweburl =
decodeURIComponent(
getQueryStringParameter('SPHostUrl')
);
appweburl =
decodeURIComponent(
getQueryStringParameter('SPAppWebUrl')
);
var scriptbase = hostweburl + '/_layouts/15/';
$.getScript(scriptbase + 'SP.Runtime.js',
function () {
$.getScript(scriptbase + 'SP.js',
function () { $.getScript(scriptbase + 'SP.RequestExecutor.js', copyAndUploadFile); }
);
}
);
}
function getQueryStringParameter(param) {
var params = document.URL.split("?")[1].split("&");
var strParams = "";
for (var i = 0; i < params.length; i = i + 1) {
var singleParam = params[i].split("=");
if (singleParam[0] == param) {
return singleParam[1];
}
}
}
function copyAndUploadFile() {
var targetUrl = "https://sogetiumea-my.sharepoint.com/personal/simonagren_sogetiumea_onmicrosoft_com";
var executor = new SP.RequestExecutor(appweburl);
var fileContentUrl = "_api/SP.AppContextSite(#target)/web/GetFileByServerRelativeUrl('/_catalogs/theme/15/fontscheme003.spfont')/$value?#target='" + hostweburl + "'";
var fileTargetUrl = "_api/SP.AppContextSite(#target)/web/GetFolderByServerRelativeUrl('_catalogs/theme/15')/Files/Add(url='fontscheme003.spfont', overwrite=true)?#target='" + targetUrl + "'";
$.ajax({
url: "_api/contextinfo",
type: "POST",
contentType: "application/x-www-url-encoded",
dataType: "json",
headers: {
"Accept": "application/json; odata=verbose",
},
success: function (data) {
var digest = data.d.GetContextWebInformation.FormDigestValue;
var getFileAction = {
url: fileContentUrl,
method: "GET",
binaryStringResponseBody: true,
success: function (getFileData) {
var results = data.body;
var copyFileAction = {
url: fileTargetUrl,
method: "POST",
headers: {
"Accept": "application/json;odata=verbose",
"X-RequestDigest": digest
},
contentType: "application/json;odata=vebose",
binaryStrinRequestBody: true,
body: getFileData.body,
success: function (copyFileData) {
alert("kopiering gick bra");
},
error: function (ex) {
alert(JSON.stringify(ex));
}
};
executor.executeAsync(copyFileAction);
},
error: function (ex) {
alert(JSON.stringify(ex));
}
};
executor.executeAsync(getFileAction);
},
error: function (ex) {
alert(JSON.stringify(ex));
}
});
}
I used a workaround of sort.
I added the app part to the app catalog, and used a hardcoded value to the mysite site collection (used as source for downloading/copying the file).
Using developer tools I copied the html for the iframe used to show the app part i n the app catalog.
I activated publishing on mysites root site collection.
I added a scripteditor webpart. Then I added the copied iframe code. Voila, now the "app part" works.
At first the app listens to the current user, checks if a personal site exists, else it creates it.
Copies as cusom spcolor file from the mysite "_catalogs/theme/15" to same folder on the current users personal site.
Applies the spcolor file in "Applytheme".
This is based on the idea that Vesa has done with a provider hosted app!

Req.data not showing up once sent to server with POST method (using connect middleware)

I'm unable to get the var data I sent in via a POST method. This should be easy (right?), but I'm clearly missing something (either conceptually or a setting).
At this stage, I simply want to check to see if the server side code will output the data to the console. The array is being stringify-ed correctly, eg. ['one','two','three'] becomes 0=one&1=two&2=three
but I can't pull it out on the server side.
What am I missing?
Client side
var qs = require('querystring')
, http = require('http');
var some_array = ['one','two','three'];
var data = qs.stringify(some_array);
var options = { host: 'localhost',
path: '/search',
port: '3000',
method: 'POST',
headers: { 'content-length': Buffer.byteLength(data),
'Content-Type': 'application/json' }
}
function go_post(data) {
req = http.request(options, function(res) {
// do something with response
});
req.write(data);
req.end();
};
go_post(data);
Server side
var connect = require('connect');
var qs = require('querystring');
var server = connect.createServer();
server.use(function(req,res,next) {
if ( '/search' == req.url && req.method == 'POST' ) {
// quick check to see if data came through
console.log('BODY IS ' + req.data);
} else {
next();
};
});
These objects arent available because they are still in the "raw" request. You have to use a middleware like connect().use(connect.bodyParser()) in order to get them from the request via req.data.

Node.js and twilio integration

I am trying to integrate twilio with Node.js+express.
I don't have a site yet. what value should I give for HOSTNAME, along with SID and AUTH_TOKEN, these values I got from twilio site.
I have written some code, whatever suggestion given below I have placed in to views folder in twiclient.js , I have added a route in app.js to redirect the request if /twi is called , but I am not getting any result. some errors are appearing in the console, would you please help me figure out what I'm doing wrong? I have placed the correct SID, token and hostname, as specified below.
app.js has the following entry, does anything else need to be done for the twilio calling part to work?
Also, where should I define the GUI for calling a phone in the views folder?
var TwilioClient = require('twilio').Client,
      Twiml = require('twilio').Twiml,
      sys = require('sys');
var client = new TwilioClient('MY_ACCOUNT_SID', 'MY_AUTH_TOKEN', 'MY_HOSTNAME');
var phone = client.getPhoneNumber('+2323232323');
phone.setup(function() { phone.makeCall('+15555555555', null, function(call) {});
phone.setup(function() {
    phone.makeCall('+15555555555', null, function(call) {
        call.on('answered', function(callParams, response) {
            response.append(new Twiml.Say('Hey buddy. Let\'s meet for drinks later tonight.'));
            response.send();
        });
    });
});
The hostname is 'api.twilio.com'. Your SID and AUTH_TOKEN come from your twilio account. When you log in, go to the dashboard. You'll find your SID and AUTH_TOKEN listed there.
Here's the code I use to make a request to twilio to place a call. It should help you get started.
var https = require('https');
var qs = require('querystring');
var api = 'your api key';
var auth = 'your auth token';
var postdata = qs.stringify({
'From' : '+5554321212',
'To' : '+5552226262',
'Url' : 'http://yourwebsite.com/call'
});
var options = {
host: 'api.twilio.com',
path: '/2010-04-01/Accounts/<your api key>/Calls.xml',
port: 443,
method: 'POST',
headers: {
'Content-Type' : 'application/x-www-form-urlencoded',
'Content-Length' : postdata.length
},
auth: api + ':' + auth
};
var request = https.request(options, function(res){
res.setEncoding('utf8');
res.on('data', function(chunk){
console.log('Response: ' + chunk);
})
})
request.write(postdata);
request.end();

LinkedIn API Fails - Node.js Request

I am trying to make REST API calls to Node.js using request module. I have obtained accessToken and accessTokenSecret.
When I make an api call to obtain my profile I get a result, but when I make an api call to do a company search I get the following error
<error>
<status>401</status>
<timestamp>1345187981287</timestamp>
<request-id>HE45IXV7YZ</request-id>
<error-code>0</error-code>
<message>[unauthorized]. OAU:xxxxx|xxxxx|*01|*01:1345188248:kCNFNUu6JePTEy7k5e8Ca9vHAzg=</message>
</error>
But when I make the same API call using JAVA (Scribe jar), using the same accessToken and accessTokenSecret I get results for the company search.
I am posting my node.js code below for reference
//oauth test
var request = require('request');
var key = 'xxxxx';
var secret = 'xxxxx';
var redirect = '';
var restURL = 'http://api.linkedin.com/v1/company-search?keywords=philips&format=json';
var accessToken = 'xxxxx';
var accessTokenSecret = 'xxxxx';
var proxySetting = "http://proxy:port/";
function getRequestToken()
{
var requestOAuth =
{
consumer_key: key
, consumer_secret: secret
//, token: accessToken
//, token_secret: accessTokenSecret
};
var requestTokenURL = 'https://api.linkedin.com/uas/oauth/requestToken';
request.get({'proxy':proxySetting,url:requestTokenURL,oauth:requestOAuth},function(e,r,data)
{
console.log('Error is: ' + e);
console.log('Data is: ' + data);
console.log('Response is: ' + r);
});
}
function getAccessToken()
{
var accessOAuth =
{
consumer_key: key
, consumer_secret: secret
, token: 'xxxxx'
, token_secret: 'xxxx'
,verifier : #####
};
var accessTokenURL = 'https://api.linkedin.com/uas/oauth/accessToken';
request.get({'proxy':proxySetting,url:accessTokenURL,oauth:accessOAuth},function(e,r,data)
{
console.log('Error is: ' + e);
console.log('Data is: ' + data);
console.log('Response is: ' + r);
});
}
/
function comSearch()
{
var apiToken = 'xxxxx';
var apiTokenSecret = 'xxxxx';
var apiOAuth =
{
consumer_key: key
, consumer_secret: secret
, token: apiToken
, token_secret: apiTokenSecret
};
var apiURL = 'http://api.linkedin.com/v1/company-search?keywords=philips';
var peopleProfile = 'http://api.linkedin.com/v1/people/~';
request.get({'proxy':proxySetting,url:apiURL,oauth:apiOAuth},function(e,r,data)
{
console.log('Error is: ' + e);
console.log('Data is: ' + data);
console.log('Response is: ' + r);
});
}
comSearch();
Following is my header
Response is: GET http://api.linkedin.com/v1/company-search?keywords=philips HTTP/1.1
host: api.linkedin.com
Authorization: OAuth keywords="philips",oauth_consumer_key="xxx",oauth_nonce="xxx",oauth_signature_method="HMAC-SHA1",oauth_timestamp="1345189928",oauth_token="xxx",oauth_version="1.0",oauth_signature="xxx"
content-length: 0
Connection: keep-alive
Could there be some error due to the signature issues ?
I have posted this Issue, but posting it here to reach a wider audience
EDIT 1
Reason why I am using the request module is, it helps me do oauth behind a proxy.
I would love to try out Passport.js or node-oauth or linked-in but none seem to have options where I can specify my proxy
I managed to get it work using node-oauth
Apparently there was code fix provided so that we could access node-oauth over the proxy and that works perfectly fine.
The fix for using node-oauth over a http-proxy was mentioned by Jared Hanson in this SO Question. This fix for node-oauth over a http-proxy can be found here
Please, share your generated base signature string. It seems like your query params were not corectly added to the signature string. In some old post on linkedIn forum I've seen that params need to be organized in the string to sign in alphanumeric order.

Resources