how to setup twilio sms api in ionic angular? - node.js

#types/twilio
ran the following code and
installed twilio npm package
npm install twilio
In my provider i have imported by specifying
import * as twilio from 'twilio'
when i run by ionic serve --verbose
my console show an error that it cannot find module '../../package.json'
eventhough the library file has one, I will attach an image for reference

Twilio developer evangelist here.
The main Twilio Node.js module is not intended for use in a front end application so is unlikely to work well for you there. You are most likely getting that error as the Twilio module relies on some core Node modules that are unavailable in a browser environment.
It is not a good idea to try to use Twilio APIs from the client side as you expose your account credentials which would allow a malicious attacker to use your account for their own purposes.
Instead, we recommend you build a server that interacts with the Twilio API and that you make calls to from your own front end. If you are trying to use any of the Twilio client side SDKs, like Twilio Video, Twilio Chat or Twilio Sync, then you should install their respective modules twilio-video, twilio-chat and twilio-sync. You will still need a server side component that can generate access tokens for those services though.
Edit
In Node.js I just did a quick test for importing the Twilio module using TypeScript 2.6.2. This worked for me:
import { Twilio } from 'twilio';
const client = new Twilio("MY_ACCOUNT_SID", "MY_AUTH_TOKEN");
client.messages.each({ limit: 10 }, function(message) {
console.log(message.body);
});

Could you try this format for importing?
import { * as twilio } from 'twilio'

As philnash said, Twilio is not designed to run clientside. I tried to do the same thing you were doing. And you just have to have your Twilio run on a server and have your angular connect to that server to run it. Easiest way. Send a POST to your server via ajax and then have it run what you need.

Related

How to get nodejs on client-side on cordova?

I am making a app with cordova. I want the coinmarketcap stats in it. I am using nodejs and it is working fine when I execute it in my command line. However I want to use it in my cordova application. This is the link to the npm package https://www.npmjs.com/package/node-coinmarketcap
When I try to run it in a browser I get the error message require not defined. I believe that error comes because nodesj is a server-side and browser is a client side ? Am I correct ?
My code
var CoinMarketCap = require("node-coinmarketcap");
var coinmarketcap = new CoinMarketCap();
coinmarketcap.multi(coins => {
console.log(coins.getTop(10)); // Prints information about top 10 cryptocurrencies
});
I expect that I can run my code in my browser or cordova application.
You are right, Node.js is a JavaScript run-time environment that executes JavaScript code outside of a browser. You have to find some client-side JS code or execute your node code on your server and send result to your Cordova app.

How to integrate React native navigation with AWS Amplify push notifications in android?

I am trying to get FCM push notifications working in my react native project for android with react-native-notification library and aws-amplify. I have an issue with PushNotification.onRegister method is not called in android to get device token to send remote notifications.How can I make these two library working together in my react native project?
I followed aws-amplify documentation https://aws-amplify.github.io/docs/js/start?ref=amplify-rn-btn&platform=react-native
to include amplify library in react native project.
I then added push notifications set up as per https://aws-amplify.github.io/docs/js/push-notifications
I have included react-native-navigation library to support navigation in my react-native app as per
https://wix.github.io/react-native-navigation/#/docs/Installing
After the installation react-native navigation library pushNotification.onRegister method is not getting called to receive device token without which I am unable to send push notifications in android.
I have push notifications configured in App.js as per below
import PushNotification from '#aws-amplify/pushnotification';
import Analytics from '#aws-amplify/analytics';
import Auth from '#aws-amplify/auth';
// retrieve temporary AWS credentials and sign requests
Auth.configure(awsconfig);
// send analytics events to Amazon Pinpoint
Analytics.configure(awsconfig);
console.log(PushNotification);
PushNotification.configure(awsconfig);
Then in the constructor of App.js I am registering for PushNotification events.
Navigation.events().registerAppLaunchedListener(() => {
PushNotification.onNotification((notification) => {
// Note that the notification object structure is different from Android and IOS
console.log('in app notification', notification);
// required on iOS only (see fetchCompletionHandler docs: https://facebook.github.io/react-native/docs/pushnotificationios.html)
notification.finish(PushNotificationIOS.FetchResult.NoData);
});
// get the registration token
PushNotification.onRegister((token) => {
Alert.alert(token);
this.setState({token:token});
console.log('in app registration', token);
});
// get the notification data when notification is opened
PushNotification.onNotificationOpened((notification) => {
console.log('the notification is opened', notification);
});
});
This set up works fine and PushNotification.onRegister event is called and device token is getting printed if I don't include react-native-navigation library.
In iOS I am able to get device token with react-native-navigation library but in android it is not working. Any pointers on this issue would be greatly appreciated!
See here: https://github.com/aws-amplify/amplify-js/issues/2541#issuecomment-455245033
the Android app calls .onRegister() once only, when the app/device is completely new. The calls afterwards seems to load from cache.

fs.existsSync is not a function error when requiring grpc through create-react-app

We are trying to get gRPC to work with React (actually we were trying to get it to work with React-Native but gave up on that for now).
Using plain node.js things are pretty straight forward if you follow this example.
We started by using create-react-app but when we started the app, we got the following error:
existsSync is not a function
That was casued by this bit in pre-binding.js belonging to the node-pre-gyp package located in grpc:
var existsSync = require('fs').existsSync || require('path').existsSync;
My understanding is that something goes on with Webpack (or some other process run by create-react-app) that goes and returns and empty object instead of require('fs').
Any ideas of how to get this to work without having to give up on the wonders of create-react-app?
To test it out you can just follow these 2 easy steps:
create-react-app test-app
add import grpc from 'grpc'; in the App.js file
Basically, from what I understand now, you are not really supposed to use gRPC + Protobuf directly from any frontend but rather it is more common to use the grpc node package on node.js server-side code and then communicate with the browser-side code using Express.
The server-side code on node.js then communicates using grpc with the microservices.
We are testing out the use of Firebase Functions to communicate securely with the frontend and Firebase Functions communicate with the Go microservices using grpc.

Using websockets (socket.io) for sails 0.10.x

I am developing a node app on sails, my app needs to do regular exchange of data between server and client
The SailsCast video demonstrates the process for sails 0.9.x, and the mentioned files are not present in Sails 0.10.x
Also the sails doc says we should be using sails.socket instead of sails.io as the later will be deprecated in coming versions
Can any one help me in exchanging data between server and client through sockets. I have done it through node but with Sails MVC, i am not sure how to put the pieces together.
Any reference link or suggestion will be of great help
Thanks
I had the same trouble. You may want to check SailsSocket doc.
If you are loading sails.io.js in your page and haven't changed the default
io.sails.autoConnect to false, then a WebSocket should be created for you.
You can access it via io.socket
Create e.g. assets/js/dependencies/app.io.js with:
io.socket.on('connect', function socketConnected() {
console.debug("This is from the connect: ", io.socket);
console.debug("WebSocket is connected:", io.socket.isConnected());
});
Make sure to load this file after sails.io.js (See pipeline.js).
Open you browser console and double check.
Also check SailsSocket methods
Hope this help you get started

Using NodeJs with Firebase - Security

Due to the need to do some server side code - mainly sending emails I have decided to use Nodejs & Express for the server side element along with Firebase to hold the data - Partly from a learning experience.
My question is whats the best approach with regards to using the client side Firebase library and the Nodejs library when doing authentication using the Simple Email & Password API. If I do the authentication client side and then subsequently call a different route on the NodeJS side will the authentication for that user be carried across in the request. What would be the approach to test the user is authenticated within Node.
One approach I assume is to get the current users username & password from firebase and then post these to NodeJS and then use the firebase security API on the server to test.
Essentially the problem here is you need to securely convey to your NodeJS server who the client is authenticated as to Firebase. There are several ways you could go about this, but the easiest is probably to have all of your client<->NodeJS communication go through Firebase itself.
So instead of having the client hit a REST endpoint served by your NodeJS server, have the client write to a Firebase location that your NodeJS server is monitoring. Then you can use Firebase Security Rules to validate the data written by the client and your server can trust it.
For example, if you wanted to make it so users could send arbitrary emails through your app (with your NodeJS server taking care of actually sending the emails), you could have a /emails_to_send location with rules something like this:
{
"rules": {
"emails_to_send": {
"$id": {
".write": "!data.exists() && newData.child('from').val() == auth.email",
".validate": "newData.hasChildren(['from', 'to', 'subject', 'body'])"
}
}
}
}
Then in the client you can do:
ref.child('emails_to_send').push({
from: 'my_email#foo.com',
to: 'joe#example.com',
subject: 'hi',
body: 'Hey, how\'s it going?'
});
And in your NodeJS code you could call .auth() with your Firebase Secret (so you can read and write everything) and then do:
ref.child('emails_to_send').on('child_added', function(emailSnap) {
var email = emailSnap.val();
sendEmailHelper(email.from, email.to, email.subject, email.body);
// Remove it now that we've processed it.
emailSnap.ref().remove();
});
This is going to be the easiest as well as the most correct solution. For example, if the user logs out via Firebase, they'll no longer be able to write to Firebase so they'll no longer be able to make your NodeJS server send emails, which is most likely the behavior you'd want. It also means if your server is temporarily down, when you start it back up, it'll "catch up" sending emails and everything will continue to work.
The above seems like a roundabout way of doing things, I would use something like https://www.npmjs.com/package/connect-session-firebase and keep firebase as the model, handling all routes through express. Easier if your express server is rendering templates and not just behaving as a JSON API.
If you are using Firebase Authentication, the client side can import the Firebase Library (e.g. for javascript) and authenticate directly with the library itself
import firebase from 'firebase/app';
const result = await firebase.auth().signInWithEmailAndPassword(_email, _password);
After that, the client can to obtain the ID Token, this token will be informed on each request that will be made to the server (e.g. as header).
const sendingIdToken = await firebase.auth().currentUser.getIdToken();
On the Node.js server side, you can install the Firebase Admin SDK, to verify if the user is authenticated on the Node.js server, like:
// Let's suppose the client informed the token as header
const receivingIdToken = req.headers['auth-token'];
admin.auth().verifyIdToken(receivingIdToken, true)
.then((decodedIdToken) => { /* proceed to send emails, etc */}, (error) => {...});
The Firebase Admin SDK gives full permissions to the Database, so keep the credentials safe.
You should also configure the Security Rules on Firestore (or Firebase Realtime), so the client side can still perform specific operations directly to the database (e.g. listening for realtime changes on a collection), but you can also restrict all access if you want the client to only interact with the node.js server.
For more details, I developed an example of a node.js server that uses the Firestore Database and handles security and more.

Resources