Call from app to phone (web), app. with multi linked numbers - vonage

My use case is to be able to make a call from web interface to any number.
It all seams to work fine.
get jwt > login and get app. instance from ConversationClient > make a call using app.callPhone(number) > GET request to answer_url.
And this is where I stuck, it works if I will hardcode one of the linked numbers, like:
return [{
action: 'connect',
from: 'number',
endpoint: [{
type: 'phone',
number: query.to
}]
}]
but how I can pass query.from? or somehow decide on client side from which number I want to call?
Because each app can be linked to many numbers, and I don't want to create an app per number, but don't see any other solution.

I believe at the moment the client only supports sending a single string from the browser to the application, which you're using for to but as MrO hinted you can pass anything as an identifier here. I would suggest putting the to and from in the string separated by a comma eg: 12125551212,14155551000 and the splitting that in your answerUrl handler.

Related

router.get(), use only part of url?

Currently I have this code:
router.get('/admins', function(res,req) {
However, I want it to be when someone goes to say, 'localhost:5000/admins/54323', I want the node-js app to notice 'hey, they're requesting for an admins list! lets find it'. However, with the router.get() function it only works if it is exactly that, is there a way to have it so if only the start is /admins then it sets a variable for the final part?
Through more research, I found an answer. I just put /:id after the /admins bit,
you can access the rest of the string in req.params.id where .id is the same as the string written after the : sign

what is good way to share constants between node and angular

Added at 15 Jan.
What i was worrying is to synchronize protocol values.
below is an API example.
GET /user/:type
type: 'admin' | 'guest' | 'operator'
as much as program get larger, those definitions get larger and more complex and it would be scattered in many places, so adding or changing something take more time.
what I can easily think to solve this problem is use json file.
at the first time each client or server begins, parsing those protocol.json files.
is it only way to solve it?
I hope you to understand what i'm wondering.
how to handle easily large and scattered definition in server and client each side.
I wanna share some enumerate values between client(Angular 6) and server(Node.js).
I have to synchronize some values while communicate client and server.
let me give a example.
// ProductType in Angular
export enum ProductType {
phone,
tablet,
laptop
}
// ProductType in node.js
const ProductType = module.exports.ProductType = {
phone: 0,
tablet: 1,
laptop: 2
}
as you know, it works properly, but I don't think this is good way, because it's getting difficult to manipulate as project is getting bigger and more complex.
what I want to do is share constants between client and server while transferring data.
It doesn't need to be number type, string type is ok.

how to troubleshooting nodejs?

I have a weird problem and need to troubleshoot it.
In my web application, I used the request module to get data from database. However, the request function didn't go to the api route setting(all other requests work well). How could I trace it to find out where it is coming from?
The error message I got back is:
{
errors: {
'confirmed_by.id': {
message: 'Cast to ObjectID failed for value "ending" at path "confirmed_by.id"',
name: 'CastError',
stringValue: '"ending"',
kind: 'ObjectID',
value: 'ending',
path: 'confirmed_by.id',
reason: [Object],
},
},
_message: 'order validation failed',
message:
'order validation failed: confirmed_by.id: Cast to ObjectID failed for value "ending" at path "confirmed_by.id"',
name: 'ValidationError',
}
Does anyone have any idea about this? Thanks in advance!
Richard
This error occur when you are trying to create a _id for the mongoose model using _id: new ObjectId(someVal). Here, you must ensure that the someVal should be 24 character hexadecimal value. Otherwise, it will raise that error. If say, you have someVal as 18 characters then add some static characters like aabbcc which is 6 characters more to make it 24 characters and most importantly, all needs to be hexadecimal characters.
There are several ways to debug a node application based on what you need to do or what issues you are having.
If you are on a fairly recent node version (v6.3+), you can always start your app with --inspect or --inspect-brk which will enable you to inspect your node code using Chrome. More details at https://nodejs.org/api/debugger.html#debugger_advanced_usage. In the case you are in an older version you can try with node-inspector
Another very useful tool is a network inspector (is that the right name?) like CharlesProxy; with this, you can configure your node application to proxy any http requests (configuration depends on which library you might be using) and inspect the traffic going between your node app and the rest of the world.

Is there any benefit to using an object instead of several variables?

I am writing an application in nodeJS - a Facebook messenger app.
My application contains a module called strings.js, which is basically used to store common strings. Any time I need to print a greeting or whatever I pull it from the strings.js file. Strings.js looks like this:
/*
* This module exports common strings.
* */
'use strict';
module.exports = {
// Quick replies for user to choose age range
ageReplies:[
{
//Option 1 CODE
},
{
//Option 2 CODE
},
{
//Option 3 CODE
}],
// Quick replies for user to choose gender
genderReplies:[
{
//Option 1 CODE
},
{
//Option 2 CODE
},
{
//Option 3 CODE
}],
// 'greetingButtons' is used to create the buttons sent to a registered
// user during the greeting
greetingButtons: [
{
//BUTTON 1 CODE
},
{
//BUTTON 2 CODE
},
{
//BUTTON 3 CODE
}],
userAgeString: "How old are you?",
userGenderString: "What's your gender?",
userInitialGreetingString: "Hello there! I don't believe we've spoken before. You'll need to create a user profile, so let's do that now.",
userNamePromptString: "What would you like me to call you?",
userPrefNamePromptString: "Ok, what would you like me to call you instead? Type it below:",
userWelcomeGreetingString: "Welcome back! I am ready and willing to serve, as always!",
};
The first two"objects" (if that's what we can call them), "ageReplies" and "GenderReplies" are used for generating quick replies in Facebook messenger when asking user for gender and age (during user profile creation).
The next is "greetingButtons", which is used for creating buttons, which are sent to a previously registered user with a "What would you like to do next?" message.
Finally I have a number of strings for greeting the user, prompting them to enter gender and age, and so on. There will be more of these as I add them.
I have been considering putting these individual strings in an object, for example as follows:
stringData: {
userAgeString: "How old are you?",
userGenderString: "What's your gender?",
userInitialGreetingString: "Hello there! I don't believe we've spoken before. You'll need to create a user profile, so let's do that now.",
userNamePromptString: "What would you like me to call you?",
userPrefNamePromptString: "Ok, what would you like me to call you instead? Type it below:",
userWelcomeGreetingString: "Welcome back! I am ready and willing to serve, as always!",
},
Is there any benefit to doing this? Is there any point?
Another question is, if I DID use an object like this, is it possible to put my buttons and quick replies into the same object, for example as below:
stringData: {
ageReplies:[ /* Age reply code */ ],
genderReplies: [ /* Gender reply code */ ],
greetingButtons: [ /* Button code */ ],
userAgeString: "How old are you?",
userGenderString: "What's your gender?",
userInitialGreetingString: "Hello there! I don't believe we've spoken before. You'll need to create a user profile, so let's do that now.",
userNamePromptString: "What would you like me to call you?",
userPrefNamePromptString: "Ok, what would you like me to call you instead? Type it below:",
userWelcomeGreetingString: "Welcome back! I am ready and willing to serve, as always!",
},
Would this work?
EDIT: Just to clarify, I'm not talking about having an object within my main code. The object I'm talking about would be within strings.js
Generally when writing a program that involves displaying text of some sort, I store all of my copy (text eventually sent to a user) in it's own file. These blocks of text have a variable name like you've made, and that allows me to refer to them around the system.
Why do I do this? Internationalisation (commonly shortened to i18n).
It's quite common practice to pull apart text displayed to uses from the rest of your application so that you can easily create multiple files for text and load from the correct one depending on the users language settings (or locale).
In that instance, you'd have a strings file per spoken language, where variable names are all the same. You then select from the specific file depending on settings / locale.
For this reason alone, I keep all my text separate from the rest of the application. This doesn't quite work when it's HTML based projects and such, but with things like nodejs server side error messages, it works perfectly.
Personally when I've built bots, the number of options (buttons) does not relate to the text I use in anyway. So my code to create varying options happens elsewhere, but will use the strings provided by my i18n module. This way text and buttons are decoupled nicely. Often button creation happens in a function that takes some sort of array of objects which represents the options for each button, I'll then pull in the text, when creating the final button markup, from my i18n files.
On a side note: I also don't label things like a "string" prefix or suffix, referring to something as i18n.welcomeGreeting or just welcomeGreeting and I find that's more than explicit enough for this stuff.
Tl;dr
It won't make a huge difference either way right now, but decoupling your text from your button creation can render useful benefits if your application is likely to grow in the future. It can also often make it easier to work with, and separates buttons from text. After all, you don't always use the two together in chat bots, so they should probably be separate concerns.

Best practices form processing with Express

I'm writing a website which implements a usermanagement system and I wonder what best practices regarding form processing I have to consider.
Especially performance, security, SEO and user experience are important to me. When I was working on it I came across a couple questions and I didn't find an complete node/express code snippet where I could figure out all of my below questions.
Use case: Someone is going to update the birthday of his profile. Right now I am doing a POST request to the same URL to process the form on that page and the POST request will respond with a 302 redirect to the same URL.
General questions about form processing:
Should I do a POST request + 302 redirect for form processing or rather something else like an AJAX request?
How should I handle invalid FORM requests (for example invalid login, or email address is already in use during signup)?
Express specific questions about form processing:
I assume before inserting anything into my DB I need to sanitize and validate all form fields on the server side. How would you do that?
I read some things about CSRF but I have never implemented a CSRF protection. I'd be happy to see that in the code snippet too
Do I need to take care of any other possible vulnerabilities when processing forms with Express?
Example HTML/Pug:
form#profile(method='POST', action='/settings/profile')
input#profile-real-name.validate(type='text', name='profileRealName', value=profile.name)
label(for='profile-real-name') Name
textarea#profile-bio.materialize-textarea(placeholder='Tell a little about yourself', name='profileBio')
| #{profile.bio}
label(for='profile-bio') About
input#profile-url.validate(type='url', name='profileUrl', value=profile.bio)
label(for='profile-url') URL
input#profile-location.validate(type='text', name='profileLocation', value=profile.location)
label(for='profile-location') Location
.form-action-buttons.right-align
a.btn.grey(href='' onclick='resetForm()') Reset
button.btn.waves-effect.waves-light(type='submit')
Example Route Handlers:
router.get('/settings/profile', isLoggedIn, profile)
router.post('/settings/profile', isLoggedIn, updateProfile)
function profile(req, res) {
res.render('user/profile', { title: 'Profile', profile: req.user.profile })
}
function updateProfile(req, res) {
var userId = req.user._id
var form = req.body
var profile = {
name: form.profileRealName,
bio: form.profileBio,
url: form.profileUrl,
location: form.profileLocation
}
// Insert into DB
}
Note: A complete code snippet which takes care of all form processing best practices adapted to the given example is highly appreciated. I'm fine with using any publicly available express middleware.
Should I do a POST request + 302 redirect for form processing or rather something else like an AJAX request?
No, best practice for a good user experience since 2004 or so (basically since gmail launched) has been form submission via AJAX and not web 1.0 full-page load form POSTs. In particular, error handling via AJAX is less likely to leave your user at a dead end browser error page and then hit issues with the back button. The AJAX in this case should send an HTTP PATCH request to be most semantically correct but POST or PUT will also get the job done.
How should I handle invalid FORM requests (for example invalid login, or email address is already in use during signup)?
Invalid user input should result in an HTTP 400 Bad Request status code response, with details about the specific error(s) in a JSON response body (the format varies per application but either a general message or field-by-field errors are common themes)
For email already in use I use the HTTP 409 Conflict status code as a more particular flavor of general bad request payload.
I assume before inserting anything into my DB I need to sanitize and validate all form fields on the server side. How would you do that?
Absolutely. There are many tools. I generally define a schema for a valid request in JSON Schema and use a library from npm to validate that such as is-my-json-valid or ajv. In particular, I recommend being as strict as possible: reject incorrect types, or coerce types if you must, remove unexpected properties, use small but reasonable string length limits and strict regular expression patterns for strings when you can, and of course make sure your DB library property prevents injection attacks.
I read some things about CSRF but I have never implemented a CSRF protection.
The OWSAP Node Goat Project CSRF Exercise is a good place to start with a vulnerable app, understand and exploit the vulnerability, then implement the fix (in this case with a straightforward integration of the express.csrf() middleware.
Do I need to take care of any other possible vulnerabilities when processing forms with Express?
Yes generally application developers must understand and actively code securely. There's a lot of material out there on this but particular care must be taken when user input gets involved in database queries, subprocess spawning, or being written back out to HTML. Solid query libraries and template engines will handle most of the work here, you just need to be aware of the mechanics and potential places malicious user input could sneak in (like image filenames, etc).
I am certainly no Express expert but I think I can answer at least #1:
You should follow the Post/Redirect/Get web development pattern in order to prevent duplicate form submissions. I've heard a 303-redirect is the proper http statuscode for redirecting form submissions.
I do process forms using the POST route and once I'm done I trigger a 302-redirect.
As of #3 I recommend looking into express-validator, which is well introduce here: https://developer.mozilla.org/en-US/docs/Learn/Server-side/Express_Nodejs/forms . It's a middleware which allows you to validate and sanitize like this:
req.checkBody('name', 'Invalid name').isAlpha();
req.checkBody('age', 'Invalid age').notEmpty().isInt();
req.sanitizeBody('name').escape();
I wasn't able to comment hence the answer even though it's not a complete answer. Just thought it might help you.
If user experience is something you're thinking about, a page redirection is a strong no. Providing a smooth flow for the people visiting your website is important to prevent drops, and since forms are already not such a pleasure to fill, easing their usage is primary. You don't want to reload their page that might have already took some time to load just to display an error message. Once the form is valid and you created the user cookie, a redirection is fine though, even if you could do things on the client app to prevent it, but that's out-of-scope.
As stated by Levent, you should checkout express-validator, which is the more established solution for this kind of purpose.
req.check('profileRealName', 'Bad name provided').notEmpty().isAlpha()
req.check('profileLocation', 'Invalid location').optional().isAlpha();
req.getValidationResult().then(function (result) {
if (result.isEmpty()) { return null }
var errors = result.array()
// [
// { param: "profileRealName", msg: "Bad name provided", value: ".." },
// { param: "profileLocation", msg: "Invalid location", value: ".." }
// ]
res.status(400).send(errors)
})
.then(function () {
// everything is fine! insert into the DB and respond..
})
From what it looks like, I can assume you are using MongoDB. Given that, I would recommend using an ODM, like Mongoose. It will allow you to define models for your schemas and put restrictions directly on it, letting the model handles these kind of redundant validations for you.
For example, a model for your user could be
var User = new Schema({
name: { type: String, required: [true, 'Name required'] },
bio: { type: String, match: /[a-z]/ },
age: { type: Number, min: 18 }, // I don't know the kind of site you run ;)
})
Using this schema on your route would be looking like
var user = new User({
name: form.profileRealName,
bio: form.profileBio,
url: form.profileUrl,
location: form.profileLocation
})
user.save(function (err) {
// and you could grab the error here if it exists, and react accordingly
});
As you can see it provides a pretty cool api, which you should read about in their docs if you want to know more.
About CRSF, you should install csurf, which has pretty good instructions and example usages on their readme.
After that you're pretty much good to go, there is not much more I can think about apart making sure you stay up to date with your critical dependencies, in case a 0-day occurs, for example the one that happened in 2015 with JWTs, but that's still kinda rare.

Resources