I'm getting Twitter code 215 and code 400 which seems to suggest an error with my authentication. However, my keys are all right - twitter-oauth

I'm creating a Twitter bot but I keep getting this error: ApiResponseError: Request failed with code 400 - Bad Authentication data. (Twitter code 215). I am not sure what's causing it because I have added the right keys.
Here is the code;
const rwClient = require("./app.js");
const tweet = async () =>{
try{
await rwClient.v1.tweet("Good morning...")
}
catch(e){
console.error(e)
}
}
tweet()
Here is the code in app.js
const {TwitterApi} = require('twitter-api-v2');
const client = new TwitterApi({
appkey: "#################",
appSecret: "#################",
accessToken: "#################",
acessSecret:"#################"
})
const rwClient = client.readWrite
module.exports = rwClient
Kindly let me know how I can rectify this.
Thank you.

Related

Request works on Postman/Browser, but it doesn't work with axios

I make a GET request to this URL: https://api.mexc.com/api/v3/depth?symbol=BTCUSDT, if I use Postman or just paste it on my browser, it works, but if I use axios like this, it fails:
try {
const { data } = await axios.get(
'https://api.mexc.com/api/v3/depth?symbol=BTCUSDT'
);
console.log('data', data);
} catch (err) {
console.log(`Something went wrong:`, err);
}
You can test it on this link: https://stackblitz.com/edit/js-test-axios-njrh3z?file=index.js
Can someone explain me why please?
Mexc open api required a apikey for use they api.
https://mxcdevelop.github.io/apidocs/#api-key
If you log data response in axios, you will see this in console.
You don't have permission to access "http://api.mexc.com/api/v3/depth?" on this server.<P>\n
Let get an api key then use them api

Using MongoDb Realm authentication within a React app

I am learning MongoDb Realm from the documentation and following the examples given. My code to login is
const loginEmailPassword = async (email, password) => {
const app = Realm.App.getApp(APP_ID)
const credentials = Realm.Credentials.emailPassword(email, password)
try {
// Authenticate the user
const user = await app.logIn(credentials)
return true
} catch (err) {
console.error('Failed to log in', err)
}
return false
}
If the credentials match a current user all is good, if the don't it doesn't throw an error but generates the following in the console:
POST https://eu-west-1.aws.stitch.mongodb.com/api/client/v2.0/app/<"my Realm App ID">/auth/providers/local-userpass/login 401
Failed to log in Error: Request failed (POST https://eu-west-1.aws.stitch.mongodb.com/api/client/v2.0/app/<"my Realm App ID">/auth/providers/local-userpass/login): invalid username/password (status 401)
Can anyone please help me understand what is going on?

Error when trying to authorize Axios get request

I am trying to access the Uber API with Axios and I am running into some trouble. I have plugged this data into Postman and I get a 200 response code with no problems. However, when I try to make an Axios call, I get response code 401 unauthorized. Can I get some help looking through my code to find out why my authorization is not working correctly with Axios?
Here is a link to the Uber API docs I am referencing. Uber API Reference
getRide_Uber = async (addressOrigin, addressDestination) => {
let origin = await geocodeAddress(addressOrigin);
let destination = await geocodeAddress(addressDestination);
const url = "https://api.uber.com/v1.2/estimates/price";
const params = {
params: {
start_latitude: origin.lat,
start_longitude: origin.lon,
end_latitude: destination.lat,
end_longitude: destination.lon
}
};
const headers = {
headers: {
Authorization: `Token ${process.env.UBER_SERVER_TOKEN}`
}
};
const response = await axios
.get(url, params, headers)
.then(function(response) {
data = response.data;
})
.catch(function(error) {
console.log(error);
});
return data;
};
Please let me know if anything needs clarification. Thanks!
try below syntax,
const config = {
headers: {
Authorization: `Token ${process.env.UBER_SERVER_TOKEN}`
}
params: {
start_latitude: origin.lat,
start_longitude: origin.lon,
end_latitude: destination.lat,
end_longitude: destination.lon
}
};
const response = await axios
.get(url, config)
.then(function(response) {
data = response.data;
})
.catch(function(error) {
console.log(error);
});
return data;
There is one more aspect axios, async/await is not supported in Internet Explorer and older browsers. So also please check your browser versions as well.
Not sure how are you getting token from env but seems the server token is not getting pass correctly, may be few extra characters while reading from env. Try to run the program first with hard coded token in program itself and once you are sure its not code issue, you can move it into config/env and then debug env read issue.

How to fetch access token from OAuth used in google action for smart home

For my smart home action I used fake auth as shown in codelab- smartwasher application. (For testing purpose ). The app is working fine. I have build my own code to work with my devices(Switches). Now When I am implementing OAuth which uses my own custom OAuth server. I am not able to figure out how to implement it in my code. The OAuth is working as needed when I tested. But I want help in integrating it with google action. I am facing problem fetching access token.
The code is as follows:
exports.fakeauth = functions.https.onRequest((request, response) => {
const responseurl = util.format('%s?code=%s&state=%s',
decodeURIComponent(request.query.redirect_uri), request.query.code,
request.query.state);
console.log('*********'+responseurl);
return response.redirect(responseurl);
});
exports.faketoken = functions.https.onRequest((request, response) => {
const grantType = request.query.grant_type
? request.query.grant_type : request.body.grant_type;
const secondsInDay = 86400; // 60 * 60 * 24
const HTTP_STATUS_OK = 200;
console.log(`Grant type ${grantType}`);
let obj;
if (grantType === 'authorization_code') {
obj = {
token_type: 'bearer',
access_token: '123access',
refresh_token: '123refresh',
expires_in: secondsInDay,
};
} else if (grantType === 'refresh_token') {
obj = {
token_type: 'bearer',
access_token: '123access',
expires_in: secondsInDay,
};
}
response.status(HTTP_STATUS_OK)
.json(obj);
console.log('********** TOKEN **********',response);
});
The above code executes with fake auth.
Why is is not executing when I am implmenting custom OAuth?
Do I need to do any changes for clienID and secret in firebase?
How to fetch access token returned by OAuth?
Kindly help. I am new to node.js.
The authorization code that will come back in requests will be in the header, as an Authorization field. Here's a way to pull it out using Node.js.
function getToken(headers) {
// Authorization: "Bearer 123ABC"
return headers.authorization.substr(7);
}

Getting and "Error, wrong validation token" when trying to create a Facebook Chatbot

I'm trying to create a Facebook chatbot with NodeJS, Express, and a Heroku server.
I created my webhook on heroku and had it verified and saved by facebook. I then started adding code that would reply to the incoming messages and I can't seem to get it connected. It keeps saying "Error, wrong validation token" when I try to load my webhook in my browser. And when I try to send my bot a message I get no response. Even though I already had it verified and didn't change the code.
Here is my code:
var express = require('express');
var bodyParser = require('body-parser');
var app = express();
var port = process.env.PORT || 3000;
// body parser middleware
app.use(bodyParser.urlencoded({ extended: true }));
// test route
//app.get('/', function (req, res) { res.status(200).send('Hello world!') });
app.get('/', function (req, res) {
if (req.query['hub.verify_token'] === '8FKU9XWeSjnZN4ae') {
res.send(req.query['hub.challenge']);
}
res.send('Error, wrong validation token');
})
app.post('/', function (req, res) {
messaging_events = req.body.entry[0].messaging;
for (i = 0; i < messaging_events.length; i++) {
event = req.body.entry[0].messaging[i];
sender = event.sender.id;
if (event.message && event.message.text) {
text = event.message.text;
sendTextMessage(sender, "Text received, echo: "+ text.substring(0, 200));
}
}
res.sendStatus(200);
});
// error handler
app.use(function (err, req, res, next) {
console.error(err.stack);
res.status(400).send(err.message);
});
app.listen(port, function () {
console.log('Listening on port ' + port);
});
var token = <myToken>;
function sendTextMessage(sender, text) {
messageData = {
text:text
}
request({
url: 'https://graph.facebook.com/v2.6/me/messages',
qs: {access_token:token},
method: 'POST',
json: {
recipient: {id:sender},
message: messageData,
}
}, function(error, response, body) {
if (error) {
console.log('Error sending message: ', error);
} else if (response.body.error) {
console.log('Error: ', response.body.error);
}
});
}
So I'm confused as to why nothing is happening and why I'm getting that error. I feel like I'm missing a whole step. I am following this tutorial by the way: https://developers.facebook.com/docs/messenger-platform/quickstart
Any help is appreciated. Thanks!
Edit: Here are my heroku logs
Do not post your full access tokens here!
Have you tested the output of the challenge? Since it's just a GET and you know all values you can try it yourself: your-app-domain.com/your-callback-url?hub_mode=subscribe&hub_verify_token=the_token_you_set_in_your_app_config&hub_challenge=ping which sould print 'ping' if everything work fine.
Make sure you add sendStatus(200) to the hub challenge response, too.
You need to subscribe your page to the app first. To do so make a POST request to /your-page-id/subscribed_apps which should return "success". You can make a GET request to the same endpoint afterwards to double check your app is subscribed to your page
You did not mention which events you subscribed to (needs to be message_deliveries, messages, messaging_optins, messaging_postbacks)
Make sure the webhooks tab in your app dashboard now says "complete"
Test again
You are actually using "request" but you are never importing it anywhere. Here's how to fix it:
var request = require("request")
Once you have added that to your index.js or app.js file (basically whatever this file is), make sure you do:
npm install request --save
This should fix it. Unfortunately, Heroku doesn't error out and say that it does not know what "request" is and that's why it was so hard to figure this out in the first place!