Meteor Twilio SMS functionality issue and animate percentile JS query - javascript

Please see attached and kindly assist. Trying to add SMS functionality to a project but I'm getting a "Twilio is not defined error". What am I missing? Also, in terms of the code for the send button, where to I add my user ID, inside the Meteor call?
Then, as a completely unrelated query, with reference to the animated percentile code example, I was wondering if one could use different kinds of custom classes for this effect, say, a glass that appears to "fill up" based on % completeness out of a 100%. Further, could one state that multiple conditions had to be met before this percentage changes? i.e. X amount of forms filled out and X types of tasks assigned to another user in like a project management type app? (hope I'm being clear enough on this)
Your assistance is appreciated.

Twilio developer evangelist here.
Quick bit of StackOverflow advice first. It's best to stick to one question per question. I'm not sure of the percentcircle question you're asking, but I can help with Twilio! I'd recommend editing this question to just the Twilio one and asking the other question in a new question on SO.
Anyway, onto helping you!
Meteor doesn't play nicely with normal npm modules, so you can't just require the Twilio npm module. However, you are in luck as sending an SMS with Twilio is pretty straightforward without the library too.
This code is adapted from Chris Hranj's blog post on the Twilio site about creating a group messaging app with Twilio and Meteor. It uses the HTTP module from Meteor to make a POST request to the Twilio API. Chris also recommends keeping your Twilio credentials in the environment so that they don't get exposed by your Meteor front end.
Meteor.startup(function() {
Meteor.methods({
'sendSMS': function(phoneNumber, message) {
HTTP.call(
"POST",
'https://api.twilio.com/2010-04-01/Accounts/' +
process.env.TWILIO_ACCOUNT_SID + '/SMS/Messages.json', {
params: {
From: process.env.TWILIO_NUMBER,
To: phoneNumber,
Body: message
},
// Set your credentials as environment variables
// so that they are not loaded on the client
auth:
process.env.TWILIO_ACCOUNT_SID + ':' +
process.env.TWILIO_AUTH_TOKEN
},
// Print error or success to console
function (error) {
if (error) {
console.log(error);
}
else {
console.log('SMS sent successfully.');
}
}
);
}
})
})
Check out the post for more details.

Related

Google OAuth code flow, can't exchange code for token with error "redirect_uri_mismatch"

I'm implementing social login on my website.
I was able to implement the "One tap" flow, but I need to have an alternative to handle the "cooldown" which prevents the popup from appearing, if the user blocked it or closed it.
So I followed the "Authorization" flow on Google documentation.
Until yesterday morning everything was working fine and I succesfully exchanged the code with a token by calling
https://oauth2.googleapis.com/token
or
https://accounts.google.com/o/oauth2/token
sending secret and everything.
In a first instance I used Postman, then I made a sample code in a Spring project, before preparing the final code in another Spring project.
The first run in the final project I started getting a 400 error, with the redirect_uri_mismatch error key.
And then I was never able to do the exchange anymore, I get the same error from Postman as well.
The config is correct (It never changed from when it was working).
How can I solve this??
Here's some code
FRONTEND
this.client = google.accounts.oauth2.initCodeClient({
client_id: this.clientId,
scope: "openid profile email",
ux_mode: "popup",
redirect_uri: this.redirectUri,
callback: (response) => {
debugger;
this.submitFakeForm({
clientId: this.clientId,
code: response.code
});
}
});
this.client.requestCode();
POSTMAN PARAMS
this.redirectUri is identical to the one passed here and set up on Google credentials
FOR THE MOST SKEPTICAL, THE AUTHORIZED REDIRECTS :)
They're repeated in couples, because one is for local development, one is for the integration environment.
And of course the production config is on another credential.
Nowhere in the docs is this, but I came across this answer here on stackoverflow and it's basically suggesting not to pass the real redirect_uri, but to use a fixed string postmessage.
I want to point up again that I was using the real redirect_uri yesterday and it worked.
I will do some tests again in the future and update here if something changes.
For now just know that using postmessage fixed the issue for me
also I will be using https://oauth2.googleapis.com/token as endpoint, since it's the one mentioned in the (awful) docs, although https://accounts.google.com/o/oauth2/token works just as well.

Can't make WebSocketBundle subscribe/publish works. I followed official tutorial, bad setup?

I'm working on a Symfony2 application with WebSocketBundle.
https://github.com/GeniusesOfSymfony/WebSocketBundle.
The installation of the bundle has been done successfully.
So, I run a websocket server (port 8080 in local) with simple command : "php app/console gos:websocket:server"
while my symfony server is running (port 8000 in local).
I setup a simple client javascript to use WebSocketBundle following official tutorial which is on the github of the bundle.
When I come to a page on my website, I am correctly connected to the websocket server.
The problem comes when I want to use functions subscribe() and publish() that allow a user to subscribe to a channel, when anybody publish something on this channel, the message is received by the subscriber.
In my case, the message is not sent or received, I don't really know why because no revelant error is shown, I tried to follow as accurately as possible the official tutorial here :
https://github.com/GeniusesOfSymfony/WebSocketBundle/blob/master/Resources/docs/TopicSetup.md
But, unfortunately, I can't manage to make this works. That's why I solicit you to help me.
I share you below the most revelant piece of code to show how the setup takes place :
Client JavaScript :
[/web/js/own_scripts/gws_lobby.js]
var webSocket = WS.connect("ws://127.0.0.1:8080");
webSocket.on("socket/connect", function(session){
//session is an Autobahn JS WAMP session.
console.log("Successfully Connected!"); // I see this message
session.subscribe("dcqtv/lobby/1", function(uri, payload){
console.log("Message reçu : "+payload.msg);
});
session.publish("dcqtv/lobby/1", "testpublish");
});
// I should see "Message reçu : testpublish" in the console but that not happen
Parts of Topic Handler Service (only showing differences with this given in tutorial) :
[/src/AppBundle/DcqtvTopic.php]
namespace AppBundle;
class DcqtvTopic implements TopicInterface {
...
public function getName(){
return 'dcqtv.topic';
}
}
Register of the service with Symfony :
[/src/AppBundle/Resources/config/services.yml]
services:
dcqtv.topic:
class: AppBundle\DcqtvTopic
tags:
- { name: gos_web_socket.topic }
Link channel & topic with pubsub router (2 files here) :
[/src/AppBundle/Resources/config/pubsub/routing.yml]
dcqtv_topic:
channel: dcqtv/lobby/{lobby_id}
handler:
callback: 'dcqtv.topic' #related to the getName() of your topic
requirements:
lobby_id:
pattern: "\d+"
[/app/config/config.yml]
gos_web_socket:
server:
port: 8080 #The port the socket server will listen on
host: 127.0.0.1 #The host ip to bind to
router:
resources:
- #AppBundle/Resources/config/pubsub/routing.yml
This is quite long because I want to be explicit and clear enough, there are much code but that is necessary to well understand the whole thing.
Feel free to ask questions.
Thanks for your attention. Sorry if my english is bad.
loooks like you are missing
{{ ws_client() }}
https://github.com/GeniusesOfSymfony/WebSocketBundle/blob/master/Resources/docs/ClientSetup.md
hi i write this post to give you another way to use websocket and symfony i have never use your aproche but i build many application using this tutorial
if you find yourself stuck you can use it her

How do you integrate the Parse Javascript API with Appcelerator and not use undocumented calls?

I would like to create a user from his/her Facebook credentials without using undocumented calls. I do not believe it is possible based on the current implementation of Parse Javascript Library for two known reasons:
1. The current implementation of the library does not support the Appcelerator HTTP client so it fails immediately. I have addressed this issue by extending the existing Parse Javascript library's ajax method to utilize the Appcelerator HTTP client.
http://www.clearlyinnovative.com/blog/post/34758524107/parse-appcelerator-titanium-the-easy-way
There has been approximately 2K views on the slide deck I created and about the same on the blog post, so it is pretty clear to me people want this to work.
2. The current implementation of the library assumes you are integrating with the Facebook Javascript library and that library does not work with Appcelerator either. In fact Appcelerator has integrated Facebook directly into the framework so there is no need for the javascript library. All of the information required to link a user account to Facebook can be easily gotten using the API calls that Appcelerator developers are already familiar with.
The original question was removed from the Parse Support forum so I am looking for a solution from a wider community.
Hi Aaron,
It's not helpful to other developers to promote using undocumented
APIs in the Parse library as a workaround, so I make the decision to
unlist it. I understand it might help in your particular case with
Titanium, and you're well aware of the implications of using private
APIs, but other users might overlook that warning. I hope you
understand.
Héctor Ramos Solutions Architect, Parse https://parse.com/help
This is the code that was too dangerous to be left visible on the forum:
// setting auth data retrieved from Ti.Facebook login
authData = {
"facebook" : {
"id" : Ti.Facebook.uid,
"access_token" : Ti.Facebook.accessToken,
"expiration_date" : expDate, // "format: yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"
}
};
// Either way I resolved the problem, calling _handleSaveResult(true) on the returned user object,
// I just dont think it should have been as difficult as it was
// attempt to log the user in using the FB information
var user = new Parse.User();
user.save({
"authData" : authData
}).then(function(_user) {
// force the user to become current
_user._handleSaveResult(true); //<-- this is the evil method I called
if (!_user.existed()) {
// add additional user information
var userInfo = {
"acct_email" : "bryce#xxxxxx.com",
"acct_fname" : "Bryce",
"acct_lname" : "Saunders"
};
return _user.save(userInfo);
}
}).then(function(_user) {
alert('Hooray! Let them use the app now.');
}, function(error) {
alert(' ERROR: ' + JSON.stringify(error, null, 2));
});
Question on Appcelerator Forum
http://developer.appcelerator.com/question/152146/facebook-appcelerator-and-parse-integration-need-help
Question on Parse Forum
https://parse.com/questions/how-do-you-integrate-the-parse-javascript-api-with-appcelerator-and-not-use-undocumented-calls
Maybe this part of a newer SDK, but can't you just call:
Parse.FacebookUtils.logIn({
"facebook": {
"id": "user's Facebook id number as a string",
"access_token": "an authorized Facebook access token for the user",
"expiration_date": "token expiration date of the format: yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"
},
{
success : function(_user) {},
error : function(_user, error) {}
}
};
It's not documented in the Javascript guide, but it is documented in the unminified version of the code visa vie:
#param {String, Object} permissions The permissions required for Facebook
log in. This is a comma-separated string of permissions.
Alternatively, supply a Facebook authData object as described in our
REST API docs if you want to handle getting facebook auth tokens
yourself.
I made some updates to your original code to support the lastest SDK which I'm going to publish on Github.
Thanks so much for spearheading this effort. Your original post saved me hours.

How to customize the OData server using JayData?

I'm quite new to JayData, so this may sound like a stupid question.
I've read the OData server tutorial here: http://jaydata.org/blog/install-your-own-odata-server-with-nodejs-and-mongodb - it is very impressive that one can set up an OData provider just like that. However the tutorial did not go into details about how to customize the provider.
I'd be interested in seeing how I can set it up with a custom database and how I can add a layer of authentication/authorization to the OData server. What I mean is, not every user may have permissions to every entity and not every user has the permission to add new entities.
How would I handle such use cases with JayData?
Thanks in advance for your answers!
UPDATE:
Here are two posts that will get you started:
How to use the odata-server npm module
How to set up authentication/authorization
The $data.createODataServer method frequently used in the posts is a convenience method that hides the connect/express pipleline from you. To interact with the pipeline examine the method body of $data.createODataServer function found in node_modules/odata-server folder.
Disregard text below
Authentication must be solved with the connect pipeline there are planty of middleware for that.
For authorization EntityContext constructor accepts an authorization function that must be promise aware.
The all-allow authorizator looks like this.
function checkPerm(access, user, entitysets, callback) {
var pHandler = new $data.PromiseHandler();
var clbWrapper = pHandler.createCallback(callback);
var pHandlerResult = pHandler.getPromise();
clbWrapper.success(true); // this grants a joker rw permission to everyone
//consult user, entitySet and acces to decide on success/error
//since you return a promise you can call async stuff (will not be fast though)
return pHandlerResult;
}
I have to consult with one of the team members on the syntax that let you pass this into the build up process - but I can confirm this is doable and is supported. I'll get back with the answer ASAP.
Having authenticated the user you can also use EntityContext Level Events to intercept Read/Update/Create/Delete operations.
$data.EntityContext.extend({
MySet: { type: $data.EntitySet, elementType: Foobar,
beforeDelete: function(items) {
//if delete was in batch you'll get multiple items
//check items here,access this.request.user
return false // deny access
}
});
And there is a declarative way, you can annotate Role names with permissions on entity sets, this requirest that your user object actually has a roles field with an array of role names.
I too have been researching oData recently and as we develop our platform in both node and C# naturally looked at JayStorm. From my understanding of the technical details of JayStorm the whole capability of Connect and Express are available to make this topic possible. We use Restify to provide the private API of our platform and there we have written numerous middleware modules for exactly this case.
We are using JayData for our OData Service layer also, and i have implemnment a very simple basic authentication with it.
Since the JayData is using Express, so we can leverage Express' features. For Basic Auth, the simplest way is:
app.use(c.session({ secret: 'session key' }));
// Authenticator
app.use(c.basicAuth('admin', 'admin'));
app.use("/odata.svc", $data.JayService.OData.Utils.simpleBodyReader());
you also can refer to this article for more detail for authentication with Express: http://blog.modulus.io/nodejs-and-express-basic-authentication
Thanks.
I wrote that blogpost, I work for JayData.
What do you mean by custom database?
We have written a middleware for authentication and authorization but it is not open source. We might release it later.
We have a service called JayStorm, it has a free version, maybe that is good for you.
We probably will release an appliance version of it.

Websocket connection - no valid credentials

I'm trying to create a simple nodejs application that connects to the pathofexile.com/trade api.
The problem with this API is that is that you cannot use it unless you're logged in on the main website (my code works in the browser, but I'm trying to make it into a desktop application). There are several other applications that solves this issue by creating a session ID cookie with a users session ID (ID that you can get by logging in to the website). Unfortunately the documentation of the API is very limited and I havn't been able to find any information on how I can create/use the cookie as needed.
If I try to connect to the websocket, without being logged in to the main pathofexile website, I get the following error:
VM58:1 WebSocket connection to 'wss://www.pathofexile.com/api/trade/live/Metamorph/e602K4cL' failed: HTTP Authentication failed; no valid credentials available
I've tried using my sessionID to create a cookie like this by using the built in features in node:
const cookie = { name: 'POESESSID', value: '3acbf42fb842aasdqwe1a0c355f',domain:
'.pathofexile.com' }
session.defaultSession.cookies.set(cookie)
.then(() => {
// success
console.log("Cookie set (?)")
}, (error) => {
console.error(error)
})
Unfortunately, this does not work. I'm very unfamiliar with websockets (only started playing around with any of this a few days ago by accident), and I'm even less familiar with how websockets access and get data from cookies.
I've tried other modules like npm cookie-parser, npm request and npm needle to no avail.
The closest I've gotten to an answer is from a one year old reddit post where the user used C# to get this to work.
This is the code used in that example:
// Setup HTTP connection
HttpClientHandler handler = new HttpClientHandler();
CookieContainer cookieContainer = new CookieContainer();
cookieContainer.Add(composeUrl, new Cookie("POESESSID", sessionId));
handler.CookieContainer = cookieContainer;
HttpClient client = new HttpClient(handler);
If someone could help shine some light on this I'd be very appreciative. I understand that this question is incredibly niche and perhaps I'm asking it in the wrong forum, but I really don't know where to turn.
Appreciate any help!
//Alex

Categories

Resources