Failed to connect to video room in Twilio - node.js

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.

Related

Unable to retrieve auth string from auth endpoint - received status: 500

I using react native and backend is node.I trying implement pusher in my app.
Object {
"error": "Unable to retrieve auth string from auth endpoint - received status: 0 from http://10.0.27.124:8070/pusher/auth. Clients must be authenticated to join private or presence channels. See: https://pusher.com/docs/authenticating_users",
"status": 0,
"type": "AuthError",
}
Here is my react native code :
const pusher = new Pusher('73286f08a5b2aeeea398', {
cluster: 'ap1',
authEndpoint: 'http://10.0.27.124:8070/pusher/auth',
});
console.log(pusher)
const presenceChannel = pusher.subscribe('presence-channel');
Here is my node js code :
exports.authPusher = function (req, res) {
const socketId = req.body.socket_id;
const channel = req.body.channel_name;
console.log(req.body);
const presenceData = {
user_id: 'unique_user_id',
user_info: { name: 'Mr Channels', twitter_id: '#pusher' },
};
const auth = pusher.authenticate(socketId, channel, presenceData);
res.send(auth);
};
Thank you for answering.
I think you just forgot to use quote marks around authEndpoint parameter. Pusher is trying to call http instead of http://10.0.27.124:8070/pusher/auth.
const pusher = new Pusher('73286f08a5b2aeeea398', {
cluster: 'ap1',
authEndpoint: 'http://10.0.27.124:8070/pusher/auth',
});
If you open network tab on the web-developers toolbar of your browser, you must be able to see the actual request and debug it from there.

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.

Discord rest API: Kick members from guild

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)
...

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);
}

credentials used to authenticate does not have permission

I am trying to use firebase cloud messaging to deploy a http push notifications onto an actual device. When so, I am getting the error
"The credential used to authenticate this SDK does not have permission to send messages to the device corresponding to the provided registration token. Make sure the credential and registration token both belong to the same Firebase project."
I have checked the credentials on both the frontEnd and backEnd side and they all match up with my firebase correctly. I have tried to follow plenty of examples on here and I have missed on all of them. My node.js file looks like
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
export GOOGLE_APPLICATION_CREDENTIALS = "/Users/myname/mylocation/myfile.json"
exports.sendPushNotifications = functions.https.onRequest((req, res) => {
res.send("Attempting to send push notification")
console.log("LOGGER --- Trying to send push message..");
var uid = 'randomUIDString'
var fcmToken = 'myToken'
return admin.database().ref('/users/' + uid).once('value', snapshot => {
var user = snapshot.val();
console.log("username is " + user.name);
var payload = {
notification: {
title: 'Push Notification Title',
body: 'Test Notification Message'
}
}
admin.messaging().sendToDevice(fcmToken, payload)
.then(function(response) {
console.log('Succesfully sent message:', response);
console.log(response.results[0].error);
})
.catch(function(error) {
console.log('Error sending message', error);
});
})
})
The users name prints from calling the uid, but I am having trouble accessing the fcmToken.
I have checked my info.plist and the correct project is listed. Same with apple developer and appDelegate. is there something more that I am missing??

Resources