405 error with JIRA REST API using node js - jira-rest-api

I am trying to create an automated JIRA ticket using the REST API but I keep getting a 405 error.
I am using the examples here: https://developer.atlassian.com/server/jira/platform/jira-rest-api-examples/
Also, when I visit the post URL directly I do not get any errors so I doubt it is a server issue. Any ideas?
var Client = require('node-rest-client').Client;
client = new Client();
// Provide user credentials, which will be used to log in to Jira.
var loginArgs = {
data: {
"username": "user",
"password": "pass"
},
headers: {
"Content-Type": "application/json"
}
};
client.post("https://jira.mydomain.com/rest/auth/1/session", loginArgs, function(data, response) {
if (response.statusCode == 200) {
//console.log('succesfully logged in, session:', data.session);
var session = data.session;
// Get the session information and store it in a cookie in the header
var args = {
headers: {
// Set the cookie from the session information
cookie: session.name + '=' + session.value,
"Content-Type": "application/json"
},
data: {
// I copied this from the tutorial
"fields": {
"project": {
"key": "REQ"
},
"summary": "REST ye merry gentlemen.",
"description": "Creating of an issue using project keys and issue type names using the REST API",
"issuetype": {
"name": "Request"
}
}
}
};
// Make the request return the search results, passing the header information including the cookie.
client.post("https://jira.mydomain.com/rest/api/2/issue/createmeta", args, function(searchResult, response) {
console.log('status code:', response.statusCode);
console.log('search result:', searchResult);
});
} else {
throw "Login failed :(";
}
});
I am expecting the Jira ticket of type REQ to be created with the details I added in the fields section.

I believe you are using the incorrect REST API; what you're currently doing is doing a POST to Get create issue meta which requires a GET method, hence, you're getting a 405. If you want to create an issue, kindly use Create issue (POST /rest/api/2/issue) instead.

Related

Strapi / Nuxt - Can't find custom route

I've used this to setup auth in strapi and nuxt:
Auth with Strapi and Nuxt
I'm currently trying to retrieve the items specific to a authenticated user (already checked out this strapi - restrict user to fetch only data related to him). To do this I created a custom route in Strapi (/api/routine/config/routes.json):
{
"method": "GET",
"path": "/routines/me",
"handler": "Routine.me",
"config": {
"policies": []
}
}
and a custom controller (/api/controllers/Routine.js):
module.exports = {
me: async (ctx) => {
const user = ctx.state.user;
if (!user) {
return ctx.badRequest(null, [{ messages: [{ id: 'No authorization header was found' }] }]);
}
const data = await strapi.services.routine.find({user:user.id});
if(!data){
return ctx.notFound();
}
ctx.send(data);
},
};
I already gave permission through Strapi admin for authenticated users to access 'me'. When I hit the endpoint from Nuxt:
const routines = await axios.get(http://localhost:1337/routines/me)
I get this error:
GET http://localhost:1337/routines/me 404 (Not Found)
Why is the custom route not found? Am I using the wrong endpoint?
Maybe you have already solved it, but it seems like you forget to send the authentication header with the request.
const routines = await axios.get(
'http://localhost:1337/routines/me', {
headers: {
Authorization:
this.$auth.getToken('local'),
},
}
It was a fault in my Strapi routes config. Answer was provided through the amazingly helpful Strapi forums:
403 forbidden when calling custom controller from Nuxt
Here is the problem:
{
"method": "GET",
"path": "/routines/:id",
"handler": "routine.findOne",
"config": {
"policies": []
}
},
{
"method": "GET",
"path": "/routines/me",
"handler": "routine.me",
"config": {
"policies": []
}
So basically you are hitting the first route right now and it assumes that
me is actually an :id. Koa is making the verifications with regex so in this case it takes the first matched route. Move the route with /me above that one with /:id

authorization type bearer token on postman and request data from the API which requires a token bearer with flutter

im trying to request data from my API and to get the data, it requires a bearer token which can be obtain by log-in. and as a frontend I created a function to save and request from the UI to the API. I'm using flutter framework for the UI.
I've managed to create a function to store the bearer token generated at login, which keeps the user logged in. and it works by saving the bearer token in sharedpref.
login() async {
final response = await http.post(
"https://api.batulimee.com//v1_ship/login_app",
body: {"email": email, "password": password},
);
final data = jsonDecode(response.body);
String status = data['status'];
String pesan = data['message'];
String apikey = data['data']['apikey'];
SharedPreferences prefs = await SharedPreferences.getInstance();
prefs.setString('apikey', apikey);
if (status == "success") {
Navigator.of(context).pushReplacement(PageRouteBuilder(
pageBuilder: (_, __, ___) => new bottomNavBar(),
transitionDuration: Duration(milliseconds: 600),
transitionsBuilder:
(_, Animation<double> animation, __, Widget child) {
return Opacity(
opacity: animation.value,
child: child,
);
}));
print(pesan);
print(apikey);
} else {
print(pesan);
}
}
heres the response.
{
"status": "success",
"data": {
"apikey": "UUFmb0w3WlI4Q01qOWRTamgxOFVZRjhIeWhFMkN3T205R20xZXNpYw==",
"id_user": 50,
"id_role": "8",
"name_role": "Ship Owner",
"email": "me#gmail.com",
"phone": "0210201",
"saldo": "0",
"photo": "https://cdn.batulimee.com/foto_user/avatar.png"
},
"message": "login successfully "
}
and now I want to create a function that can get user profile data, and where to get this data requires the bearer token which I got from login. I need this so that the user can edit their name, password, or other data in the user's profile and save it.
My backend has created the API get my_profile. which I explained earlier, to get this requires a token bearer that is the same as the token bearer we got earlier from login. And now it's my job to get the get my_profile data using a function in flutter.
heres the response from the API get my_profile.
{
"status": "success",
"data": {
"id_user": 49,
"id_role": "8",
"name_role": "Ship Owner",
"first_name": "a",
"last_name": "f",
"email": "afriansyahm86#gmail.com",
"phone": "082258785595",
"saldo": "0",
"company_name": "aa",
"company_address": "jl kav pgri",
"photo": "https://batulimee.com/foto_user/avatar.png"
},
"message": "get profile detail successfully "
}
How is the function to store the bearer token into Authorization so I can get my_profile data ? please help me.... :(
make an api class :
import 'package:http/io_client.dart';
class Api {
String _token;
final Client http =IOClient(HttpClient()
..badCertificateCallback = _certificateCheck
..connectionTimeout = const Duration(seconds: kConnectionTimeoutSeconds));
static bool _certificateCheck(X509Certificate cert, String host, int port) =>
host.endsWith('EXAMPLE.com'); // Enter your url for api here
String GetToken() {
return _token;
}
Future<bool> setToken(String token) async {
_token = token;
return Future.value(true);
}
Map<String, String> get headers => {
"Content-Type": "application/json",
"Accept": "application/json",
"Authorization": "Bearer $_token",
};
}
in your login use the setToken:
await _api.setToken(apikey);
next for your profile or any request in api class:
Future<ProfileResponse> getProfile() async {
var url = "$urlPrefix/api/v1/profile";
var response = await http.get(url, headers: headers);
if (response.statusCode != 200) {
print(
"$response");
var parsed = json.decode(response.body);
var message = parsed["message"];
if (message != null) {
throw message;
}
throw Exception(
"Request to $url failed with status ${response.statusCode}: ${response.body}");
}
// return the response you want
return json.decode(response.body);
}

Expo - React Native: How to read User data from Google Fit API

thanks in advance for any assistance that can be provided. My goal is to use OAuth2 to get users’ step data from the Google Fit API. I am able to authenticate using Expo's expo-app-auth package, and receive an accessToken, but, when I try to read from the Fit API, I get an error that the authentication credential is missing.
Relevant Code:
let config = {
issuer: 'https://accounts.google.com',
scopes: ['openid', 'profile', 'https://www.googleapis.com/auth/fitness.activity.read'],
/* This is the CLIENT_ID generated from a Firebase project */
clientId: 'xxx.apps.googleusercontent.com',
};
let authState = await AppAuth.authAsync(config); // this returns an idToken, accessToken, list of scopes configured, including the fitness.activity.read
const url = 'https://www.googleapis.com/fitness/v1/users/me/dataset:aggregate';
const today = new Date().getTime();
const past = today - (5 * 24 * 60 * 60 * 100);
const body = {
"aggregateBy": [{
"dataTypeName": "com.google.step_count.delta",
"dataSourceId": "derived:com.google.step_count.delta:com.google.android.gms:estimated_steps"
}],
"bucketByTime": { "durationMillis": 86400000 },
"startTimeMillis": today,
"endTimeMillis": past
}
const header = {
'Content-Type': 'application/json',
'Authorization': `BEARER ${authState.accessToken}`
}
const req = await fetch(url, {
method: 'POST',
headers: header,
body: JSON.stringify(body)
});
const resp = await req.json();
/*
Object {
"error": Object {
"code": 401,
"errors": Array [
Object {
"domain": "global",
"location": "Authorization",
"locationType": "header",
"message": "Login Required.",
"reason": "required",
},
],
"message": "Request is missing required authentication credential. Expected OAuth 2 access token, login cookie or other valid authentication credential. See https://developers.google.com/identity/sign-in/web/devconsole-project.",
"status": "UNAUTHENTICATED",
},
}
*/
I am able to produce this issue using a built apk on a real device. For the standalone build, I am using an OAuth2 clientId from Google Console as clientId in the config, and the Fitness API is enabled.
Does anyone know what I might be doing incorrectly?

Website login automation without XHR request

Background: I'm trying to automate local ISP login using simple request in python (without selenium, that's last resort as I'm trying to learn other ways too).
Upon inspecting website, submit button calls the validateForm() function.
function validateForm(){
var input=true;
var uname = "?"+document.login.Username.value+"+/#";
var pwd = "?"+document.login.Password.value+"+/#";
document.login.LoginName.value=encodeURIComponent(uname);
document.login.LoginPassword.value=encodeURIComponent(pwd);
if (input==true&&document.login.checker.checked)
toMem(this);
}
function toMem(a) {
newCookie('theName', document.login.Username.value); // add a new cookie as shown at left for every
newCookie('theEmail', document.login.Password.value); // field you wish to have the script remember
}
function newCookie(Username,value,days) {
var days = 30; // the number at the left reflects the number of days for the cookie to last
// modify it according to your needs
if (days) {
var date = new Date();
date.setTime(date.getTime()+(days*24*60*60*1000));
var expires = "; expires="+date.toGMTString(); }
else var expires = "";
document.cookie = Username+"="+value+expires+"; path=/";
}
No where it is sending any request.
The website doesn't make any XHR request. I'm not able to grasp how they are making the login work. I found one request from 'other' tab of network (chrome dev tools). From where it is generating this request!!!
fetch("http://ip:port/Sristi3/SRISTI/loginUI.do2", {
"headers": {
"accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9",
"accept-language": "en-US,en;q=0.9,bn;q=0.8",
"cache-control": "no-cache",
"content-type": "application/x-www-form-urlencoded",
"pragma": "no-cache",
"upgrade-insecure-requests": "1"
},
"referrer": "http://ip:port/Sristi3/SRISTI/Login.jsp?",
"referrerPolicy": "no-referrer-when-downgrade",
"body": "Username=username&Password=password&LoginName=encodedusername&LoginPassword=encodedpass",
"method": "POST",
"mode": "cors",
"credentials": "include"
});
I tried to simply paste the request in console but this also does not make the login. Returned a promise with [[PromiseStatus]]: "rejected" and [[PromiseValue]]: TypeError: Failed to fetch, message: "Failed to fetch", stack: "TypeError: Failed to fetch". What and where to look for? Any help?

Cancel all Google/Firebase messaging subscriptions

I just rewrote my firebase cloud messaging code for my web API and now use a Cloud Function to handle the subscriptions, or at least that is the theory.
Where can I go to cancel any existing subscriptions so that I can check that what seems now to be working, actually is (and that is not some hangover from before that is giving the impression of working).
This is all on a development instance of Firebase so I can delete whatever I want. I set up the subscriptions with the following code, which may or may not be coreect, but I think it means I need to look on Google rather than Firebase, but I can't find anything
let token = req.query.token;
let topic = "presents";
let uri = `https://iid.googleapis.com/iid/v1/${token}/rel/topics/${topic}`;
// Make the request to Google IID
var myHeaders = {
"Content-Type": "application/json",
Authorization: "key=" + secrets.devKey
};
var options = {
uri: uri,
method: "POST",
headers: myHeaders,
mode: "no-cors",
cache: "default"
};
rp(options)
.then(function(response) {
// console.log("rp success", response);
res.status(200).send({
msg: "Ok from Simon for " + token,
payload: response}
);
})
.catch(function(err) {
console.log("[fbm.registerForUpdates] Error registering for topic", err.message);
res.status(500).send(err);
});
The Firebase documentation seems to be incomplete on this topic. Playing around showed the following (valid at least at the time of writing, verified w/ Postman):
POST https://iid.googleapis.com/iid/v1/IID_TOKEN/rel/topics/TOPIC_NAME request creates a subscription for a topic & token
GET https://iid.googleapis.com/iid/info/IID_TOKEN?details=true request lists all subscribed topics for a token
DELETE https://iid.googleapis.com/iid/v1/IID_TOKEN/rel/topics/TOPIC_NAME request removes a subscription for a topic for a token
DELETE https://iid.googleapis.com/v1/web/iid/IID_TOKEN request removes all subscriptions for a token
On all these requests the header 'Authorization: key=YOUR_SERVER_KEY' needs to be set.
Sample output from a GET request:
{
"connectDate": "2018-10-06",
"application": "com.chrome.macosx",
"subtype": "wp:https://192.168.0.196:8020/#9885158F-953C-48BC-BCF5-38ABF2F89-V2",
"scope": "*",
"authorizedEntity": "30916174593",
"rel": {
"topics": {
"sensorUpdate": {
"addDate": "2018-10-07"
}
}
},
"connectionType": "WIFI",
"platform": "BROWSER"
}