Clash Royale Node Fetch with Key - javascript

Im trying to make a discord bot where if you type -cr into the chat, it takes the Arguments of the user (Being the Clash Royale Player's player tag) and would then use the package node-fetch to receive data with my specified endpoint. I am constantly running into the error of { reason: 'accessDenied', message: 'Invalid authorization' }. Im rather new to this stuff, especially API's, but im hoping to access certain data which I can decide later on (Which I know how to do). My code is :
const fetch = require('node-fetch')
module.exports = {
name: 'clash',
aliases: ['cr', 'clashroyale'],
category: 'This',
utilisation: '{prefix}clash',
async execute(client, message) {
var msgArgs = message.content.slice(this.name.length + 1)
var endpoint = `/players/${msgArgs}`
var url = `https://api.clashroyale.com/v1`
var token = `hidingmytoken`
fetch(url + endpoint, {
method: 'POST',
headers: {
"Authorization": token
}
}).then(data => data.json()).then(json => {
console.log(json)
})
},
};
The message parts with msgArgs and discord sides all work but fetching that clash Royale API is a big hurdle for me. The API for Clash Royale can be found here https://developer.clashroyale.com/#/documentation and Im just generally stuck on this whole concept. Im using version 2.6.6 of node-fetch so I can use the require() method which should work if that does matter. In general, how can I pass my token properly to receive that API data?

Since the Clash Royale API uses bearer authentication, you need to specify that it will be a bearer token.
headers: {
'Authorization': `Bearer ${token}`
}

I've implemented the following functionality. The code is written in GO but you can copy the logic and translate into your language.
The library have the following functionality:
Login
Token generation
Token list
Token delete
https://github.com/alessiosavi/GoClashRoyale/blob/master/api/auth.go

Related

Firebase error. Please ensure that you have the URL of your Firebase Realtime Database instance configured correctly

I am using getServerSideProps to fetch data from my firebase database into my Next.js application.
My code snippet looks like this:
export async function getServerSideProps(context) {
const session = await getSession(context);
const products = await fetch("https://database-73695.firebaseio.com/").then(
(res) => res.json()
);
return {
props: {
products,
session
},
};
}
The problem is that I get error message saying the following: "FetchError: invalid json response body at https://database-73695.firebaseio.com/ reason: Unexpected token F in JSON at position 0"
I have seen that some people report this error when the data fetched is actually text and not an object. I tried changing the response from res.json to res.text, but then I'm told that "text is undefined".
Does anybody have any idea of what could be happening?
UPDATE:
By testing different fetching methods, I have seen the error:
Firebase error. Please ensure that you have the URL of your Firebase Realtime Database instance configured correctly.
All fetching code (with or without getServerSideProps) work when used with other APIs.
My database URL comes from Firestore, and is formated as follows:
https://PROJECT-ID.firebaseio.com
It is located in us-central, which I know is important for the URL.
Something else that might be worth noting: the database has already a collection called "users" tied to Stripe transactions, which works.
Any ideas?
Thank you for your time.
->try adding headers:
headers:
{
Accept: 'application/json, text/plain, /'
'User-Agent': '*',
},
->try checking if data is not been fetch from the back-end

Assigning Roles to a Discord Member Already in Guild

I'm trying to assign a discord role to a member using OAuth2 on my website. They sign in, I get the access token (which works with other requests), and then send the request below with every header and variable being correct.
factionRoleMapping = { OG: "929218237030354994" };
const newRoles = [...currentRoles, factionRoleMapping[faction]];
var rolesInfoFetch = await fetch(
`https://discord.com/api/v9/guilds/${config.GUILD_ID}/members/${req.body.uid}`,
{
method: "PUT",
headers: { Authorization: req.headers.authorization },
body: {
roles: newRoles,
},
}
);
I read the docs and it said that I would get a 204 No Content if the user was already in the discord guild, which I'm guessing should be okay. But I keep getting 401 Unauthorized.
The current permissions are "guilds", "guilds.join", "guilds.members.read", and "identify".
I'm not even sure if this is possible the way I'm doing it, but any help is appreciated!
Authorization header should be in format of Bot your.bot.token
also your question is unrelated to discord.js

How to get a valid access token for a custom Azure App API? (MSAL.js)

I am trying to build a small web app which shows me my name, my schedule and my grades for school.
My school mostly uses the services from Microsoft, which gave me the idea to use their Azure API endpoints (for the schedules and grades) in my project.
I have access to create an app registration in the Azure-portal, so I did that and got it working to login with my student email. Also I tried to fetch the Microsoft Graph API and that works absolutely great.
However, when I try to fetch the Grades endpoint, it returns a 401 Unauthorized error. I'm guessing this has to do with the scopes, but I'm not sure. It turns out that my access token isn't valid for those API endpoints.
So my question is, how do I get an access token that IS valid for those API's? Or is it even possible? Keep in mind that they're separate App registrations in the Azure-portal, and that I can only edit my own one, not the one of my school.
Here is my JavaScript file, with some comments:
const config = {
auth: {
clientId: "my_client_id_is_here",
authority: "https://login.microsoftonline.com/my_tenant_id_is_here",
redirectUri: "localhost"
}
};
async function login() {
console.log("Started..")
var client = new Msal.UserAgentApplication(config);
var request = {
scopes: [ 'User.Read' ]
};
let loginResponse = await client.loginPopup(request);
console.dir(loginResponse);
let tokenResponse = await client.acquireTokenSilent(request);
console.dir(tokenResponse);
// User REQUEST - Here I fetch the Graph API for some profile information, which works fine and writes it to the HTML perfectly.
let req = await fetch("https://graph.microsoft.com/v1.0/me/", {
headers: {
"Authorization": "Bearer " + tokenResponse.accessToken
}
});
let json = await req.json();
console.log(json);
document.write("Logged in as " + json.displayName);
document.write("<br>" + json.mail);
document.write("<br>" + json.jobTitle + " " + json.officeLocation);
// School Grades REQUEST - this is the part where I'm trying to fetch my School Grades, but it's not working since it gives me a 401 error..
let gradesReq = await fetch("https://myschool.azurewebsites.net/API/Grades/GetGrades", {
"headers": {
"authorization": "Bearer " + tokenResponse.accessToken
}
});
try {
let gradesJson = await gradesReq.json();
console.log(gradesJson);
} catch (err) {
document.write("An error occured while trying to get the school grades..")
}
}```
You're correct in your thinking. The reason you're getting this error is because you're using the access token acquired for a different scope (User.Read) with your API.
Fix is rather simple.
What you have to do is protect your API with Azure AD first. You may find this link helpful in implementing this functionality: https://learn.microsoft.com/en-us/azure/active-directory/develop/scenario-protected-web-api-overview.
Once you have done that, all you need to do then is to acquire token for your API. In that case, your scopes code will be something like the following:
var request = {
scopes: [ 'api://<your-application-id>/.default' ]
};
Once you acquire the token for this scope and use it with your API, you should not get 401 exception that you're getting.

Using appUser scoped tokens in Smooch

I am developing a widget that users in my company can use to communicate with end-users through Smooch.
The widget is accessible through the web browser and the communication goes mostly through a layer developed in node. However, I was trying to send attachments directly to Smooch to reduce the load in the server.
As I understand, it is necessary to use a token with a appUser scope to avoid issues with CORS.
I create the token using the following code
app.get('/getjwt', (req, res) => {
var token = jwt.sign({ scope: 'appUser', userId: req.body.userId }, SECRET, { header: { 'alg': 'HS256', 'type': 'JWT', 'kid': '[app key ID]' } });
res.send({ jwt: token });
});
I try to use the generated token (using Postman for tests) by making a request with Authorization Bearer [my generated token] and I get the following error:
{
"error": {
"code": "invalid_auth",
"description": "Invalid JWT header. Missing key id (kid)"
}
}
I have tried changing the 'kid' value to the app ID, the API key ID, and the API key Secret and I'm always getting the same error. What am I missing? Am I supposed to pass the Key ID somewhere else?
Thank you,
Your code works fine for me, what version of jsonwebtoken are you using? In v6.0.0 the headers option was renamed to header, so if you're using 5.x or lower your code should look like this instead
var token = jwt.sign({ scope: 'appUser', userId: req.body.userId }, SECRET, { headers: { 'alg': 'HS256', 'type': 'JWT', 'kid': '[app key ID]' } });
That said, Smooch already provides a fully functional web messenger / widget that you should use instead of attempting to build your own. It provides event hooks and methods to build a fully custom UI if that's what you're trying to achieve. See https://docs.smooch.io/guide/web-messenger/ and https://www.npmjs.com/package/smooch

Narro API:: message: 'Unauthorized'

I was trying to work with Narro API and MEAN stack. I have some text articles. I want to convert my text data to audio. From the requirements, it should use Narro.co for audio conversion. From their documentation, I started with authentication.
Here is the code,
var request = require("request");
var options = {
method: 'GET',
url: 'https://www.narro.co/api/v1',
headers: {
authorization: 'Bearer <access_token>'
}
};
request(options, function (error, response, body) {
if (error) throw new Error(error);
console.log(body);
});
We can generate the clientId and clientSecret from the Narro developer account.
The ClientId(sample) :
921edefq-540y-4g75-be2c-2ade450dc503
The clientSecret(sample):
a904efd2-a362-4cc5-80qe-262b24728b47743e244e-e39c-44e7-a479-3f0bt3445245
But it is not working.
I always end up with -
{ errors: [ { message: 'Unauthorized' } ] }
If it is not the right method, Please suggest me the best way to use Narro API with authentication.
You need to follow proper OAuth 2.0 flows.It would seem you want to use the Client Credential flow for your purposes, if you're not doing actions on behalf of a user.
I hope the ClientID and Secret there aren't actually yours.
Their own documentation page links to https://oauth.net/2/ which is where you can learn about the different flows, how to request a Bearer token, and how to then use that token to access the API endpoints. (Basically, read the docs...)

Categories