Twilio Fund Winner Profile: Wedgies, Making Social Polling Easy and Fun w/ Twilio

wedgies“Wedgies are fun to give. And it’s fun to watch what happens after,” explains Jimmy Jacobson, co-founder of social polling service Wedgies. “But we aren’t talking about in real life wedgies, like you got in school.”

Las Vegas based members, Wedgies, offers users easy, realtime social polls for the web. With Wedgies, you can share a poll on Twitter or broadcast an SMS poll to thousands of fans on a jumbotron at an NCAA basketball game (yeah, that happened).

We talked to Jimmy and the team about being a part of Vegas Tech their new API, and much more.

Learn more about fellow Twilio Fund winners Healthsouk, and Babelverse

Register for Twilio Fund Europe, our microfund supported by 500 Startups for Twilio-powered companies and products to the EU. Submissions are open now until May 1st, 2013 and we encourage you to apply now.

What led you to found Wedgies and when did you decide to focus on it full-time?

Have you ever taken a survey? I bet in your inbox you have a half dozen pleading messages from contacts begging you to take their 800 page, billion question survey.  And you aren’t going to answer them. We wanted to tackle this problem and bring polling and surveys into the 21st century with great UX, big data and realtime buzzwords.  Along the way we discovered there is a real appeal and need for fun and fast ways to give and answer surveys and polls. So we decided to go for it and work full time to make this a successful business.  And if you want to know how we got the domain name Wedgies.com, well you might have to buy us a beer first.

How are you using Twilio and do you have any big ships planned?

We believe you should be able to give Wedgies wherever your audience is. Twitter, your blog, or even in a large audience.  SMS is the perfect channel for allowing an audience to interact with your app. It’s platform agnostic and always backwards compatible. Wedgies is providing real time audience polling both for contests and audience intelligence.  We will be launching this as a product that anyone from teachers to politicians can sign up for and use.  For now, enjoy a picture of a satisfied customer who won a Wedgie at a Tech Cocktail event in LA this last month.

wedgies_team

What’s it like living/working in the same house with the team?

The Wedgies team all works out of a Ranch in Downtown Las Vegas, and a couple of us also live at the Ranch. At this stage in our company, it’s great to be able to focus wholeheartedly on our business and product by living in the same place we work. We’re a tight knit group and have a lot of fun working where we live.  We’ve done a good job of integrating our life and work together and are very proud of our Downtown Las Vegas community.

wedgiesscreenshot

How will the Twilio Fund affect your business?

We are very excited to be part of the Twilio Fund and join the other awesome companies in the portfolio. From hackathon to Startup Weekend and finally as part of this fund, Wedgies has received valuable assistance from developer evangelists, engineers and the marketing team at Twilio. And we look forward to continued collaboration as we deliver a product that will help both us and Twilio reach a larger audience.

Anything you’d like to add?

Dear Reader, Twilio is a great company because of the great people it hires. Both professionally and personally. The next time you see a Twilion in the wild, you should buy him or her a beer.  And the next time you need to make a poll, use Wedgies.com.

Posted by Kyle Kelly-Yahner on April 10, 2013 Tagged , ,

Add Two-Factor Authentication To Your Website with Google Authenticator and Twilio SMS

jf
This is an in-depth article that gives an example of how to add Two-Factor
Authentication to an existing Python application. If you are looking for software you can purchase and plug in, you should take a look at Authy.

Why Two-Factor Authentication?

Back in the day, it used to be that enforcing a strong password policy was sufficient to prevent unauthorized access into your user’s accounts. (Ah, those were the days, when kids were polite and respected their elders). However, as the security landscape continues to evolve, it is becoming clear that a strong password policy is not enough any more. Today, an attacker can discover your user’s password in a variety of ways: they might find your user’s password on a stolen or lost computer, they might find their password on another site where your user used the same password, or your user’s computer might be infected with a virus that is capturing their keystrokes.

In an ideal world, we would all be authenticating ourselves using tamper-proof hardware that implements a public-key cryptographic system. In the meantime, a simple and effective way of improving the way your users authenticate themselves is a method known as “Two-Factor Authentication“, “Two-Factor Auth”, or just “TFA”. Two-Factor Authentication is a method where your users are required to log in with two “factors”: a password, and a code from a device that they carry on their person. That device used to be a special-purpose device, but these days that device can just as well be a mobile phone.

A great pattern that we are seeing for implementing two-factor authentication is to use the TOTP (Time-based One-time Password Algorithm) standard for the second authentication step. What is so cool about TOTP is that it is flexible enough to allow your users to generate their authentication tokens directly on their smart phones using a TOTP app like Google Authenticator or have their tokens sent to their mobile phone via SMS.

This means that you only need to implement and test one additional authentication scheme, but get the benefits of having two different ways that your users can get tokens.

The best way to see how this is done is to look at some code. Let’s do that now.

Here are the topics that I’ll be covering:

  1. An Example of Application
    I will start with a very basic Python application that implements password authentication and build from there.
  2.  

  3. Understanding TOTP
    Before I show you how to add TOTP to that example application, I’ll explain how TOTP works.
  4.  

  5. Adding Two-Factor Authentication
    Now that we know more about how TOTP works, I’ll show you how to add it to the example application that we started with.
  6.  

  7. Adding Google Authenticator
    Here I will show you how to enable your users to authenticate via the Google Authenticator.
  8.  

  9. Adding Twilio
    Here I will show you how to enable your users to authenticate using a code that is delivered to their phone via SMS.
  10.  

  11. Try It Out Yourself
    Finally, I give you a working example of a site that can use both the Google Authenticator and SMS to do two-factor authentication.
  12.  

An Example of An Application

Below is the code for a very basic website that only uses a username and password for authentication. We will start with this code, and then add two-factor authentication to it.

import os

import bcrypt
from twilio.rest import TwilioRestClient
from flask.ext.login import LoginManager
from flask import Flask
from flask import request
from flask import redirect
from flask import url_for
from flask import render_template
from flask.ext.login import login_user
from flask.ext.login import logout_user
from flask.ext.login import current_user
from flask.ext.login import login_required
from pymongo import Connection

from konfig import Konfig

app = Flask(__name__)
konf = Konfig()
app.secret_key = konf.secret_key

connection = Connection(konf.mongo_url)

login_manager = LoginManager()
login_manager.setup_app(app)

twilio = TwilioRestClient()

@login_manager.user_loader
def load_user(user_id):
    return User(user_id)

class User:
    def __init__(self, user_id):
        self.id = user_id.lower()
        self.db = connection.tfa.users
        self.account = self.db.find_one({'uid': self.id})

    def create(self):
        self.db.insert({'uid': self.id})
        self.account = self.db.find_one({'uid': self.id})

    def save(self):
        self.db.save(self.account)

    def password_valid(self, pwd):
        pwd_hash = self.account['password_hash']
        return bcrypt.hashpw(pwd, pwd_hash) == pwd_hash

    # The methods below are required by flask-login
    def is_authenticated(self):
        """Always return true - we don't do any account verification"""
        return True

    def is_active(self):
        return True

    def is_anonymous(self):
        return False

    def get_id(self):
        return self.id

@app.route("/", methods=['GET', 'POST'])
def main_page():
    opts = {}
    if request.method == 'GET':
        return render_template('main_page.html', opts=opts)
    user = User(request.form['username'])
    if not user.account or not user.password_valid(request.form['password']):
        opts['invalid_username_or_password'] = True
        return render_template('main_page.html', opts=opts)
    login_user(user)
    return redirect(url_for('user'))

@app.route("/sign-up", methods=['GET', 'POST'])
def sign_up():
    opts = {}
    if request.method == 'GET':
        return render_template('sign_up.html', opts=opts)
    user = User(request.form['username'])
    if user.account:
        opts['username_exists'] = True
        return render_template('sign_up.html', opts=opts)
    if request.form['password1'] != request.form['password2']:
        opts['passwords_do_not_match'] = True
        return render_template('sign_up.html', opts=opts)
    user.create()
    pwd_hash = bcrypt.hashpw(request.form['password1'], bcrypt.gensalt())
    user.account['password_hash'] = pwd_hash
    user.save()
    login_user(user)
    return redirect(url_for('user'))

@app.route("/user")
@login_required
def user():
    opts = {'user': current_user,
            'logged_in': True}
    return render_template('user.html', opts=opts)

@app.route("/logout")
def logout():
    logout_user()
    return redirect(url_for('main_page'))

if __name__ == "__main__":
    # Bind to PORT if defined, otherwise default to 5000.
    port = int(os.environ.get('PORT', 5000))
    if port == 5000:
        app.debug = True
    app.run(host='0.0.0.0', port=port)

If you don’t want to read over everything, you can just focus on the “main_page()” function, here:

@app.route("/", methods=['GET', 'POST'])
def main_page():
    opts = {}
    if request.method == 'GET':
       return render_template('main_page.html', opts=opts)
    user = User(request.form['username'])
    if not user.account or not user.password_valid(request.form['password']):
       opts['invalid_username_or_password'] = True
       return render_template('main_page.html', opts=opts)
    login_user(user)
    return redirect(url_for('user'))

If you’re new to Python or Flask, here is what’s going on in the code:

The first line is a Python function decorator which tells Flask to register this function as the handler for GET and POST requests for ‘/’ (the main page)

@app.route("/", methods=['GET', 'POST'])
def main_page():
    opts = {}

This if statement is true if the request was a “GET” request, meaning, no data was sent to us to process. In that case, we just send HTML to the user.

    if request.method == 'GET':
        return render_template('main_page.html', opts=opts)

If we get to this point, then we know that we were sent a “POST” request, hopefully with a username and password. We check to see if the user or password are invalid. If the user or password are not valid, then we display an error saying so. Otherwise, we log the user in.

    user = User(request.form['username'])
    if not user.account or not user.password_valid(request.form['password']):
       opts['invalid_username_or_password'] = True
       return render_template('main_page.html', opts=opts)
    login_user(user)
    return redirect(url_for('user'))

The rest of the code in this example deals with including additional libraries, setting up the application, defining the User class and handling other website functionality.

You can see the full source on GitHub here: https://github.com/jpf/Twilio-TFA/tree/no-tfa
 

Understanding TOTP

Before we get started with adding two-factor authentication to this example application, let’s take a quick detour and to learn more about how TOTP works.

As you’ll find on Wikipedia, TOTP “is an extension of the HMAC-based One Time Password algorithm HOTP to support a time based moving factor.”

Based on that involved explanation, you might be surprised to find that generating a one time token with TOTP is not actually very complicated. Here is how you generate a 6 digit TOTP code:

  1. Compute the 20 byte HMAC of a “shared secret” and a timecode using HMAC-SHA1.
  2. Deterministically select an offset inside of that 20 byte HMAC.
  3. Starting at the offset, select a 4 byte range from the 20 byte HMAC.
  4. Turn the 4 byte range into an integer.
  5. Divide that integer by 1,000,000 (or “10**6″, the “6″ is the number of digits in the TOTP code)
  6. The remainder of that division is the 6 digit code – the TOTP code

If that isn’t making sense, try taking a look at RFC 6238 and this simple implementation of TOTP in Python below. If needed, you can cut and paste this code into a script and run it from your command line:

 

Adding Two-Factor Authentication

Now that you have a better understanding of how TOTP works, let’s see how we would add it to the example web application that we started with. The first place that we’ll be touching in our example above is the “main_page()” function, here’s what it looks like when it is modified to support logging in with two-factor authentication:

@app.route("/", methods=['GET', 'POST'])
def main_page():
    opts = {}
    if request.method == 'GET':
       return render_template('main_page.html', opts=opts)
    user = User(request.form['username'])
    if not user.account or not user.password_valid(request.form['password']):
       opts['invalid_username_or_password'] = True
       return render_template('main_page.html', opts=opts)
    totp_enabled = False
    for totp_type in ['totp_enabled_via_app', 'totp_enabled_via_sms']:
       if totp_type in user.account:
           totp_enabled = user.account[totp_type]
    if totp_enabled:
       session['uid'] = user.get_id()
       session['stage'] = 'password-validated'
       return redirect(url_for('verify_tfa'))
    else:
       login_user(user)
       return redirect(url_for('user'))

This should all look very familiar, it’s all the same code as before, with some modifications at the end.

Let’s go over these modifications in a little more detail.

Here is the code that we started out with. No big changes here.

@app.route("/", methods=['GET', 'POST'])
def main_page():
    opts = {}
    if request.method == 'GET':
       return render_template('main_page.html', opts=opts)
    user = User(request.form['username'])
    if not user.account or not user.password_valid(request.form['password']):
       opts['invalid_username_or_password'] = True
       return render_template('main_page.html', opts=opts)

Here is where we add our modifications. We start by checking to see if the user has one enabled two-factor authentication on their account via an app or SMS.

    totp_enabled = False
    for totp_type in ['totp_enabled_via_app', 'totp_enabled_via_sms']:
       if totp_type in user.account:
           totp_enabled = user.account[totp_type]

If either two-factor authentication method is enabled, the “totp_enabled” variable will be True.

If TOTP is enabled, we record the fact that the user’s password has been validated into the session state, and redirect the user’s browser to “/verify-tfa”.

Otherwise, if the user doesn’t have any form of two-factor authentication enabled, then we just log them in as before.

    if totp_enabled:
       session['uid'] = user.get_id()
       session['stage'] = 'password-validated'
       return redirect(url_for('verify_tfa'))
    else:
       login_user(user)
       return redirect(url_for('user'))

In the case where the user has two-factor authentication enabled, they will be redirected to a page to enter in their two-factor authentication token. Here is what the code behind that page looks like:

@app.route("/verify-tfa", methods=['GET', 'POST'])
def verify_tfa():
    user = User(session['uid'])
    opts = {'user': user}
    if request.method == 'GET':
       opts['sms_sent'] = user.send_sms()
       return render_template('verify_tfa.html', opts=opts)
    if not session['uid']:
       opts['error-no-username'] = True
       return render_template('verify_tfa.html', opts=opts)
    if session['stage'] != 'password-validated':
       opts['error-unverified-password'] = True
       return render_template('verify_tfa.html', opts=opts)
    if user.totp.valid(request.form['token']):
       login_user(user)
       session['stage'] = 'logged-in'
       return redirect(url_for('user'))
    else:
       opts['error-invalid-token'] = True
       return render_template('verify_tfa.html', opts=opts)

And here’s what that code does. Again, this is a Python method decorator that registers this method to handle “GET” and “POST” requests to the “/verify-tfa” path.

@app.route("/verify-tfa", methods=['GET', 'POST'])
def verify_tfa():

This loads in the user information from the session state that we saved before.

    user = User(session['uid'])
    opts = {'user': user}

If the request was a “GET” request, then we send the user an SMS with their token (if they have that configured) and then render the page prompting the user to enter their token.

    if request.method == 'GET':
       opts['sms_sent'] = user.send_sms()
       return render_template('verify_tfa.html', opts=opts)

This code does some sanity checking on the session data. We should never actually get into a state where this code will run, it’s here Just In Case.

    if not session['uid']:
       opts['error-no-username'] = True
       return render_template('verify_tfa.html', opts=opts)
    if session['stage'] != 'password-validated':
       opts['error-unverified-password'] = True
       return render_template('verify_tfa.html', opts=opts)

If we got to this point, we know that we got a POST request. We check to see if the user submitted a token, and if that token is valid for the user. If the token is valid, log the user in and send them to their user page!

    if user.totp.valid(request.form['token']):
       login_user(user)
       session['stage'] = 'logged-in'
       return redirect(url_for('user'))

Otherwise, if the token wasn’t valid, ask the user to enter their token again.

    else:
       opts['error-invalid-token'] = True
       return render_template('verify_tfa.html', opts=opts)

Adding Google Authenticator

Now that we have code to add TOTP authentication to the login process, let’s take a look at how we’ll get our users to enable TOTP authentication on their account.

Keep in mind that you don’t have to use Google Authenticator for this to work. TOTP is an IETF standard and has many different client implementations.

I’m using Google Authenticator in this example because it seems to be the most widely used TOTP client at this time. Let’s get started.

Here is the basic overview of how this part works:

  • The user visits a page to add Google Authenticator to their account.
  • The page contains a QR code that the user scans with Google Authenticator.
  • After scanning the QR code, the user will enter the 6 digit token that Google Authenticator displays

This is what the page will look like:

And here is the code that handles takes the 6 digit token and adds it to the user’s account.

@app.route("/enable-tfa-via-app", methods=['GET', 'POST'])
@login_required
def enable_tfa_via_app():
    opts = {'user': current_user}
    if request.method == 'GET':
       return render_template('enable_tfa_via_app.html', opts=opts)
    token = request.form['token']
    if token and current_user.totp.valid(token):
       current_user.account['totp_enabled_via_app'] = True
       current_user.save()
       return render_template('enable_tfa_via_app.html', opts=opts)
    else:
       opts['token_error'] = True
       return render_template('enable_tfa_via_app.html', opts=opts)

By this point, you should be familiar with the first part of this function.

Starting at line 7, we check to see if the token that the user entered is valid, this is an important step that makes sure that the user set up Google Authenticator correctly.

Once we know that the token is valid, we update a flag on the user’s account and save the update. The details of how this data is persisted will differ from application to application, so we don’t cover those details in this tutorial.

If there was an error with the token, notify the user and ask them to try again.

Finally, I wanted to show you how I generate the QR code. I’m generating my own QR code to avoid sending the shared secret to another service and reduce the risk of leaking the shared secret in a plaintext string.

Each account in Google Authenticator has an account name, so in this section we create a globally unique name for our user and then have our totp object make us an image with the QR code that will contain that account name and the TOTP shared secret for that account.

The object that the “.qrcode()” method can only write the image to a file. So here, we create a “StringIO”, a file-like object in memory, to write to. We write the image to that object and then send the contents over the wire.

@app.route('/auth-qr-code.png')
@login_required
def auth_qr_code():
    domain = urlparse.urlparse(request.url).netloc
    if not domain:
       domain = 'example.com'
    username = "%s@%s" % (current_user.id, domain)
    qrcode = current_user.totp.qrcode(username)
    stream = StringIO.StringIO()
    qrcode.save(stream)
    image = stream.getvalue()
    return Response(image, mimetype='image/png')

As I noted earlier, I’m glossing over several things here. I’m not showing you how I persist the user objects and I’m not showing you the HTML that gets sent to the user. If you’re wondering what those look like, take a look at the full source over here: https://github.com/jpf/Twilio-TFA

Adding Twilio

Once we’ve added support for Google Authenticator, it’s just a small additional step to give our users the ability to receive TOTP tokens on their phones via SMS. The procedure for adding SMS based two-factor authentication is very similar to adding support for Google Authenticator. The main difference is that instead of having our users scan a QR code, we have them enter in their mobile phone number.

Here is what this page looks like:

And here is the code that powers the page above.

@app.route("/enable-tfa-via-sms", methods=['GET', 'POST'])
@login_required
def enable_tfa_via_sms():
    opts = {'user': current_user}
    if request.method == 'GET':
       return render_template('enable_tfa_via_sms.html', opts=opts)
    if 'phone_number' in request.form and request.form['phone_number']:
       current_user.account['phone_number'] = request.form['phone_number']
       current_user.save()
       opts['sms_sent'] = current_user.send_sms(ok_to_send=True)
       opts['phone_number_updated'] = True
       return render_template('enable_tfa_via_sms.html', opts=opts)
    token = request.form['token']
    if token and current_user.totp.valid(token):
       current_user.account['totp_enabled_via_sms'] = True
       current_user.save()
       return render_template('enable_tfa_via_sms.html', opts=opts)
    else:
       opts['token_error'] = True
       return render_template('enable_tfa_via_sms.html', opts=opts)

In this code, we check to see if we got a phone number in the “POST” request.

If so, we take the phone number and send an SMS with the TOTP code to that phone number. We store the results of the SMS sending method in an option called “sms_sent”, if the SMS sending method returns “False” then the HTML template will display an error to the user saying that the phone number was invalid.

Assuming that previous section of code worked, the user should have recieved an SMS with their TOTP code and then entered that code into the page. In this part of the code, we check to see if we were give a token and see if that token is valid. If the token is valid, we enable two-factor authentication for this account and save that setting. As I said in the section on adding Google Authenticator, the details of how to persist the user settings will be unique to your situation, so I don’t cover that here. If there was an error validating the token, then we notify the user of that error via a flag that will be checked by our HTML template.

Summary

In this article, we showed you an example of a simple web application written in Python/Flask. We showed you how to add two-factor authentication to that application, Finally, we showed you how you would enable your users to use Google Authenticator or SMS to authenticate to that modified application.

What I didn’t cover is the HTML that I used in this example or how I saved the user data.

To really understand what is going on, I suggest that you try out the example I have running online and then look at the code.

Try it out yourself

If you want to see what this all looks like, here is a copy of the code running online for you to try out: http://twilio-tfa.herokuapp.com

All of the source code for this example is also available on GitHub: https://github.com/jpf/Twilio-TFA

Thanks for reading.

Please let me know if you have any additional questions, feedback or patches.

Posted by Joel Franusic on Tagged , , ,

TwilioCon 2013: Early Bird Tickets On Sale Now, Call For Speakers Open

TwilioCon 2013 Today we’re excited to kick off ticket sales and open the official call for speakers. Join us in San Francisco this September 17 – 19th at the Design Concourse in San Francisco for the 3rd annual TwilioCon.

Take advantage now of Super Early Bird discounts for both the conference and the Workshop Day, including special Entrepreneur pricing and complimentary tickets for students.

Call For Speakers: Accepting Submissions Now

Do you think like a Software person? What tools are essential for your business? What are your key strategies for leveraging communications? We’re looking for your insight on tools, strategy, technology, and success stories. Submit your speaker proposal here before May 15th, 2013.

TwilioCon 2012 Highlights

If you missed out on last year’s TwilioCon, we’re here to fill you in on the “Army of 1’s and 0’s”, the tech behind playing Twilio Chess via SMS, and how Twilio can improve your scalability and security. You can check out videos of our workshops, keynotes and sessions below.

Stay tuned to the blog for speaker updates, announcements and more. Grab your tickets here. We’ll see you at TwilioCon!

Posted by Kyle Kelly-Yahner on April 9, 2013 Tagged , ,

Introduction to Twilio Client with node.js

nodejs-1024x768

This is the second in a series of tutorial blog posts covering the use of Twilio’s new helper library for node.js.  Last time, we introduced you to the basic features and usage of the Twilio module for node. In this tutorial, we will introduce the APIs necessary for using Twilio Client, turning our browser-based node application into a full-fledged soft phone.  Stop by next week, when we’ll learn how to secure a node.js web application with two-factor authentication!

The official node.js helper library documentation is located here.

VoIP in the browser with node.js and Twilio Client

Twilio Client allows front-end developers to create rich VoIP communications apps using Twilio’s infrastructure on the back end.  With a few lines of code, any desktop web browser, iPhone app, or Android app can call any phone on the global telecom network, and receive calls from any of them as well.  Twilio Client requires the use of a special SDK on the client side (a JavaScript library for browser-based apps), which knows how to talk to the Twilio back-end to handle signaling, presence, and establishing a connection to other clients.

However, your application will also need to have code running on a server to generate what’s called a capability token.  At a high level, the capability token gives the client (in the browser, or in a native app on a phone) the authority to use your Twilio account (and credits) to make outbound or accept incoming calls.

Wait what?  Clients using my app get to spend my Twilio credits to make calls?

Yup, that’s right – which is why you’ll probably want to have code running on a server to determine whether or not you’re okay with that client using your credits (maybe by making sure they’re logged in and you know who they are).  You might also want to limit the amount of time the client can connect to the Twilio infrastructure.  When you generate a capability token on the server, that token contains all the permissions and limitations you want to grant a particular user.  In the browser, the Client SDK will send this token to the Twilio back-end, where we can verify that your account credentials were used to generate it, and determine what powers you have granted to this particular user.

The node.js module provides (along with all our other helper libraries) a simple, high-level API for generating a capability token to give to a client.  Let’s take a look at how this is done, and how to both accept and make calls in the browser.

Generating capability tokens for Twilio Client

As we discussed previously, the capability token is used by the Client SDK to tell Twilio’s back end which powers your browser-based client can have (either or both of accepting inbound and making outbound calls).  It will also verify that you, the app developer, have “blessed” that client to consume services.  The capability token must be signed with your account SID and auth token to allow this verification.  This must happen on the server to avoid exposing your account SID and auth token to your users.

There are more moving parts with Twilio Client than with other parts of the SDK, but it’s easy to get started!  Let’s do a simple browser phone right now using express, a popular node.js web framework.  Open up a command prompt or terminal window and create a new local directory for this exercise, and go to that directory in the terminal.

To use express, go to the terminal and install it via npm – depending on your system configuration, you may need to install the module using “sudo”:

[sudo] npm install express

Additionally, we will install a template engine to render HTML pages from express, called EJS:
[sudo] npm install ejs

Finally, we will need to install the Twilio module:

[sudo] npm install twilio

Now, create a new file called “server.js”.  Inside this file, we will use the Twilio helper library to generate an HTML page with contains a capability token.  This capability token will allow our browser-based client to accept inbound calls using the ID “kevin” (this could be any string, however).  This ID is like the phone number for our VoIP client in the browser – it should be unique for every user of your application.  Open “server.js” with your text editor and enter the following code:

This will respond to a GET request to the root path of our web application, and render an HTML template called “index.ejs”.  Back in the terminal, create a directory at the same level of “node_modules” and “server.js” called “views” – express will look here for view templates to render.  Inside the “views” directory, create a new file called “index.ejs”.  Open this file with your text editor and add the following code:

Now, back in the terminal, fire up your express application by running “node server.js”. Your simple VoIP client will now be available at http://localhost:1337/ to accept inbound calls!

But how do I call my browser?

So glad you asked! When we generated our capability token, we gave that browser-based client an ID (“kevin”). Twilio can route calls to that client in a few ways, but let’s see how we would route a call from a standard mobile phone to the browser based client. First, you will need to buy or select a phone number in your Twilio account. Click on a number your control – we are going to configure the “Voice URL” of this number to call our browser-based client.

The Voice URL for this number must point to a TwiML-generating URL out there on the internet. If you’re not familiar with TwiML, it’s a set of XML instructions which tell Twilio how to handle an incoming call or SMS to a given number. For testing purposes, one little utility we use a lot is the “Echo” Twimlet, which just allows us to post static TwiML on the internet and make it available for call routing instructions. Create a new echo Twimlet call using the XML in this Gist:

Which should look like this:

Fullscreen-20130404-115202
Copy the “Resulting URL” in the Twimlet, and paste it as the “Voice URL” for your Twilio number. Save your changes in the Twilio web UI to have Twilio use this new URL when a phone call is placed to your number.

Back in your terminal, launch your express app with “node server.js” if you haven’t already. Open your web browser to http://localhost:1337/ – then give your Twilio number a call on any phone! If all goes well, you should be hearing your own voice echoed back on your computer speakers.

Congrats – you just turned your browser into a phone!

Making outbound calls from the client

Alright, so we just accepted an inbound call in the browser – let’s also allow our client to make outbound calls. When a Twilio Client device in the browser wants to make an outbound call, Twilio’s back end will need to fetch TwiML that tells it how to behave during that call. That could be calling another phone, connecting to a conference call, or adding them to a queue for voice-based technical support.

For this example, we’re going to have the client call a number that we enter into a text field on our web page. First we’ll update our HTML UI to contain a text field and a button to handle initiating a call, and add some JavaScript to send a call off to the number we entered. Replace the contents of “index.ejs” with this file – note the new set of comments in the source, explaining each new parameter:

Next, we’ll need to update the capability token we generate on the server to enable this client to also make outbound calls using the “allowClientOutgoing” function. The argument to this function is the identifier of a TwiML application, which has a set of callback URLs associated with it to handle inbound voice and SMS calls.

A TwiML application has a few uses – one common use case is to allow a bunch of Twilio phone numbers to use the same Voice and SMS URLs, so you don’t have to copy/paste your server configuration in the website’s UI over and over again. The other use is handling outbound calls for Twilio Client apps.

The Voice URL for a TwiML app is requested when a client tries to make an outbound call. Twilio Client knows which TwiML app to use because when the capability token is generated, it can be generated with the unique identifier of a TwiML app associated with it. Let’s create a TwiML app right now, which will make use of another Twimlet that simply forwards to a given phone number (using a verified caller ID). You can create a TwiML app here. For the voice URL, configure the URL for the Forward Twimlet:
 
Twilio_User_-_Account_Apps_Add-20130404-132422
When your app is created, a new unique identifier will be generated for it. We will need this value in our server-side node.js code:
 
Twilio_User_-_Account_Apps-20130404-124314
Take this value, and update “server.js” with the following code, replacing “APP_SID” with the unique identifier of the TwiML application we just created:

Restart your node.js server process to pick up the changes we just made (you can kill it with Control-C). Now visit http://localhost:1337/ in your browser, and enter your phone number. You should now have an outbound call routed from the browser!

Conclusion

In this tutorial, we have explored the concepts and APIs necessary to create voice over IP applications using node.js and Twilio Client. JavaScript code running in the browser uses the Twilio Client SDK to make connections to other clients out on the telecom network. The Twilio node.js module assists on the server side, generating capability tokens that configure the permissions of VoIP clients.

With very little code, you can add in-browser calling to your node.js webapps, which is great for apps from call centers to online dating sites. We’re very excited to see what the node.js community can build. Please stop by next week, when we will build a web application that is protected using two-factor authentication. See you then!

Posted by Kevin Whinnery on April 7, 2013 Tagged , , ,

Twilio SxSW Panel Rewind: Your Execution Year and After The Hackathon

After The Hackathon

After The HackathonAre LAN parties the original hackathon? What’s the goal of a hackathon? Joel Franusic (co-founder of Super Happy Dev House) leads a discussion with organizers of Hack N’ Jill, Hacker Olympics, and Music Hack Day about the current state of the hackathon, how prizes affect the build process, and what happens after the hackathon.

See Megan Kilgore’s Storify of the panel here.

Your Execution Year

Your Execution Year
So you’ve locked in your series B funding and you’ve developed your customer base. That’s great, now it’s time to really work. Rob Spectre details what your execution year looks like, why it’s essential to your startup’s success.

From hiring, to shipping code, to obsessing over the customer. Rob explains what your next four quarters will look like using slides of robot unicorns, polar bears, and cowboys.
 
Read the outline of Rob’s talk here.
View Rob’s (awesome) slides here.

Posted by Kyle Kelly-Yahner on April 5, 2013 Tagged , ,

Vision Mobile Puts Data In Developer’s Hands w/ Developer Economics Survey

devsurveyFor developers, data is important but quality data is essential to make strategic decisions and build awesome products. We’re happy to work with Vision Mobile to help drive the latest Developer Economics survey, giving developers the information they need to build successful businesses.

This ten minute survey compiles information on your type of work you’re doing, the size of your team and what you’re building. Your input is invaluable to the report. The more information collected, the higher quality of data to give back to developers.

The goal is to give developers a better sense of what platforms, business models, and teams are succeeding and why. Vision Mobile takes that data and creates valuable resources like white papers, graphs, and reports for developers.
This is the 5th Developer Economics survey from Vision Mobile. You can download previous survey results for free here. To take the survey visit their website here.  The survey will concludes at the end of May and the report will be available in June.

Posted by Kyle Kelly-Yahner on Tagged , ,

Day In The Life: Being A Twilio Product Manager

emmadanninTwilio is hiring for a Senior Product Manager! We’re looking for someone who can organize big ships, plan sprints, and drive worldwide expansion so any developer on the planet can use Twilio. You can find the job listing here. Now let’s take a look at a typical day for Product Manager, Emma Dannin.

Emma works on the Voice Team, collaborating with the engineering team to ship new products and empower developers worldwide. Emma comes from a unique background. She holds dual degrees in Cognitive Science and Music, and previously worked as a software developer. We talked to Emma about what led her to Twilio and Product Management.

How did you end up here at Twilio?

I was recruited from my former job. I thought the interview process was great, and the technology seemed really intriguing. I like that it’s a disruptive technology aimed at developers and enterprise companies; it resonated a lot with my prior experience.

What is a typical workday like for a Product Manager at Twilio?

There’s no such thing as typical in the workday of any product manager — that’s why so many of us who gravitate toward this field are extreme multitaskers. I do spend a lot of time emailing, chatting and using Jira.

How is your work as Senior Product Manager of Voice different than that of the messaging team or other engineering team?

There are a lot of eyes on what I do as it’s the product with the biggest chunk of company revenue, although I think messaging is probably the most similar in terms of what they build and team size.

What are some valuable skills or traits for someone looking to be a Product Manager at Twilio?

Intelligence, perseverance and even temperament.

What is the most challenging part of your job and what is the most rewarding?

The most challenging part is where the company is at — there’s a lot of growing up still to do as we build in important new processes as we scale. The most rewarding is working with such a driven, kind and often hilarious group of people.

What’s your most memorable experience at Twilio (so far)?

Spending New Years with Twilions up in Tahoe was definitely awesome. If it’s a question of something happening at the company — launching Jira or <Sip> are definitely two big wins, I think.

Why should someone join the Product Management team at Twilio? 

Twilio is not only growing as a product but as a company. There’s a lot of opportunities to define not just roadmaps but also process. The potential is pretty great.

Click here to apply for the position of Senior Product Manager.

Posted by Kyle Kelly-Yahner on April 3, 2013 Tagged , , ,

Twilio-Powered Nomorobo Wins FTC Robocall Challenge

twitter-profileIn October, the FTC declared war against illegal, unsolicited robocalling, and asked developers to join them in the fight. The FTC offered $50,000 and an FTC Technology Achievement Award to the developer who could build the best tool to deter robocalling. Today, the FTC announced Aaron FossNomorobo as one of the two winners. Powered by Twilio, Nomorobo acts as a middleman, snuffing out illegal calls before they get to the consumer.

So how does Nomorobo decide who’s a robocaller, who’s a legal telemarketer and act accordingly– all before your phone rings?

Nomorobo uses conditional call forwarding to cache the potential robocall. From there, it inspects the caller’s call frequency. Let’s say the caller made 3,000 calls in the one minute. Odds are it’s a robocaller, and Nomorobo hangs up on them.

Nomorobo also checks if the caller is on an FTC blacklist or a whitelist. If the caller is blacklisted, Nomorobo hangs up on caller. If the caller is on an FTC whitelist as a legal telemarketer, Nomorobo passes on the call. If Nomorobo isn’t sure, it’ll prompt the caller with an audio CAPTCHA to determine if the caller’s human. If they pass the CAPTCHA, their call goes through. If they fail, Nomorobo adds that number to the FTC blacklist in realtime.

The whole service takes place in the cloud. There are no infrastructure changes, or hardware required. This was one of FTC’s guidelines for the contest. Creator Aaron Foss said “their number one criteria for the winner was ‘how feasible is it to get this launched, and get people using it as fast as possible.’”

Aaron is no stranger to building and scaling products fast. He holds two patents, previously founded SideTour and Alegean, and is currently co-founder and lead developer at SmartChemo.

Congrats to Aaron on his big win, and fighting the good fight against Robocallers.

To learn more about Aaron visit his website here.

Posted by Kyle Kelly-Yahner on April 2, 2013 Tagged , ,