error making twilio rest api call in meteor - meteor

I was following the twilio tutorial but was having issues making the http call. I replaced the SID and token with my own, however when I submit the call I receive the following error:
Error: failed [401] {"code": 20003, "detail": "Your AccountSid or AuthToken was incorrect.", "message": "Authentication Error - No credentials provided", "more_info": "https://www.twilio.com/docs/errors/20003", "status": 401}(…).
I am confused because I am providing the correct credentials. My code is below. Thanks!
HTTP.call(
"POST",
'https://api.twilio.com/2010-04-01/Accounts/' +
'sid' + '/SMS/Messages.json', {
params: {
From: '+14013541756',
To: "+14012610096",
Body: "yo"
},
// Set your credentials as environment variables
// so that they are not loaded on the client
auth:
'SID+ ':' +
'token'
},
// Print error or success to console
function (error) {
if (error) {
console.log(error);
}
else {
console.log('SMS sent successfully.');
}
}
);
}

I don't this will even compile:
auth:
'SID+ ':' +
'token'
Should it be
auth:
SID+ ':' +
'token'
But that might be a red herring, have you checked your environment variables are set properly, with a console.log(process.env.XXX) - which assumes this method is being called from the server...?

Related

How to use SailsJs with firebase functions

I'm trying to create nodejs app with sails.js and firebase. Cannot understand how to access express part of SailsJs.
Firebase app initialized by
exports.app = functions.https.onRequest(app);
app - express app.
Sails app initialized by
sails.lift(rc('sails'));
Tried to access to sails.hooks.http.app but it is undefined. Any ideas?
Thanks
hi you can use this piece of code to to execute fire base messaging services and in same manner other services too
var request = require('request');
function sendMessageToUser(deviceId, message) {
request({
url: 'https://fcm.googleapis.com/fcm/send',
method: 'POST',
headers: {
'Content-Type' :' application/json',
'Authorization': 'key=AI...8o'
},
body: JSON.stringify(
{ "data": {
"message": message
},
"to" : deviceId
}
)
}, function(error, response, body) {
if (error) {
console.error(error, response, body);
}
else if (response.statusCode >= 400) {
console.error('HTTP Error: '+response.statusCode+' - '+response.statusMessage+'\n'+body);
}
else {
console.log('Done!')
}
});
sendMessageToUser(
"d7x...KJQ",
{ message: 'Hello puf'}
);
as sails provide a method mentioned below ,but i was not able find exact example to implement Firebase with it so i used core node to explain it , I will be updating this answer after i finished with this method and sails + Firebase
res.created()
hope this helps you in your work

Firebase Phone Auth Error 400

Just getting started with Firebase phone auth. Seems pretty slick however I've hit a wall with a bug.
{
"error": {
"errors": [
{
"domain": "global",
"reason": "invalid",
"message": "SESSION_EXPIRED"
}
],
"code": 400,
"message": "SESSION_EXPIRED"
}
}
Starting with the Captcha: (standard documentation code!)
var applicationVerifier = new firebase.auth.RecaptchaVerifier('recaptcha-container', {
'size': 'invisible',
'callback': function(response) {
},
'expired-callback': function() {
}
});
Its rendered and the captcha works well.
Next is the sign-in bit where you are sent the auth code to your phone. Works great:
$scope.signInWithPhoneNumber = function signInWithPhoneNumber() {
var phoneNumber = "*censored*";
var appVerifier = window.recaptchaVerifier;
firebase.auth().signInWithPhoneNumber(phoneNumber, applicationVerifier)
.then(function (confirmationResult) {
// SMS sent. Prompt user to type the code from the message, then sign the
// user in with confirmationResult.confirm(code).
window.confirmationResult = confirmationResult;
$scope.setConfirmationResult(confirmationResult);
alert('Result: ' + JSON.stringify(confirmationResult));
}).catch(function (error) {
// Error; SMS not sent
alert('Error: ' + error);
// ...
});
};
Finally its the authentication of the code that the user inputs from the text message. Here is when I get the error 400:
$scope.AuthenticateCode = function (code) {
var code = String(document.getElementById("auth_code").value);
var confirmationResult = $scope.getConfirmationResult();
alert(code);
confirmationResult.confirm(code).then(function (result) {
// User signed in successfully.
var user = result.user;
console.log('Signed In! ' + JSON.stringify(user));
// ...
}).catch(function (error) {
// User couldn't sign in (bad verification code?)
// ...
});
}//end of AuthenticateCode
The error is coming from the VerifyPhone method:
https://www.googleapis.com/identitytoolkit/v3/relyingparty/verifyPhoneNumber?key=censored
Any help or ideas?
Many Thanks,
Kieran
Ok, there are 2 likely reasons:
The code expired. The user took too long to provide the SMS code and finish sign in.
The code was already successfully used. I think this is the likely reason. You need to get a new verificationId in that case. Get a new reCAPTCHA token via the invisible reCAPTCHA you are using.
You are most likely to forget the "Country Code" before the phone no.
That is why firebase throw error 400 which means invalid parameters
If it's an Ionic3 project, change the following lines:
Imports:
import { AngularFireAuth } from 'angularfire2/auth';
import firebase from 'firebase';
Create var:
public recaptchaVerifier: firebase.auth.RecaptchaVerifier;
on "ionViewDidLoad()"
this.recaptchaVerifier = new firebase.auth.RecaptchaVerifier('recaptcha-container');
on "your_method(phoneNumber: number)"
const appVerifier = this.recaptchaVerifier;
const phoneNumberString = "+" + phoneNumber;
this.fireAuth.auth.signInWithPhoneNumber(phoneNumberString, appVerifier)
.then(confirmationResult => {
// SMS sent. Prompt user to type the code from the message, then sign the
// user in with confirmationResult.confirm(code).
let prompt = this.alertCtrl.create({
title: 'Enter the Confirmation code',
inputs: [{ name: 'confirmationCode', placeholder: 'Confirmation Code' }],
buttons: [
{
text: 'Cancel',
handler: data => { console.log('Cancel clicked'); }
},
{
text: 'Send',
handler: data => {
confirmationResult.confirm(data.confirmationCode)
.then(result => {
// Phone number confirmed
}).catch(error => {
// Invalid
console.log(error);
});
}
}
]
});
prompt.present();
})
.catch(error => {
console.error("SMS not sent", error);
});
Reference:
Firebase Phone Number Authentication
I got into a similar situation when a POST request to google API was returning Bad Request 400. When the message was logged, it said:
All requests from this device are blocked due to Unusual Activity. Please try again later
The issue was when the ReCaptcha was sensing a bot out of my development environment and it worked well when I tried later. During the rest of the development, I turned off this feature for easy work.

Meteor - Slack oAuth2 Accounts.LoginCancelledError

I am using in my Meteor application Slack package: acemtp:accounts-slack and Sign in with Slack button. Unfortunately I am getting an error and cannot login. I am getting following error in console:
"No matching login attempt found",
errorType: "Accounts.LoginCancelledError"
Button redirects me to the following link: https://slack.com/oauth/authorize?client_id=188243231058.189281460071&response_type=code&scope=identity.basic,identity.email,identity.avatar&redirect_uri=http://localhost:3000/_oauth/slack?close&state=eyJsb2dpblN0eWxlIjoicG9wdXAiLCJjcmVkZW50aWFsVG9rZW4iOiIzWktaaWFhdGNRNkpheld5WiIsImlzQ29yZG92YSI6ZmFsc2V9
and response is: 404 File Not Found
I've already added to my Slack application following redirect urls:
http://localhost:3000/_oauth/slack?close
http://localhost:3000/
Unfortunately it does not work. I am not sure what happened. It was working week ago and stopped yesterday. Users can't sign in.
This is my loginWithSlack method:
Meteor.loginWithSlack({requestPermissions: ["identity.basic", "identity.email", "identity.avatar"]}, (error) => {
if (error) {
$notification({
type: 'error',
title: 'Signup with slack error',
message: error.error ? error.error.message : JSON.stringify(error)
});
console.log(error);
slackLog.error(error);
} else {
this.$router.push({name: 'home'})
Meteor.call('loginSlackUpdate', (error) => {
if (error) {
$notification({
type:'warning',
title: "Error activating account",
message: error.error ? error.error.message : JSON.stringify(error)
});
slackLog.error(error);
}
});
}
});
The '?' in the redirect_uri is no longer accepted by Slack as a valid character. You can remove it by configuring the loginStyle property when configuring your Slack service (in your server side application code) :
ServiceConfiguration.configurations.upsert(
{ service: 'slack' },
{
$set: {
loginStyle: "redirect",
clientId: "1292962797", // See table below for correct property name!
secret: "75a730b58f5691de5522789070c319bc"
}
}
);
Link is here : http://docs.meteor.com/api/accounts.html#service-configuration
For more details, you can check this issue out too : https://github.com/meteor/meteor/issues/2758
Hope this helps!

Why is this core package being called?

I am trying to authenticate with Google through OAuth, and this is my server code
my.fetchTokens = function(code) {
var endpoint = 'https://accounts.google.com/o/oauth2/token';
var params = {
code: code,
client_id: Meteor.settings.google.CLIENT_ID,
client_secret: Meteor.settings.google.CLIENT_SECRET,
redirect_uri: Meteor.settings.google.REDIRECT_URL,
grant_type: 'authorization_code',
};
try {
response = HTTP.post(endpoint, { params: params });
} catch (err) {
throw _.extend(new Error("Failed to complete OAuth handshake with Google. " + err.message),
{response: err.response});
}
if (response.data.error) { // if the http response was a json object with an error attribute
throw new Error("Failed to complete OAuth handshake with Google. " + response.data);
}
var tokens = {
accessToken: response.data.access_token,
refreshToken: response.data.refresh_token,
expiresIn: response.data.expires_in,
idToken: response.data.id_token
};
console.log(tokens);
return tokens;
};
But when I invoke this method, I get the following warnings
W20150316-10:30:05.853(1) (oauth_server.js:71) Unable to base64 decode state from OAuth query: undefined
W20150316-10:30:05.854(1) (oauth_server.js:71) Unable to base64 decode state from OAuth query: undefined
W20150316-10:30:05.855(1) (oauth_server.js:71) Unable to base64 decode state from OAuth query: undefined
W20150316-10:30:05.855(1) (oauth_server.js:398) Error in OAuth Server: Match error: Expected string, got undefined
But I dont get why oauth_server.js:71 is being referenced
any ideas?
Probably because you're calling OAuth.openSecret or OAuth._redirectUri('google', config).
I assume one of these calls parses the current URL.

invalid_grant Google OAuth

I am trying to authentiate through Google's OAuth, but I'm having problems establishing a connection to their API
My client code:
'click #addChannel': function (event) {
event.preventDefault();
var userId = Meteor.userId();
var options = {
requestPermissions: [
'https://www.googleapis.com/auth/youtube',
'https://www.googleapis.com/auth/userinfo.email',
'https://www.googleapis.com/auth/youtube.force-ssl',
'https://www.googleapis.com/auth/youtube.readonly',
'https://www.googleapis.com/auth/youtube.upload',
'https://www.googleapis.com/auth/youtubepartner',
'https://www.googleapis.com/auth/youtubepartner-channel-audit',
],
requestOfflineToken: true
};
Google.requestCredential(options, function(token) {
Meteor.call('userAddOauthCredentials', userId, token, function(error, result) {
if (error) {
throw error;
}
console.log(result);
});
});
My server code:
userAddOauthCredentials: function(userId, token) {
check(userId, String);
check(token, String);
var config = ServiceConfiguration.configurations.findOne({service: 'google'});
if (!config) {
throw new ServiceConfiguration.ConfigError();
}
console.log(token, config);
var endpoint = 'https://accounts.google.com/o/oauth2/token';
var params = {
code: token,
client_id: config.clientId,
client_secret: OAuth.openSecret(config.secret),
redirect_uri: OAuth._redirectUri('google', config),
grant_type: 'authorization_code',
};
try { <------------------------------------------------------ this fails
response = HTTP.post(endpoint, { params: params });
} catch (err) {
throw _.extend(new Error("(first) Failed to complete OAuth handshake with Google. " + err.message),
{response: err.response});
}
if (response.data.error) { // if the http response was a json object with an error attribute
throw new Error("(second) Failed to complete OAuth handshake with Google. " + response.data);
} else {
return {
accessToken: response.data.access_token,
refreshToken: response.data.refresh_token,
expiresIn: response.data.expires_in,
idToken: response.data.id_token
};
}
The above throws a [400] { "error" : "invalid_grant" } error.
Most of the above code I got from how the meteor accounts-google packages logs in a user (which works fine in my application). Link to that:
https://github.com/meteor/meteor/blob/87e3c6499d5eacce62f10faefe9ce49c77bb03ee/packages/google/google_server.js
Any advice on how to proceed from here?
Much appreciated
UPDATE1:
I get these warnings in my log
W20150318-09:11:42.532(1) (oauth_server.js:71) Unable to base64 decode state from OAuth query: undefined
W20150318-09:11:42.532(1) (oauth_server.js:71) Unable to base64 decode state from OAuth query: undefined
W20150318-09:11:42.533(1) (oauth_server.js:71) Unable to base64 decode state from OAuth query: undefined
W20150318-09:11:42.534(1) (oauth_server.js:398) Error in OAuth Server: Match error: Expected string, got undefined
You have to parse your var params to application/x-www-form-urlencoded. Please find the below code to parse as i done in php
$fields_string="";
foreach($params as $key=>$value)
{
$fields_string .= $key.'='.$value.'&';
}
rtrim($fields_string, '&');
Now the $filed_string will contained the parse of params array.

Resources