GitHub API 401 Bad Credentials in Node but not curl - javascript

I'm trying to authenticate on Enterprise GitHub with #octokit/rest. If I use the following Curl I get a list of the API's URL's:
curl -u "my#email.com" https://api.github.<my domain>.com
when I run that I am prompted for a password where I enter my personal access token.
However, If I use the same details in my node application I get a 401 Bad Credentials response. This is how I'm configuring my authentication:
octokit.authenticate({
baseUrl: 'https://api.github.<my domain>.com',
type: 'basic',
username: 'my#email.com',
password: '<my personal access token>'
});
Based on the documentation I believe this should work. can anybody advise why it doesn't?
This is the full HTTP response I get:
{ HttpError: {"message":"Bad credentials","documentation_url":"https://developer.github.com/v3"}
at response.text.then.message (/node_modules/#octokit/rest/lib/request/request.js:72:19)
at <anonymous>
at process._tickCallback (internal/process/next_tick.js:188:7)
name: 'HttpError',
code: 401,
status: undefined,
headers:
{ 'access-control-allow-origin': '*',
'access-control-expose-headers': 'ETag, Link, Retry-After, X-GitHub-OTP, X-RateLimit-Limit, X-RateLimit-Remaining, X-RateLimit-Reset, X-OAuth-Scopes, X-Accepted-OAuth-Scopes, X-Poll-Interval',
connection: 'close',
'content-length': '83',
'content-security-policy': 'default-src \'none\'',
'content-type': 'application/json; charset=utf-8',
date: 'Mon, 10 Sep 2018 13:20:12 GMT',
'referrer-policy': 'origin-when-cross-origin, strict-origin-when-cross-origin',
server: 'GitHub.com',
status: '401 Unauthorized',
'strict-transport-security': 'max-age=31536000; includeSubdomains; preload',
'x-content-type-options': 'nosniff',
'x-frame-options': 'deny',
'x-github-media-type': 'github.v3; format=json',
'x-github-request-id': 'C8BA:76CE:24B2BB3:45F82A2:5B966F8B',
'x-ratelimit-limit': '10',
'x-ratelimit-remaining': '9',
'x-ratelimit-reset': '1536585672',
'x-runtime-rack': '0.039959',
'x-xss-protection': '1; mode=block' } }
Addtional Information
This seems to be where my issue occurs:
let response = await method({
q: "repo:" + repoOrg + "/" + repoName + " is:issue",
per_page: 100
});
This is similar to the example on the npm page. Is it in some way possible the authentication isn't getting appliet to this and if so how do I ensure it does get applied?

In order to authenticate with a token you should set the auth type to token and generate a token
username takes both email and username
Full working example :
const octokit = require('#octokit/rest')();
octokit.authenticate({
type: 'token',
username: 'my username',
token: 'my token'
});
octokit.activity.getStarredRepos().then(results => {
console.log(results);
});

The .authenticate method does not accept a baseUrl parameter. You have to add it to the Octokit constructor, see https://github.com/octokit/rest.js#client-options
Here's an example from my code:
const octokit = require('#octokit/rest')({
baseUrl: 'https://api.github.<my domain>.com'
})
octokit.authenticate({
type: 'basic',
username: 'my#email.com',
password: '<my personal access token>'
});

Related

Cypress intercept only message with specific body

I'm kind of new on Cypress intercept, but I am in need of capturing the response to a GET message, but wait for the message which has a response body with a specific value on its body.
For example, I may be receiving two responses to two GET requests, such as these two:
Event: request
cypress_runner.js:190995 Resource type: xhr
cypress_runner.js:190995 Method: GET
cypress_runner.js:190995 Url: https://127.0.0.1/api/users/61a68c4a1d2c5258baece19c?_=1638304841558
cypress_runner.js:190995 Matched `cy.intercept()`: {RouteMatcher: {…}, RouteHandler Type: 'Spy', RouteHandler: undefined, Request: {…}, Response: {…}, …}
cypress_runner.js:190995 Response status code: 200
cypress_runner.js:190995 Response headers: {date: 'Tue, 30 Nov 2021 20:40:43 GMT', Content-Encoding: 'gzip', server: 'nginx', Vary: 'Accept-Encoding', access-control-allow-methods: 'PUT, GET, POST, DELETE, OPTIONS, PATCH', …}
cypress_runner.js:190995 Response body: {"name": "Alice", "description": "Created by Cypress"}
Event: request
cypress_runner.js:190995 Resource type: xhr
cypress_runner.js:190995 Method: GET
cypress_runner.js:190995 Url: https://127.0.0.1/api/users/61a68c4a1d2c5258baece19c?_=1638304841558
cypress_runner.js:190995 Matched `cy.intercept()`: {RouteMatcher: {…}, RouteHandler Type: 'Spy', RouteHandler: undefined, Request: {…}, Response: {…}, …}
cypress_runner.js:190995 Response status code: 200
cypress_runner.js:190995 Response headers: {date: 'Tue, 30 Nov 2021 20:40:43 GMT', Content-Encoding: 'gzip', server: 'nginx', Vary: 'Accept-Encoding', access-control-allow-methods: 'PUT, GET, POST, DELETE, OPTIONS, PATCH', …}
cypress_runner.js:190995 Response body: {"name": "Bob", "description": "Created by Cypress"}
My intercept for now looks like this:
cy.intercept("GET", "/api/users/*").as("waitingForUpdateOnAlice")
cy.wait("#waitingForUpdateOnAlice")
But if the server returns the answer for Bob, then I don't have the chance of continue waiting.
Is there a way to handle this?
Mention: I do NOT have control or access to the trailing id on the url, so I do need to do this filtering only upon the response body.
First of all, declare a function to be used recursively:
function doIntercept(functionToWait){
cy.wait("#"+functionToWait).then((res)=>{
if(res.response.body.name === 'Bob') {
doIntercept("#"+functionToWait);
} else {
assert(res.response.body.name).to.be.eq('Alice');
}
})
}
then in your test section:
it("your test", ()=>{
cy.intercept("GET", "/api/users/*").as("waitingForUpdateOnAlice");
doIntercept("waitingForUpdateOnAlice");
})
You can alias an individual request. This should accomplish what you'd like.
cy.intercept("GET", "/api/users/*", (req) => {
if (req.body.name.equals('Alice')) {
req.alias = 'waitingForUpdateOnAlice'
}
});
cy.wait('#waitingForUpdateOnAlice');
You might need to play around with the exact form of that req.body.name conditional.

cURL into NodeJS with Axios using hosted file

I'm trying to convert this cURL command into a request with AXIOS
`curl -X POST "https://serverless-upload.twilio.com/v1/Services/${service_uid}/Functions/${function_uid}/Versions" \
-F "Content=#./template_scripts/collect.js; type=application/javascript" \
-F "Path=collect.js" \
-F "Visibility=public" \
-u "${client.accountSid}:${client.password}"`
my attempt at doing so looks like this:
collect_file = ""
await axios.get("https://pastebin.com/raw/RFYs4n2p").then((r) => collect_file = r.data)
url = `https://serverless-upload.twilio.com/v1/Services/${service_uid}/Functions/${function_uid}/Versions`
form = new FormData();
form.append("Path", "collect");
form.append("Visibility", "public");
form.append("Content", collect_file);
form.append("filename", "collect.js");
form.append("contentType", "application/javascript");
await axios.post(url, form, {
headers: {
Authorization: 'Basic ' + Buffer.from(`${accountSid}:${authToken}`).toString('base64'),
...form.getHeaders(),
},
})
When filling the "Content" param I'm using the text representation of a JS file that I have hosted on Pastebin. In the initial cURL command you see I specify the file ./template_scripts/collect.js I don't want to use fs to load the "collect.js" file as I want the code to not use the file system.
The error I get is
Error: Request failed with status code 400
{
message: 'Invalid function version content.',
code: 20001,
user_error: true,
http_status_code: 400,
params: {}
}
400
{
date: 'Wed, 10 Feb 2021 13:39:08 GMT',
'content-type': 'application/json',
'content-length': '113',
connection: 'close',
't-request-id': 'RQ1bf727ce267b5b974cd1eeab122ad02e',
'x-shenanigans': 'none',
'access-control-allow-origin': '*',
'access-control-allow-headers': 'Accept, Authorization, Content-Type, If-Match, If-Modified-Since, If-None-Match, If-Unmodified-Since',
'access-control-allow-methods': 'GET, POST, DELETE, OPTIONS',
'access-control-expose-headers': 'ETag',
'access-control-allow-credentials': 'true',
'x-powered-by': 'AT-5000',
'x-home-region': 'us1',
'x-api-domain': 'serverless-upload.twilio.com',
'strict-transport-security': 'max-age=31536000'
}
I'm assuming the problem may be with using the text version of the JS file but not entirely sure. When read from pastebin it is returned as type "string".
Thank You!
Place the filename as the third argument for "Content" param
form.append("Content", collect_file, "collect.js");

How do I pass use Authorize from Paypal Orders API in my method & what should I return?

I have a pending fetch request that is waiting for the authorize method below to execute on my backend.
I need to use the authorize request details from PayPal orders api from here
and implement that in the method below. I have attempted to do that below but I'm not sure if it's correct.
async authorize(): Promise<PAR> {
var res = HTTPClient.request(
'https://api-m.sandbox.paypal.com/v2/checkout/orders',
{
method: 'post',
headers: {
'Content-Type': 'application/json',
'Authorization':
'Bearer access-token',
},
body: JSON.stringify({
intent: 'AUTHORIZE',
purchase_units: [
{ amount: { currency_code: 'USD', value: '100' } },
],
}),
},
);
return (await res).responseText;
}
Sorry if I'm not able to explain it properly, please feel free to ask for anything else you may need for this. This is my first time doing something in TypeScript & I got into node very very recently too.

nodejs cookie not persist from request.post to a follow up request.get call

Using NodeJS, opn to open up a protected web page in a default browser after login. here is the code break down.
var loginActionUrl = "http://example.com/Logon.do";
var protectedPageUrl = "http://example.com/protected_page.html";
request.post({
url: loginActionUrl,
jar: jar.getJar(),
followAllRedirects: false,
body: 'username=' + username + '&password=' + password
}, function (err, res, body) {
//enter code here
request.get({
url:protectedPageurl,
method: 'get',
jar: jar.getJar()
}, function(err, res, body) {
// todo 2
}
});
SO, from the post call, I get set-cookie in response headers.
'set-cookie':
[ 'X-Uaa-Csrf=JFrlPA; Expires=Thu, 01-Jan-1970 00:00:10 GMT; HttpOnly',
'X-Uaa-Csrf=RmXmOa; Expires=Mon, 16-Oct-2017 18:24:22 GMT; HttpOnly',
'SESSION=b0536096-e184-4f42-a68f-ff8f58802adc; Path=/Logon/; HttpOnly' ]
then, the set-cookie info get lost in the follow up http.get call, you can't find it from the new response header, see below
'set-cookie': [ 'JSESSIONID=8CB721B97EE3C07FAD481A56A84B4D82.protectedpage-111-22-333-44; Path=/ProtectedPage; HttpOnly' ]
I am using cookieJar to get/set the cookie, I am set followAllRedirects to false, so, I am expecting, the cookie will carry over to the next call. but, it is not.
any ideas? thanks
fixed this issue by setting up a personal cookieJar
// init personal jar
var cookiejar = request.jar();
request.defaults({jar:cookieJar});
// reset the jar
cookieJar = request.jar()
// if want to add extra to the cookie,
cookieJar.setCookie('key=value')

How to send chat message using skype BOT api

I want to send messages,images ... using skype BOT API. If there is any other NPM available for doing skype chat.
Refer how to get access token from the docs
https://azure.microsoft.com/en-us/documentation/articles/active-directory-v2-protocols-oauth-code/
Then using this token i will try to send message using the following request
Refer docs:
https://docs.botframework.com/en-us/skype/chat/#navtitle
conversationId: 29:f2ca6a4a-93bd-434a-9ca5-5f81f8f9b455
request({
url: 'https://api.skype.com/v3/conversations/29:f2ca6a4a-93bd-434a-9ca5-5f81f8f9b455/activities',
method: "POST",
json: true,
headers: {
Authorization: ' Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsImtpZCI6IjIifQ.eyJpYXQiOjE0NzMzMTk4MDEsImV4cCI6MTQ3MzQwNjqwqwqwqwt5cGVpZCI6ImFtdF8wNjIiLCJzY3AiOjk1OCwiY3NpIjoiMCIsImNpZCI6ImVhODhhYWFmMmFkMjYwYzEiLCJhYXQiOjE0NzMzMTk4MDF9.ZrC0weALCz7QbUHFslJZD7L16k_ciFSCNY-q29h99x70qNrpB5e71KYrD18FTZ-3tI8Ck37_91yMHleQZvEziyEq5-t9EOaGM32RiF0iwnKZcbkOkvgqofWmcGdPT63HEyjWBHg3e_NLIE-RnDob4vMCQrHTkqmuQq6cVaIDkjke1Yi4xjONUNIB9QpWmpuRju0Kxi7oIJqiHWQK',
'Content-Type': 'application/json'
},
body: {
"type": "message/text",
"text": "Hi! (wave)"
}
}
But got error:
{ status: { code: 40499, text: 'No handler found for resource' } }
How to get conversationId?
You are addressing different domain. url should be https://apis.skype.com/v3....

Categories