Discord rest API: Kick members from guild - node.js

I'm trying to use the Discord Rest API and the "unirest" module with node.js to kick members from my server:
const unirest = require('unirest');
const guildId = "xyz";
const botSecret = "xyz";
const memberId = "xyz"
var request = 'https://discord.com/api/v8//guilds/' + guildId + '/members/' + memberId;
unirest.delete(request).send({"botToken": botSecret}).then((response) => {
console.log(response.body);
}).catch(error =>{
console.log(error);
})
However, I get a 401: Unauthorized response. The bot I'm using has the administrator role, so it is allowed to kick members from the guild.
I think that I'm making some mistakes in the request.

A 401 indicates you have not properly sent your authentication credentials.
If we look at the documentation for Discord Authentication we can see that they expect the bot token in the Authorization header instead of in the request like you have done.
We aren't using basic auth so we need to write the header manually.
unirest.delete(request)
.header('Authorization', 'Bot ' + botSecret)
...

Related

Telegram - 401 AUTH_KEY_UNREGISTERED

I am trying to get the Telegram API working by saving the StringSession in a database and then using it to access the channels on my telegram app.
But with the following codes, I am facing the issue around 401 - Unregistered Auth Key.
Is there anyway to verify that the Auth key is registered? Or is there anything wrong with the codes?
Any pointers will be greatly appreciated.
const apiId = result.apiId;
const apiHash = result.apiHash;
const _stringSession = new telegramStringSession.StringSession(result.stringSession);
const client = new telegramClient.TelegramClient(_stringSession, apiId, apiHash, {
connectionRetries: 3,
});
await client.connect();
const dialogs = await client.getDialogs(new iterDialogs(this, {
limit: 100
}));

PERMISSION_DENIED: IAM permission 'dialogflow.sessions.detectIntent' Node js

I have created a webhook for WhatsApp Chatbot using NodeJS following this online article: https://dev.to/newtonmunene_yg/creating-a-whatsapp-chatbot-using-node-js-dialogflow-and-twilio-31km
The webhook is linked to Twilio Sandbox for WhatsApp.
I have also provided the DialogFlow Admin API permission to service account on Google Cloud Platform.
When I send a new message from WhatsApp, it's received on Twilio and the webhook is triggered, but I am getting the following error on the console on my local machine.
"Error: 7 PERMISSION_DENIED: IAM permission 'dialogflow.sessions.detectIntent' on 'projects/xxxx-xxx-xxxx/agent' denied."
I am using Ngrok to tunnel the localhost build to the web and using that URL as the webhook URL in Twilio.
We have a client demo for this feature, so any quick help is appreciated. I am placing my dialog flow code and controller code below
dialogflow.ts
const dialogflow = require("dialogflow");
const credentials = require("../../credential-new.json");
const sessionClient = new dialogflow.SessionsClient({
credentials: credentials
});
const projectId: string = process.env.DIALOGFLOW_PROJECT_ID!;
export const runQuery = (query: string, number: string) => {
return new Promise(async (resolve, reject) => {
try {
// A unique identifier for the given session
//const sessionId = uuid.v4();
const sessionId = number;
// Create a new session
const sessionPath = sessionClient.sessionPath(projectId, sessionId);
// The text query request.
const request = {
session: sessionPath,
queryInput: {
text: {
// The query to send to the dialogflow agent
text: query,
// The language used by the client (en-US)
languageCode: "en-US"
}
}
};
// Send request and log result
const responses = await sessionClient.detectIntent(request);
const result = responses[0].queryResult;
resolve(result);
} catch (error) {
reject(error);
}
});
};
This issue got resolved by creating a new account on DialogFlow and providing new API key.
I think the problem is with the service account. Make sure you use the same email which is registered with Dialogflow and GCP and then create a service account and also make sure the service account email is present in the credential-new.json file is the same service account which has the Dialog Flow Admin Role and also check you have given the valid path to access credential-new.json file in the code.
You can safely do this by going to the settings menu on Dialogflow and then clicking on the project id, it will take you to the correct place.
Also, there may be a possibility that you forget to enable the Dialogflow API from the API section on GCP.

How to resolve Nodejs google-auth-library invalid token signature error?

I'm using flutter for my mobile app. I try to add sign in with google. Everything is okay for Flutter side. I'm gettin idToken from mobile app and send to my backend, nodejs.
Now, I want to use this idToken to authenticate user's requests on nodejs backend side with google-auth-library package.
let token = "token"
const CLIENT_ID = "client_id"
const { OAuth2Client } = require('google-auth-library');
const client = new OAuth2Client(CLIENT_ID);
async function verify() {
try {
const ticket = await client.verifyIdToken({
idToken: token,
audience: CLIENT_ID, // Specify the CLIENT_ID of the app that accesses the backend
// Or, if multiple clients access the backend:
//[CLIENT_ID_1, CLIENT_ID_2, CLIENT_ID_3]
});
const payload = ticket.getPayload();
const userid = payload['sub'];
console.log(payload)
} catch (error) {
console.log(error)
}
}
verify()
But this code always returns this error => Error: Invalid token signature:
at OAuth2Client.verifySignedJwtWithCertsAsync (\node_modules\google-auth-library\build\src\auth\oauth2client.js:566:19)
What should I do for to verify this idToken on nodejs backend side?
Thanks.
If the idToken that you are passing to the function is from the log of your flutter app, it is likely that you are not getting the entire idToken printed in the log due to the limitations of print().
I used the below code snippet to print out the idToken and used that in the API which gave me a success response.
print('ID TOKEN');
String token = googleAuth.idToken;
while (token.length > 0) {
int initLength = (token.length >= 500 ? 500 : token.length);
print(token.substring(0, initLength));
int endLength = token.length;
token = token.substring(initLength, endLength);
}

How to integrate rest api with front end website/app?

I already built out my restful api for logging in and registering, my question is how do I now use this api in my website? Isn't the point of an api to return json to consume? If i were to put a res.redirect() then wouldn't that make the api useless for later on when i want to use the api for say an iOS app?
router.post('/login', async (request, response) => {
// validate
const {error} = loginValidation(request.body)
if (error) return response.status(400).send(error.details[0].message)
const {email, password} = request.body
// check if email doesn't exist
const user = await pool.query('SELECT id, email, password FROM users WHERE email = $1 LIMIT 1', [email])
if(user.rowCount == 0) return response.status(400).send('Wrong email or password')
// password is correct; move on to validating password
const id = user.rows[0].id
const storedEmail = user.rows[0].email
const storedPassword = user.rows[0].password
const validPass = await bcrypt.compare(request.body.password, storedPassword)
if(!validPass) return response.status(400).send('Wrong email or password')
// create and send token to client
const token = jwt.sign({_id: id}, "SOMESECRET")
response.header('auth-token', token).send(token)
})
You could try these ways:
Make API calls from web clients(i.e. web browsers) with Javascript.
Set up a web server and make API calls from the server.

Failed to connect to video room in Twilio

I'm woking on building a web calling application in React + Twilio API. But it failed to post API and this is unable to connect to video room because of the token error.
an error:
POST https://ecs.us1.twilio.com/v2/Configuration 403
Unable to connect to Room: The authorization with Token failed
I have set up Twilio account like below:
1) Get Twilio credentials and API key
2) This time I use TEST Credentials. And I set up ACCOUNT_SID, API_KEY_SID, and API_KEY_SECRET to .env.
REACT_APP_TWILIO_ACCOUNT_SID = 'ACXXXXXXXXXXXXXX'
REACT_APP_TWILIO_AUTH_TOKEN = 'XXXXXXXXXXXXXXXXX'
REACT_APP_TWILIO_API_KEY_SID = 'SKXXXXXXXXXXX'
REACT_APP_TWILIO_API_KEY_SECRET = 'XXXXXXXXXXXXXXXXX'
3) Set up twilio configuration with API document
import twilio from "twilio";
const AccessToken = twilio.jwt.AccessToken;
const VideoGrant = AccessToken.VideoGrant;
// Substitute your Twilio AccountSid and ApiKey details
const ACCOUNT_SID = process.env.REACT_APP_TWILIO_ACCOUNT_SID;
const API_KEY_SID = process.env.REACT_APP_TWILIO_API_KEY_SID;
const API_KEY_SECRET = process.env.REACT_APP_TWILIO_API_KEY_SECRET;
// Create an Access Token
const accessToken = new AccessToken(ACCOUNT_SID, API_KEY_SID, API_KEY_SECRET);
// Set the Identity of this token
accessToken.identity = "my-user";
// Grant access to Video
const grant = new VideoGrant();
grant.room = "cool room";
accessToken.addGrant(grant);
// Serialize the token as a JWT
const twilioToken = accessToken.toJwt();
export default twilioToken;
4) call a room
connect(twilioToken, { name: "my-new-room" }).then(
room => {
console.log(`Successfully joined a Room: ${room}`);
room.on("participantConnected", participant => {
console.log(`A remote Participant connected: ${participant}`);
});
},
error => {
console.error(`Unable to connect to Room: ${error.message}`);
}
);
But it failed. What's wrong with this?
Passed with Live Account. I don't know why but Test account is not working.

Resources