Discord guilds.join resulting in Bad Request - javascript

I am trying to add a member to my guild using Node's request module.
The access token is retrieved through Discord's OAuth2 system. The token provides identify and guilds.join permissions.
The bot token has been copied directly from Discord's development site. The bot is connected to my application, joined the guild I am working with and has permission for both manage roles and create instant invites.
Here is my request,
request({
url: `http://discordapp.com/api/guilds/${guildID}/members/${userID}`,
method: "PUT",
headers: {
'Authorization': `Bot ${botToken}`,
'Content-Type': 'application/json'
},
json: {
'access_token': access_token
}
}, (err, res, body) => {
console.log(body);
});
and here is the response
{ _misc: [ 'Expected "Content-Type" header to be one of {\'application/json\'}.' ] }
I have searched through all related questions on here and cannot find the solution.
Any help would be valued. Thanks.

I figured out the solution. You'll want to take advantage of DiscordJS and use the guild.addMember function rather than building your own request.

Related

Linkedin webhooks event subscription not working

I've been stuck on this issue for some time now, I am trying to subscribe to Linkedin's webhook using ngrok for testing on localhost, and have been trying for some time now, i have tried using encode uri's as well but still running into error, I have verified that the APP_ID, profileId and organizationId i'm using are correct, but still i get the same error. I have also tried using the Restli protocol that linkedin suggests in their documentation but to no avail.
let url = `https://api.linkedin.com/v2/eventSubscriptions/(developerApplication:urn:li:developerApplication:${config.IN.APP_ID},user:urn:li:person:${profileId},entity:urn:li:organization:${organizationId},eventType:ORGANIZATION_SOCIAL_ACTION_NOTIFICATIONS)`;
return new Promise((resolve, reject) => {
request(
{
url,
method: 'PUT',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${accessToken}`,
// 'X-Restli-Protocol-Version': '2.0.0',
},
json: {
webhook: "https://url.ngrok.io/api/v1/webhook/linkedin/callback"
},
},
(err, response, body) => {
if (err) {
reject(err);
} else {
resolve(body);
}
},
);
});
I have been receiving this error constantly no matter what I try, I have tried sending the url like this:
https://api.linkedin.com/v2/eventSubscriptions/(developerApplication:urn:li:developerApplication:{${config.IN.APP_ID}},user:urn:li:person:{${profileId}},entity:urn:li:organization:{${organizationId}},eventType:ORGANIZATION_SOCIAL_ACTION_NOTIFICATIONS)
https://api.linkedin.com/v2/eventSubscriptions/${encodeURIComponent((developerApplication:urn:li:developerApplication:${config.IN.APP_ID},user:urn:li:person:${profileId},entity:urn:li:organization:${organizationId},eventType:ORGANIZATION_SOCIAL_ACTION_NOTIFICATIONS))
All I receive is this error
'{"serviceErrorCode":100,"message":"Unpermitted fields present in RESOURCE_KEY: Data Processing Exception while processing fields [/key]","status":403}'
Any help would be appreciated, I have been stuck on this for a while now.
The request seems to be OK , but the method should be GET (not PUT)
One thing is to check which ID are you using for application_id. The application ID is the one in the url - https://www.linkedin.com/developers/apps/<id from here>/settings
. You need to use and uncomment the header for Restli.
I'd say that your url needs to look like this, as this is from their original POSTMAN collection.
https://api.linkedin.com/v2/eventSubscriptions/(developerApplication:urn%3Ali%3AdeveloperApplication%3A{{application_id}},user:urn%3Ali%3Aperson%3A{{person_id}},entity:urn%3Ali%3Aorganization%3A{{organization_id}},eventType:ORGANIZATION_SOCIAL_ACTION_NOTIFICATIONS)
You can validate here, their full collection - https://www.postman.com/linkedin-developer-apis/workspace/e781b3ac-4101-4d60-8981-afcb4812623d/request/16069442-9d0bf046-ea81-4af0-9515-d07246a0ab39
LinkedIn webhooks does not support ngrok URIs

Auth0 returning 401 unauthorized when requesting new auth token

I am trying to request an authorization token through auth0 using an M2M application with the code:
var axios = require("axios").default;
var options = {
method: 'POST',
url: 'https://chaptify.us.auth0.com/oauth/token',
headers: { 'content-type': 'application/x-www-form-urlencoded' },
data: {
grant_type: 'client_credentials',
client_id: 'KbFUk08Qq24VA03i1mVAkLc3uPKc6V79',
client_secret: process.env.AUTH0_M2M_CLIENT_SECRET,
audience: process.env.AUTH0_AUDIENCE
}
};
axios.request(options).then(function(response) {
console.log(response.data);
}).catch(function(error) {
console.error(error);
});
which is pulled straight from auth0's website. but every time I've gotten a 401 error so far I've tried
using different M2M applications
making sure all the M2M applications are authorized and trying again
checking the Token Endpoint Authentication Method is set to None
checking all the fields are correct
googling to see if I can find absolutely anything to help
pasting in the values directly
unauthorizing the M2M shutting down the application, waiting a while then starting it up again, nothing

Why can I not authenticate with the GitHub REST API using Axios?

I'm sort of new to REST..
For full disclosure, I'm running this code inside of a Netlify Lambda function and testing via netlify-lambda.
My curl command works:
curl -u "<username>:<password>" https://api.github.com/repos/<username>/<reponame>
But when I attempt a get request via axios I'm getting a 404 (which according to github docs implies an auth issue). This is what I'm doing (also doesn't work without the custom headers, I've just been trying random things).
axios({
method: "get",
url: `https://api.github.com/repos/${user}/<reponame>/`,
headers: {
Authorization: `Bearer ${githubToken}`,
"Content-Type": "application/json"
},
auth: {
username: user,
password: pass
}
})
.then(res => {
callback(null, {
statusCode: 200,
body: JSON.stringify(res.data)
});
})
.catch(err => {
callback(err);
});
One thing I noticed was that it seems axios was taking my username and password and prepending them to the url i.g. https://<username>:<password>#api.github.com/repos/<username>/<reponame>
Is this how auth should be sent over?
I shouldn't have had a trailing forward slash at the end of my URL.
If you already have a token you don’t need user/pass, just add the token to the header.

Unsupported grant type when getting OAuth token for Reddit API

I'm trying to get an OAuth token for the Reddit API following the Application Only OAuth instructions. My reddit app is an installed app, so for my grant_type I'm using https://oauth.reddit.com/grants/installed_client.
Currently I'm running a very short JS script to query the API and get a token:
const APP_ID = 'MY_APP_ID'
const DEVICE_ID = 'TRACKING_ID_20_TO_30_CHARS'
let form = new FormData()
form.append('grant_type', 'https://oauth.reddit.com/grants/installed_client')
form.append('device_id', DEVICE_ID)
fetch('https://www.reddit.com/api/v1/access_token', {
method: 'POST',
headers: new Headers({
'Content-Type': 'application/x-www-form-urlencoded',
'Authorization': `Basic ${btoa(`${APP_ID}:`)}`,
}),
body: form })
.then(handleResponse)
.then(function(data) {
console.log(data)
})
.catch(error => console.error(error))
function handleResponse(response) {
return response.json()
}
(Note: running the snippet as-is will give you a NetworkError because the APP_ID isn't a real one and I don't want to give mine out.)
The response I get is:
{
"error": "unsupported_grant_type"
}
When I try the same API request using a REST client I get back the expected response, so this makes me think that the problem is JavaScript-related. Since the grant_type matches what the instructions say I'm not really sure what to do with the error. I'm hoping someone else more experienced with OAuth will know what is going on here.
The problem was the use of the FormData object. In earlier stages of troubleshooting I found this answer on Reddit and decided to use it, but that didn't work for me.
It was submitting the data as multipart/form-data rather than application/x-www-form-urlencoded, which Reddit's OAuth server did not like. I wrote a helper function based on this answer which did the trick:
function urlEncode(data) {
let out = [];
for (let key in data) {
out.push(`${key}=${encodeURIComponent(data[key])}`);
}
return out.join('&')
}

Get browser response headers on API call (I'm using Meteor but vanilla would be helpful too)

I'm making an API call (specifically to stubhub) and I want to get the response headers found in the browser network tab:
Here's my API call (using Meteor HTTP)
HTTP.post('https://api.stubhub.com/login', {
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Authorization': 'Basic ' + base64
},
params: {
'grant_type' : 'password',
'username' : username,
'password' : password,
'scope' : 'PRODUCTION'
}
}, function(err, res) {
if (err) {
console.log(err)
} else {
console.log(res);
}
})
I console.log 'res' to see everything, and I saw a few objects but main ones are header and data. Data is the content object which is usable in other ways, but header just returns this:
How do I get the Response Headers?
Figured it out. I was making this call client-side (obviously not secure, just to get my app up and running/testing). If you make the call server-side, say via a Meteor method, the full header field will be available in the response.

Categories

Resources