Atlassian Connect-Express: JIRA REST API authentication within the JIRA plugin - node.js

i am using the atlassian-connect-express toolkit for creating Atlassian Connect based Add-ons with Node.js.
It provides Automatic JWT authentication of inbound requests as well as JWT signing for outbound requests back to the host.
The add-on is authenticated when i install it in the JIRA dashboard and return the following pay-load:
{ key: 'my-add-on',
clientKey: '*****',
publicKey: '********'
sharedSecret: '*****'
serverVersion: '100082',
pluginsVersion: '1.3.491',
baseUrl: 'https://myaccount.atlassian.net',
productType: 'jira',
description: 'Atlassian JIRA at https://myaccount.atlassian.net ',
eventType: 'installed' }
But i am not able to authenticate the JIRA Rest Api with the JWT token generated by the framework. It throws below error message.
404 '{"errorMessages":["Issue does not exist or you do not have permission to see it."],"errors":{}}'
below is the code when i send a GET request:
app.get('/getissue', addon.authenticate(), function(req, res){
var request = require('request');
request({
url: 'https://myaccount.atlassian.net/rest/api/2/issue/ABC-1',
method: 'GET',
}, function(error, response, body){
if(error){
console.log("error!");
}else{
console.log(response.statusCode, body);
}
});
res.render('getissue');
});
Below is the code for my app descriptor file:
{
"key": "my-add-on",
"name": "Ping Pong",
"description": "My very first add-on",
"vendor": {
"name": "Ping Pong",
"url": "https://www.example.com"
},
"baseUrl": "{{localBaseUrl}}",
"links": {
"self": "{{localBaseUrl}}/atlassian-connect.json",
"homepage": "{{localBaseUrl}}/atlassian-connect.json"
},
"authentication": {
"type": "jwt"
},
"lifecycle": {
"installed": "/installed"
},
"scopes": [
"READ",
"WRITE"
],
"modules": {
"generalPages": [
{
"key": "hello-world-page-jira",
"location": "system.top.navigation.bar",
"name": {
"value": "Hello World"
},
"url": "/hello-world",
"conditions": [{
"condition": "user_is_logged_in"
}]
},
{
"key": "getissue-jira",
"location": "system.top.navigation.bar",
"name": {
"value": "Get Issue"
},
"url": "/getissue",
"conditions": [{
"condition": "user_is_logged_in"
}]
}
]
}
}
I am pretty sure this is not the correct way i am doing, Either i should use OAuth. But i want to make the JWT method for authentication work here.

Got it working by checking in here Atlassian Connect for Node.js Express Docs
Within JIRA ADD-On Signed HTTP Requests works like below. GET and POST both.
GET:
app.get('/getissue', addon.authenticate(), function(req, res){
var httpClient = addon.httpClient(req);
httpClient.get('rest/api/2/issue/ABC-1',
function(err, resp, body) {
Response = JSON.parse(body);
if(err){
console.log(err);
}else {
console.log('Sucessful')
}
});
res.send(response);
});
POST:
var httpClient = addon.httpClient(req);
var postdata = {
"fields": {
"project":
{
"key": "MYW"
},
"summary": "My Story Name",
"description":"My Story Description",
"issuetype": {
"name": "Story"
}
}
}
httpClient.post({
url: '/rest/api/2/issue/' ,
headers: {
'X-Atlassian-Token': 'nocheck'
},
json: postdata
},function (err, httpResponse, body) {
if (err) {
return console.error('Error', err);
}
console.log('Response',+httpResponse)
});

You should be using global variable 'AP' that's initialized by JIRA along with your add-on execution. You may explore it with Chrome/Firefox Debug.
Have you tried calling ?
AP.request(..,...);
instead of "var request = require('request');"
You may set at the top of the script follwing to pass JS hinters and IDE validations:
/* global AP */
And when using AP the URL should look like:
url: /rest/api/2/issue/ABC-1
instead of:
url: https://myaccount.atlassian.net/rest/api/2/issue/ABC-1
My assumption is that ABC-1 issue and user credentials are verified and the user is able to access ABC-1 through JIRA UI.
Here is doc for ref.: https://developer.atlassian.com/cloud/jira/software/jsapi/request/

Related

Can't get a succesful jira create issue api response

I am trying to call jira rest api POST /rest/api/3/issue from a node js application. I am getting the following error even though am passing correct details. I am passing issueType as 10103 and remaining sensitive params as required. Here is my
nodejs code.
app.post("/webhook", function(req,res,next){
console.log(req.body);
let options = {
method: 'POST',
url: req.body.tags["jira:endpointURL"]+"/rest/api/3/issue",
auth: {
user: req.body.tags["jira:user"],
password: req.body.tags["jira:token"]
},
headers: {
'Content-Type': 'application/json'
},
json: {
"update": {},
"fields": {
//"summary": req.body["subject"],
"summary": "Test",
"description": {
"type": "doc",
"version": 1,
"content": [
{
"type": "paragraph",
"content": [
{
"text": "body",
"type": "text"
}
]
}
]
},
"issuetype": {
"id": req.body.tags["jira:issueType"]
},
"project": {
"key": req.body.tags["jira:project"]
}
}
}
};
request(options, function (error, response, body) {
if (error) throw new Error(error);
console.log(
'Response: ' + response.statusCode + ' ' + response.statusMessage
);
console.log(body);
res.send("OK");
});
});
Error thrown
summary: "Field 'summary' cannot be set. It is not on the appropriate screen, or unknown.",
description: "Field 'description' cannot be set. It is not on the appropriate screen
You have to configure the fields to the screens first.
See:
https://support.atlassian.com/jira-cloud-administration/docs/add-a-custom-field-to-a-screen/
https://support.atlassian.com/jira-cloud-administration/docs/configure-issue-screens/#Configure-a-screen--x27-s-tabs-and-fields

Using Request to post from NodeJS

I am running into an issue with posting a json doc via request from my nodeJs app.
The problem is for me how to pass the json doc to post. Here is what works for me
const options = {
url: 'http://localhost/message/send/981f1507-2df2-4011-8f55-5460897fcde6',
method: 'POST',
json: true,
body: { "message": {
"subject": "Meet for lunch?",
"body": {
"contentType": "html",
"content": "</p>\r\n\r\n<ul type=\"disc\">\r\n\t<li><strong>Ready to Use Experiences</strong> – Get instant access to our fully configured and integrated environments allowing you to use and experience the products as a customer would in their own deployment. We’ve set up the products alongside partner solutions so you can experience the entire ecosystem including Office 365, Salesforce, and more. </li>\r\n</ul>"
},
"toRecipients": [
{
"emailAddress": {
"address": "test#ueser.com"
}} ]}}}
request(options, function(err, res, body) {
console.log(res.statusCode)
})
the problem i have is if i want to pass the body from a string like this
var mybody = `{ "message": {
"subject": "Meet for lunch?",
"body": {
"contentType": "html",
"content": "This is a test"
},
"toRecipients": [
{
"emailAddress": {
"address": "test#user.com"
}
}]}}`
and then call it like this
const options = {
url: 'http://localhost/message/send/981f1507-2df2-4011-8f55-5460897fcde6',
method: 'POST',
json: true,
body: mybody
}
request(options, function(err, res, body) {
console.log(res.statusCode)
})
which throws errors like
SyntaxError: Unexpected token " in JSON at position 0
Have you tried using stringify? Node.js has a a built in module called querystring.
const querystring = require("querystring");
const myStringBody = querystring.stringify(myBody);
Then write it to your request.
req.write(myStringBody);

Post request works as node script, but not on localhost

I have this post request to JIRA to create an issue:
require('isomorphic-fetch');
process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0";
var summ = "Review Test Ticket";
var issue = {
"fields": {
"project":
{
"key": "ABC"
},
"summary": summ,
"description": "This is a test JIRA issue creation",
"issuetype": {
"name": "Story"
},
"assignee": {
"name": "myname"
},
"customfield_10902": [{ "value": "Red Team" }],
"customfield_10008": 1
}
};
var missue = JSON.stringify(issue)
fetch("https://my_jira_host/jira/rest/api/2/issue/", {
body: missue,
headers: {
"Authorization": "Basic my_auth_token",
"Content-Type": "application/json"
},
method: "POST"
})
.then(function( data ) {
console.log(data);
}).catch(function(data) {
alert(data);
});
If the above code is in a file called "my_file.js" if I run node my_file.js the ticket is successfully created.
However, if I move that code inside a function that runs on button click in my react app, and then run the app (on localhost or a server) then it fails. I get a 403. The alert displayed from my catch is: TypeError: NetworkError when attempting to fetch resource.
I have tried absolutely everything. Have no idea where to go from here. Any ideas?

Facebook Messenger Bot Persistent Menu

I am generating my first bot working with node.js and heroku but finding some difficulties to understand the persistent menu functionalities.
Question 1) How do can I attach event as callbacks?
function persistentMenu(sender){
request({
url: 'https://graph.facebook.com/v2.6/me/thread_settings',
qs: {access_token:token},
method: 'POST',
json:{
setting_type : "call_to_actions",
thread_state : "existing_thread",
call_to_actions:[
{
type:"postback",
title:"FAQ",
payload:"DEVELOPER_DEFINED_PAYLOAD_FOR_HELP"
},
{
type:"postback",
title:"I Prodotti in offerta",
payload:"DEVELOPER_DEFINED_PAYLOAD_FOR_HELP"
},
{
type:"web_url",
title:"View Website",
url:"https://google.com/"
}
]
}
}, function(error, response, body) {
console.log(response)
if (error) {
console.log('Error sending messages: ', error)
} else if (response.body.error) {
console.log('Error: ', response.body.error)
}
})
}
Question 2) The only way I have found for empty the persistent menu and generating a new one is with a delete request via terminal ("as Facebook documented")m is there a possibily to clear inserting a refresh function on my app.js file?
curl -X DELETE -H "Content-Type: application/json" -d '{"setting_type":"call_to_actions","thread_state":"existing_thread"}' "https://graph.facebook.com/v2.6/me/thread_settingsaccess_token=PAGE_ACCESS_TOKEN"
The FB example robot is not well structured for call backs. I haven't found a good way to structure the example in Node callback or promise model. I'm sure a Node expert can reorg it.
As for the persistent menu, if you send an empty call_to_actions array the menu will disappear. The menu seems a bit 'sticky' however as it does not immediately appear/disappear when the message is sent.
I incorporated your snippet into my example robot. You can see it at
https://messenger.com/t/dynamicmemorysolutions
The source is at:
https://github.com/matthewericfisher/fb-robot
See the add/remove menu commands and functions.
EDIT: The persistent menu API has been updated. See this question for more details.
this worked for me:
function menuButton() {
var messageData = {
setting_type : "call_to_actions",
composerinputdisabled :"TRUE",
thread_state : "existing_thread",
call_to_actions:[
{
type:"postback",
title:"¿Tiempo de espera?",
payload:"ACTUALIZAR"
},
{
type:"postback",
title:"Ver Promociones",
payload:"DEVELOPER_DEFINED_PAYLOAD_FOR_START_ORDER"
}
]
}
request({
uri: 'https://graph.facebook.com/v2.6/me/thread_settings',
qs: { access_token: PAGE_ACCESS_TOKEN },
method: 'POST',
json: messageData
}, function (error, response, body) {
if (!error && response.statusCode == 200) {
var recipientId = body.recipient_id;
var messageId = body.message_id;
console.log("Successfully sent generic message with id %s to recipient %s",
messageId, recipientId);
} else {
console.error("Unable to send message.");
console.error(response);
console.error(error);
}
});
}
And I call this function at the beggining
app.post('/webhook', function(req, res){
var data = req.body;
if (data.object == 'page') {
menuButton();
data.entry.forEach(function(entry) {
var pageID = entry.id;
var timeOfEvent = entry.time;
// Iterate over each messaging event
entry.messaging.forEach(function(event) {
if (event.message) {
receivedMessage(event);
}else if (event.postback) {
receivedPostback(event);
} else {
console.log("Webhook received unknown event: ", event);
}
});
});
res.sendStatus(200);
}
})
What I have not being able to do is to remove the option of free text input. Facebook claimed now is possible yet have found no instructions or examples on how to do it. Any clues?
If you want to disable the free text input, you shoud add the following parameter to your persistent menu request:
"composer_input_disabled": true
and not
composerinputdisabled :"TRUE"
The FB API document states that the API link to hit for applying persistent menu to the page specific bot is:
https://graph.facebook.com/v2.6/me/messenger_profile?access_token=<PAGE_ACCESS_TOKEN>
Notice the me after version number i.e v2.6 in this specific case. However, this did not worked for a lot of people
There is small change in the API link to hit:
graph.facebook.com/v2.6/Page ID/messenger_profile?access_token=PAGE ACCESS TOKEN
Notice that me is replaced with the fb Page Id.
And the sample payload can still be the same:
{
"get_started": {
"payload": "Get started"
},
"persistent_menu": [
{
"locale": "default",
"composer_input_disabled": false,
"call_to_actions": [
{
"title": "Subscribe",
"type": "postback",
"payload": "subscribe"
},
{
"title": "Stop notifications",
"type": "nested",
"call_to_actions": [
{
"title": "For 1 week",
"type": "postback",
"payload": "For_1_week"
},
{
"title": "For 1 month",
"type": "postback",
"payload": "For_1_month"
},
{
"title": "For 1 year",
"type": "postback",
"payload": "For_1_year"
}
]
},
{
"title": "More",
"type": "nested",
"call_to_actions": [
{
"title": "Fresh jobs",
"type": "postback",
"payload": "fresh jobs"
},
{
"title": "Like us",
"type": "web_url",
"url": "https://www.facebook.com/onlysoftwarejobs/"
},
{
"title": "Feedback",
"type": "web_url",
"url": "https://docs.google.com/forms/d/e/1FAIpQLScjgFRbfBLznO55kFIskcH_eFc23zRSUUxzIgv_o44uj0GMpw/viewform"
}
]
}
]
}
]
}
Notice that it is mandatory to configure get_started button before setting up the persistent_menu.

Create an Issue with Jira API REST

When I try to create an Issue via the Jira API REST, I get a 500 Internal server error, I succeeded to get an issue from a project with a get-request but when I try the post-request to create a new issue it doesn't work I get the error.
Here is my JavaScript code :
createIssue: function(req, res) {
var Http = require('machinepack-http');
process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0";
Http.sendHttpRequest({
url: '/rest/api/2/issue/',
baseUrl: 'https://jira.mydomain.com',
method: 'post',
data: {
"fields": {
"project": {
"key": "TEST"
},
"summary": "REST ye merry gentlemen.",
"description": "Creating of an issue using project keys and issue type names using the REST API",
"issuetype": {
"name": "Bug"
}
}
},
headers: {
"Authorization": "Basic YWxbG9wMS4zp0bWFuzeThYS5l1TIqaXoxOTg5554Jh"
},
}).exec({
serverError: function(result) {
res.send("server error" + JSON.stringify(result))
},
success: function(result) {
res.send("issue has been created succefly");
},
});
}
Error content :
{
"body": "{\"errorMessages\":[\"Internal server error\"],\"errors\":{}}",
"headers": "{\"server\":\"nginx/1.6.0\",\"date\":\"Tue, 14 Apr 2015 13:45:38 GMT\",\"content-type\":\"application/json;charset=UTF-8\",\"transfer-encoding\":\"chunked\",\"connection\":\"close\",\"x-arequestid\":\"945x246734x1\",\"set-cookie\":[\"JSESSIONID=838923A79DA31F77BDD62510399065CF; Path=/; HttpOnly\",\"atlassian.xsrf.token=BQIV-TVLW-FGBG-OTYU|63c1b4a7b87a9367fff6185f0101c415f757e85b|lin; Path=/\"],\"x-seraph-loginreason\":\"OK\",\"x-asessionid\":\"ughpoh\",\"x-ausername\":\"alaa\",\"cache-control\":\"no-cache, no-store, no-transform\",\"x-content-type-options\":\"nosniff\"}",
"status": 500
}
Use params instead of data
JS:-
createIssue: function(req, res) {
var Http = require('machinepack-http');
process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0";
Http.sendHttpRequest({
url: '/rest/api/2/issue/',
baseUrl: 'https://jira.mydomain.com',
method: 'post',
params: {
"fields": {
"project": {
"key": "TASC"
},
"summary": "REST ye merry gentlemen.",
"description": "Creating of an issue using project keys and issue type names using the REST API",
"issuetype": {
"name": "Bug"
}
}
},
headers: {
"Authorization": "Basic YWxbG9wMS4zp0bWFuzeThYS5l1TIqaXoxOTg5554Jh"
},
}).exec({
serverError: function(result) {
res.send("server error" + JSON.stringify(result))
},
success: function(result) {
res.send("issue has been created succefly");
},
});
}
Reference
It looks like it's expecting some non-null value when it's trying to parse the project or issuetype fields, though without the full stacktrace, it's hard to be sure.
You might try adding an id property to both the project and issuetype fields:
params: {
"fields": {
"project": {
"key": "TASC",
"id": "10001"
},
"summary": "REST ye merry gentlemen.",
"description": "Creating of an issue using project keys and issue type names using the REST API",
"issuetype": {
"id": "1",
"name": "Bug"
}
}
}
Obviously you'll want to make sure to use an appropriate value in both cases.

Resources