Account Verification with Authy, Java and Servlets

Download the Code

Ready to implement user account verification in your application? Here's how it works at a high level:

  1. The users begin the registration process by entering their data, including a phone number, into a signup form.
  2. The authentication system sends a one-time password to the user's mobile phone to verify the possession of that phone number.
  3. The user enters the one-time password into a form before completing registration.
  4. The user opens a success page and receives an SMS indicating that their account has been created.

Building Blocks

To get this done, you'll be working with the following Twilio-powered APIs:

Authy REST API

  • Authy Docs: Find quick starts, documentation, and all about the helper libraries.

Twilio REST API

  • Messages Resource: We will use Twilio directly to send our user a confirmation message after they create an account.
Loading Code Samples...
Language
<?xml version="1.0" encoding="UTF-8"?>

<web-app xmlns="http://java.sun.com/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
         version="3.0">
    <welcome-file-list>
        <welcome-file>home.html</welcome-file>
    </welcome-file-list>
    <servlet>
        <servlet-name>registration</servlet-name>
        <servlet-class>com.twilio.verification.servlet.RegistrationServlet</servlet-class>
    </servlet>
    <servlet>
        <servlet-name>verify-code</servlet-name>
        <servlet-class>com.twilio.verification.servlet.VerifyCodeServlet</servlet-class>
    </servlet>
    <servlet>
        <servlet-name>account</servlet-name>
        <servlet-class>com.twilio.verification.servlet.AccountServlet</servlet-class>
    </servlet>
    <servlet>
        <servlet-name>resend-token</servlet-name>
        <servlet-class>com.twilio.verification.servlet.ResendTokenServlet</servlet-class>
    </servlet>

    <servlet-mapping>
        <servlet-name>registration</servlet-name>
        <url-pattern>/registration</url-pattern>
    </servlet-mapping>
    <servlet-mapping>
        <servlet-name>verify-code</servlet-name>
        <url-pattern>/verify-code</url-pattern>
    </servlet-mapping>
    <servlet-mapping>
        <servlet-name>account</servlet-name>
        <url-pattern>/account</url-pattern>
    </servlet-mapping>
    <servlet-mapping>
        <servlet-name>resend-token</servlet-name>
        <url-pattern>/resend-token</url-pattern>
    </servlet-mapping>

    <filter>
        <filter-name>authentication</filter-name>
        <filter-class>com.twilio.verification.filter.AuthenticationFilter</filter-class>
    </filter>

    <filter-mapping>
        <filter-name>authentication</filter-name>
        <url-pattern>/account</url-pattern>
        <url-pattern>/verify-code</url-pattern>
        <url-pattern>/resend-token</url-pattern>
    </filter-mapping>

    <filter>
        <filter-name>TeeFilter</filter-name>
        <filter-class>ch.qos.logback.access.servlet.TeeFilter</filter-class>
    </filter>

    <filter-mapping>
        <filter-name>TeeFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

    <filter>
        <filter-name>LoggingFilter</filter-name>
        <filter-class>com.twilio.verification.logging.LoggingFilter</filter-class>
    </filter>

    <filter-mapping>
        <filter-name>LoggingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
</web-app>
src/main/webapp/WEB-INF/web.xml
Deployment descriptor

src/main/webapp/WEB-INF/web.xml

Let's get started!

The User Model

The User Model for this use-case is pretty straightforward and JPA offers us some tools to make it even simpler. If you have already read through the 2FA tutorial this one probably looks very similar. We need to make sure that our User model contains a phone number, country code so that the user can be verified with Authy.

Loading Code Samples...
Language
package com.twilio.verification.model;

import javax.persistence.*;
import java.util.Date;

@SuppressWarnings("unused")
@Entity
@Table(name = "users")
public class User {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id")
    private int id;

    @Column(name = "name")
    private String name;

    @Column(name = "email")
    private String email;

    @Column(name = "password")
    private String password;

    @Column(name = "country_code")
    private String countryCode;

    @Column(name = "phone_number")
    private String phoneNumber;

    @Column(name = "authy_id")
    private int authyId;

    @Column(name = "verified")
    private boolean verified;

    @Column(name = "date")
    private Date date;

    public User() {
    }

    public User(String name, String email, String password, String countryCode, String phoneNumber, int authyId) {
        this.name = name;
        this.email = email;
        this.password = password;
        this.countryCode = countryCode;
        this.phoneNumber = phoneNumber;
        this.authyId = authyId;
        this.verified = false;
        this.date = new Date();
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getCountryCode() {
        return countryCode;
    }

    public void setCountryCode(String countryCode) {
        this.countryCode = countryCode;
    }

    public String getPhoneNumber() {
        return phoneNumber;
    }

    public void setPhoneNumber(String phoneNumber) {
        this.phoneNumber = phoneNumber;
    }

    public String getFullPhoneNumber() {
        return countryCode + phoneNumber;
    }

    public int getAuthyId() {
        return authyId;
    }

    public void setAuthyId(int authyId) {
        this.authyId = authyId;
    }

    public boolean isVerified() {
        return verified;
    }

    public void setVerified(boolean verified) {
        this.verified = verified;
    }

    public Date getDate() {
        return date;
    }

    public void setDate(Date date) {
        this.date = date;
    }
}
src/main/java/com/twilio/verification/model/User.java
User model definition and JPA mappings

src/main/java/com/twilio/verification/model/User.java

Next we will see how to handle the new user form.

New User Form

When we create a new user, we ask for a name, e-mail address, and a password. In order to validate a new account we also ask the user for a mobile number with a country code. We will use Authy to send a one-time password via SMS to this phone number.

It is now the servlet's responsibility to verify that the user provides the necessary information to create a new user. If the user is created successfully, they will be logged into the system automatically.

Loading Code Samples...
Language
package com.twilio.verification.servlet;

import com.authy.AuthyApiClient;
import com.twilio.verification.lib.RequestParametersValidator;
import com.twilio.verification.lib.SessionManager;
import com.twilio.verification.model.User;
import com.twilio.verification.repository.UsersRepository;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class RegistrationServlet extends HttpServlet {

    private final UsersRepository usersRepository;
    private final SessionManager sessionManager;
    private final AuthyApiClient authyClient;

    @SuppressWarnings("unused")
    public RegistrationServlet() {
       this(
               new UsersRepository(),
               new SessionManager(),
               new AuthyApiClient(System.getenv("AUTHY_API_KEY"))
       );
    }

    public RegistrationServlet(UsersRepository usersRepository, SessionManager sessionManager, AuthyApiClient authyClient) {
        this.usersRepository = usersRepository;
        this.sessionManager = sessionManager;
        this.authyClient = authyClient;
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        String name = request.getParameter("name");
        String email = request.getParameter("email");
        String password = request.getParameter("password");
        String countryCode = request.getParameter("countryCode");
        String phoneNumber = request.getParameter("phoneNumber");

        if (validateRequest(request)) {

            com.authy.api.User authyUser = authyClient.getUsers().createUser(email, phoneNumber, countryCode);

            // Create user remotely
            if (authyUser.isOk()) {
                int authyUserId = authyUser.getId();
                // Create user locally
                User user = usersRepository.create(new User(name, email, password, countryCode, phoneNumber, authyUserId));

                // Request SMS authentication
                authyClient.getUsers().requestSms(authyUserId);

                sessionManager.partialLogIn(request, user.getId());
                response.sendRedirect("/verify-code");
            }
        } else {
            preserveStatusRequest(request, name, email, countryCode, phoneNumber);
            request.getRequestDispatcher("/registration.jsp").forward(request, response);
        }
    }

    private boolean validateRequest(HttpServletRequest request) {
        RequestParametersValidator validator = new RequestParametersValidator(request);

        return validator.validatePresence("name", "email", "password", "countryCode", "phoneNumber")
                && validator.validateEmail("email");
    }

    private void preserveStatusRequest(
            HttpServletRequest request,
            String name,
            String email,
            String countryCode,
            String phoneNumber) {
        request.setAttribute("name", name);
        request.setAttribute("email", email);
        request.setAttribute("countryCode", countryCode);
        request.setAttribute("phoneNumber", phoneNumber);
    }
}
src/main/java/com/twilio/verification/servlet/RegistrationServlet.java
Handle registration of new accounts

src/main/java/com/twilio/verification/servlet/RegistrationServlet.java

Now the user is logged in but not verified. In the next steps we'll learn how to verify the user using Authy.

Configuring Authy

In .environment we list configuration parameters for the application. These are pulled from system environment variables, which is a helpful way to access sensitive values (like API keys). This prevents us from accidentally checking them into source control. We use the System.getenv method to load the key and inject the AuthyApiClient into the RegistrationServlet class.

Now we need our Authy production key (sign up for Authy here). When you create an Authy application the production key is found on the dashboard.

Authy dashboard

Loading Code Samples...
Language
package com.twilio.verification.servlet;

import com.authy.AuthyApiClient;
import com.twilio.verification.lib.RequestParametersValidator;
import com.twilio.verification.lib.SessionManager;
import com.twilio.verification.model.User;
import com.twilio.verification.repository.UsersRepository;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class RegistrationServlet extends HttpServlet {

    private final UsersRepository usersRepository;
    private final SessionManager sessionManager;
    private final AuthyApiClient authyClient;

    @SuppressWarnings("unused")
    public RegistrationServlet() {
       this(
               new UsersRepository(),
               new SessionManager(),
               new AuthyApiClient(System.getenv("AUTHY_API_KEY"))
       );
    }

    public RegistrationServlet(UsersRepository usersRepository, SessionManager sessionManager, AuthyApiClient authyClient) {
        this.usersRepository = usersRepository;
        this.sessionManager = sessionManager;
        this.authyClient = authyClient;
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        String name = request.getParameter("name");
        String email = request.getParameter("email");
        String password = request.getParameter("password");
        String countryCode = request.getParameter("countryCode");
        String phoneNumber = request.getParameter("phoneNumber");

        if (validateRequest(request)) {

            com.authy.api.User authyUser = authyClient.getUsers().createUser(email, phoneNumber, countryCode);

            // Create user remotely
            if (authyUser.isOk()) {
                int authyUserId = authyUser.getId();
                // Create user locally
                User user = usersRepository.create(new User(name, email, password, countryCode, phoneNumber, authyUserId));

                // Request SMS authentication
                authyClient.getUsers().requestSms(authyUserId);

                sessionManager.partialLogIn(request, user.getId());
                response.sendRedirect("/verify-code");
            }
        } else {
            preserveStatusRequest(request, name, email, countryCode, phoneNumber);
            request.getRequestDispatcher("/registration.jsp").forward(request, response);
        }
    }

    private boolean validateRequest(HttpServletRequest request) {
        RequestParametersValidator validator = new RequestParametersValidator(request);

        return validator.validatePresence("name", "email", "password", "countryCode", "phoneNumber")
                && validator.validateEmail("email");
    }

    private void preserveStatusRequest(
            HttpServletRequest request,
            String name,
            String email,
            String countryCode,
            String phoneNumber) {
        request.setAttribute("name", name);
        request.setAttribute("email", email);
        request.setAttribute("countryCode", countryCode);
        request.setAttribute("phoneNumber", phoneNumber);
    }
}
src/main/java/com/twilio/verification/servlet/RegistrationServlet.java
Register your AuthyAPIClient with your Authy API key

src/main/java/com/twilio/verification/servlet/RegistrationServlet.java

Now let's check out the Servlet handling a new user registration and see how it sends a token upon account creation.

Sending a Token on Account Creation

Once the user has an authyId we can actually send a verification code to that user's mobile phone using the Java Client for Authy.

When our user is created successfully via the form we implemented, we send a token to the user's mobile phone to verify their account in our servlet.

Loading Code Samples...
Language
package com.twilio.verification.servlet;

import com.authy.AuthyApiClient;
import com.twilio.verification.lib.RequestParametersValidator;
import com.twilio.verification.lib.SessionManager;
import com.twilio.verification.model.User;
import com.twilio.verification.repository.UsersRepository;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class RegistrationServlet extends HttpServlet {

    private final UsersRepository usersRepository;
    private final SessionManager sessionManager;
    private final AuthyApiClient authyClient;

    @SuppressWarnings("unused")
    public RegistrationServlet() {
       this(
               new UsersRepository(),
               new SessionManager(),
               new AuthyApiClient(System.getenv("AUTHY_API_KEY"))
       );
    }

    public RegistrationServlet(UsersRepository usersRepository, SessionManager sessionManager, AuthyApiClient authyClient) {
        this.usersRepository = usersRepository;
        this.sessionManager = sessionManager;
        this.authyClient = authyClient;
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        String name = request.getParameter("name");
        String email = request.getParameter("email");
        String password = request.getParameter("password");
        String countryCode = request.getParameter("countryCode");
        String phoneNumber = request.getParameter("phoneNumber");

        if (validateRequest(request)) {

            com.authy.api.User authyUser = authyClient.getUsers().createUser(email, phoneNumber, countryCode);

            // Create user remotely
            if (authyUser.isOk()) {
                int authyUserId = authyUser.getId();
                // Create user locally
                User user = usersRepository.create(new User(name, email, password, countryCode, phoneNumber, authyUserId));

                // Request SMS authentication
                authyClient.getUsers().requestSms(authyUserId);

                sessionManager.partialLogIn(request, user.getId());
                response.sendRedirect("/verify-code");
            }
        } else {
            preserveStatusRequest(request, name, email, countryCode, phoneNumber);
            request.getRequestDispatcher("/registration.jsp").forward(request, response);
        }
    }

    private boolean validateRequest(HttpServletRequest request) {
        RequestParametersValidator validator = new RequestParametersValidator(request);

        return validator.validatePresence("name", "email", "password", "countryCode", "phoneNumber")
                && validator.validateEmail("email");
    }

    private void preserveStatusRequest(
            HttpServletRequest request,
            String name,
            String email,
            String countryCode,
            String phoneNumber) {
        request.setAttribute("name", name);
        request.setAttribute("email", email);
        request.setAttribute("countryCode", countryCode);
        request.setAttribute("phoneNumber", phoneNumber);
    }
}
src/main/java/com/twilio/verification/servlet/RegistrationServlet.java
Handle registration of new accounts

src/main/java/com/twilio/verification/servlet/RegistrationServlet.java

When the code is sent we redirect to another page where the user can enter the token they received, therefore completing the verification process.

Verifying the Code

This servlet method handles the submission form. It needs to:

  • Get the current user.
  • Verify the code that was entered by the user.
  • If the code entered was valid, flip a boolean flag on the user model to indicate the account was verified.

Verifying the Code

The Authy client provides us with a verify() method that allows us to pass a user id and a token. In this case we just need to check that the API request was successful and, if so, set the User's verified field to true.

Loading Code Samples...
Language
package com.twilio.verification.servlet;

import com.authy.AuthyApiClient;
import com.authy.api.Token;
import com.twilio.verification.lib.RequestParametersValidator;
import com.twilio.verification.lib.Sender;
import com.twilio.verification.lib.SessionManager;
import com.twilio.verification.model.User;
import com.twilio.verification.repository.UsersRepository;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class VerifyCodeServlet extends HttpServlet {

    private final UsersRepository usersRepository;
    private final SessionManager sessionManager;
    private final AuthyApiClient authyClient;
    private final Sender sender;

    @SuppressWarnings("unused")
    public VerifyCodeServlet() {
        this(
                new UsersRepository(),
                new SessionManager(),
                new AuthyApiClient(System.getenv("AUTHY_API_KEY")),
                new Sender()
        );
    }

    public VerifyCodeServlet(
            UsersRepository usersRepository, SessionManager sessionManager, AuthyApiClient authyClient, Sender sender) {
        this.usersRepository = usersRepository;
        this.authyClient = authyClient;
        this.sessionManager = sessionManager;
        this.sender = sender;
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        request.getRequestDispatcher("/verifyCode.jsp").forward(request, response);
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        String code = request.getParameter("code");

        if (validateRequest(request)) {
            int userId = sessionManager.getLoggedUserId(request);
            User user = usersRepository.find(userId);

            Token token = authyClient.getTokens().verify(user.getAuthyId(), code);
            if (token.isOk()) {
                user.setVerified(true);
                usersRepository.update(user);
                // Send SMS confirmation
                sender.send(user.getFullPhoneNumber(), "You did it! Sign up complete :3");

                sessionManager.logIn(request, userId);
                response.sendRedirect("/account");
            } else {
                request.setAttribute("codeError", "Incorrect code, please try again");
                request.getRequestDispatcher("/verifyCode.jsp").forward(request, response);
            }
        } else {
            request.getRequestDispatcher("/verifyCode.jsp").forward(request, response);
        }
    }


    private boolean validateRequest(HttpServletRequest request) {
        RequestParametersValidator validator = new RequestParametersValidator(request);

        return validator.validatePresence("code");
    }
}
src/main/java/com/twilio/verification/servlet/VerifyCodeServlet.java
Verify an Authy code

src/main/java/com/twilio/verification/servlet/VerifyCodeServlet.java

That's all for token verification! However, our verification form wouldn't be very usable if there wasn't a way to resend a verification code if the message didn't arrive at the end user's handset.

Re-sending the Code

Since the form for re-sending the code is very simple, we're going to skip that for this tutorial. Let's just look at the servlet.

This method loads the user associated with the request and then uses the same Authy API method we used earlier to resend the code.

Loading Code Samples...
Language
package com.twilio.verification.servlet;

import com.authy.AuthyApiClient;
import com.twilio.verification.lib.SessionManager;
import com.twilio.verification.model.User;
import com.twilio.verification.repository.UsersRepository;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class ResendTokenServlet extends HttpServlet {

    private final UsersRepository usersRepository;
    private final SessionManager sessionManager;
    private final AuthyApiClient authyClient;

    @SuppressWarnings("unused")
    public ResendTokenServlet() {
        this(
                new UsersRepository(),
                new SessionManager(),
                new AuthyApiClient(System.getenv("AUTHY_API_KEY"))
        );
    }

    public ResendTokenServlet(
            UsersRepository usersRepository, SessionManager sessionManager, AuthyApiClient authyClient) {
        this.usersRepository = usersRepository;
        this.sessionManager = sessionManager;
        this.authyClient = authyClient;
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        int userId = sessionManager.getLoggedUserId(request);
        User user = usersRepository.find(userId);

        // Request SMS authentication
        authyClient.getUsers().requestSms(user.getAuthyId());

        response.sendRedirect("/verify-token");
    }
}
src/main/java/com/twilio/verification/servlet/ResendTokenServlet.java
Re-send an Authy verification code

src/main/java/com/twilio/verification/servlet/ResendTokenServlet.java

To wrap things up, let's implement the last step where we confirm that the user's account has been verified with a text message.

Sending the Confirmation Message

In this example, we create a single instance of the Twilio REST API helper, called client.

Then we need to get the account, the messageFactory, and finally use its sendMessage method in order to send an SMS to the user's phone

Loading Code Samples...
Language
package com.twilio.verification.lib;

import com.twilio.http.TwilioRestClient;
import com.twilio.rest.api.v2010.account.MessageCreator;
import com.twilio.type.PhoneNumber;
import com.twilio.verification.lib.Twilio.Config;

public class Sender {

    private final TwilioRestClient client;

    public Sender() {
        client = new TwilioRestClient.Builder(Config.getAccountSid(), Config.getAuthToken()).build();
    }

    public Sender(TwilioRestClient client) {
        this.client = client;
    }

    public void send(String to, String message) {
        new MessageCreator(
                new PhoneNumber(to),
                new PhoneNumber(Config.getPhoneNumber()),
                message
        ).create(client);
    }

}
src/main/java/com/twilio/verification/lib/Sender.java
Send a confirmation with a TwilioRestClient wrapper

src/main/java/com/twilio/verification/lib/Sender.java

Congratulations! You've successfully verified new user accounts with Authy. Where can we take it from here?

Where to Next?

If you're a Java developer working with Twilio, you might want to check out these other tutorials:

Click-To-Call

Put a button on your web page that connects visitors to live support or sales people via telephone.

Automated Survey

Instantly collect structured data from your users with a survey conducted over a voice call or SMS text messages.

Did this help?

Thanks for checking out this tutorial! If you have any feedback to share with us, we'd love to hear it. Reach out to us on Twitter and let us know what you build!

Agustin Camino
Kat King
Samuel Mendes
Hector Ortega

Need some help?

We all do sometimes; code is hard. Get help now from our support team, or lean on the wisdom of the crowd browsing the Twilio tag on Stack Overflow.

1 / 1
Loading Code Samples...
<?xml version="1.0" encoding="UTF-8"?>

<web-app xmlns="http://java.sun.com/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
         version="3.0">
    <welcome-file-list>
        <welcome-file>home.html</welcome-file>
    </welcome-file-list>
    <servlet>
        <servlet-name>registration</servlet-name>
        <servlet-class>com.twilio.verification.servlet.RegistrationServlet</servlet-class>
    </servlet>
    <servlet>
        <servlet-name>verify-code</servlet-name>
        <servlet-class>com.twilio.verification.servlet.VerifyCodeServlet</servlet-class>
    </servlet>
    <servlet>
        <servlet-name>account</servlet-name>
        <servlet-class>com.twilio.verification.servlet.AccountServlet</servlet-class>
    </servlet>
    <servlet>
        <servlet-name>resend-token</servlet-name>
        <servlet-class>com.twilio.verification.servlet.ResendTokenServlet</servlet-class>
    </servlet>

    <servlet-mapping>
        <servlet-name>registration</servlet-name>
        <url-pattern>/registration</url-pattern>
    </servlet-mapping>
    <servlet-mapping>
        <servlet-name>verify-code</servlet-name>
        <url-pattern>/verify-code</url-pattern>
    </servlet-mapping>
    <servlet-mapping>
        <servlet-name>account</servlet-name>
        <url-pattern>/account</url-pattern>
    </servlet-mapping>
    <servlet-mapping>
        <servlet-name>resend-token</servlet-name>
        <url-pattern>/resend-token</url-pattern>
    </servlet-mapping>

    <filter>
        <filter-name>authentication</filter-name>
        <filter-class>com.twilio.verification.filter.AuthenticationFilter</filter-class>
    </filter>

    <filter-mapping>
        <filter-name>authentication</filter-name>
        <url-pattern>/account</url-pattern>
        <url-pattern>/verify-code</url-pattern>
        <url-pattern>/resend-token</url-pattern>
    </filter-mapping>

    <filter>
        <filter-name>TeeFilter</filter-name>
        <filter-class>ch.qos.logback.access.servlet.TeeFilter</filter-class>
    </filter>

    <filter-mapping>
        <filter-name>TeeFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

    <filter>
        <filter-name>LoggingFilter</filter-name>
        <filter-class>com.twilio.verification.logging.LoggingFilter</filter-class>
    </filter>

    <filter-mapping>
        <filter-name>LoggingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
</web-app>
package com.twilio.verification.model;

import javax.persistence.*;
import java.util.Date;

@SuppressWarnings("unused")
@Entity
@Table(name = "users")
public class User {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id")
    private int id;

    @Column(name = "name")
    private String name;

    @Column(name = "email")
    private String email;

    @Column(name = "password")
    private String password;

    @Column(name = "country_code")
    private String countryCode;

    @Column(name = "phone_number")
    private String phoneNumber;

    @Column(name = "authy_id")
    private int authyId;

    @Column(name = "verified")
    private boolean verified;

    @Column(name = "date")
    private Date date;

    public User() {
    }

    public User(String name, String email, String password, String countryCode, String phoneNumber, int authyId) {
        this.name = name;
        this.email = email;
        this.password = password;
        this.countryCode = countryCode;
        this.phoneNumber = phoneNumber;
        this.authyId = authyId;
        this.verified = false;
        this.date = new Date();
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getCountryCode() {
        return countryCode;
    }

    public void setCountryCode(String countryCode) {
        this.countryCode = countryCode;
    }

    public String getPhoneNumber() {
        return phoneNumber;
    }

    public void setPhoneNumber(String phoneNumber) {
        this.phoneNumber = phoneNumber;
    }

    public String getFullPhoneNumber() {
        return countryCode + phoneNumber;
    }

    public int getAuthyId() {
        return authyId;
    }

    public void setAuthyId(int authyId) {
        this.authyId = authyId;
    }

    public boolean isVerified() {
        return verified;
    }

    public void setVerified(boolean verified) {
        this.verified = verified;
    }

    public Date getDate() {
        return date;
    }

    public void setDate(Date date) {
        this.date = date;
    }
}
package com.twilio.verification.servlet;

import com.authy.AuthyApiClient;
import com.twilio.verification.lib.RequestParametersValidator;
import com.twilio.verification.lib.SessionManager;
import com.twilio.verification.model.User;
import com.twilio.verification.repository.UsersRepository;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class RegistrationServlet extends HttpServlet {

    private final UsersRepository usersRepository;
    private final SessionManager sessionManager;
    private final AuthyApiClient authyClient;

    @SuppressWarnings("unused")
    public RegistrationServlet() {
       this(
               new UsersRepository(),
               new SessionManager(),
               new AuthyApiClient(System.getenv("AUTHY_API_KEY"))
       );
    }

    public RegistrationServlet(UsersRepository usersRepository, SessionManager sessionManager, AuthyApiClient authyClient) {
        this.usersRepository = usersRepository;
        this.sessionManager = sessionManager;
        this.authyClient = authyClient;
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        String name = request.getParameter("name");
        String email = request.getParameter("email");
        String password = request.getParameter("password");
        String countryCode = request.getParameter("countryCode");
        String phoneNumber = request.getParameter("phoneNumber");

        if (validateRequest(request)) {

            com.authy.api.User authyUser = authyClient.getUsers().createUser(email, phoneNumber, countryCode);

            // Create user remotely
            if (authyUser.isOk()) {
                int authyUserId = authyUser.getId();
                // Create user locally
                User user = usersRepository.create(new User(name, email, password, countryCode, phoneNumber, authyUserId));

                // Request SMS authentication
                authyClient.getUsers().requestSms(authyUserId);

                sessionManager.partialLogIn(request, user.getId());
                response.sendRedirect("/verify-code");
            }
        } else {
            preserveStatusRequest(request, name, email, countryCode, phoneNumber);
            request.getRequestDispatcher("/registration.jsp").forward(request, response);
        }
    }

    private boolean validateRequest(HttpServletRequest request) {
        RequestParametersValidator validator = new RequestParametersValidator(request);

        return validator.validatePresence("name", "email", "password", "countryCode", "phoneNumber")
                && validator.validateEmail("email");
    }

    private void preserveStatusRequest(
            HttpServletRequest request,
            String name,
            String email,
            String countryCode,
            String phoneNumber) {
        request.setAttribute("name", name);
        request.setAttribute("email", email);
        request.setAttribute("countryCode", countryCode);
        request.setAttribute("phoneNumber", phoneNumber);
    }
}
package com.twilio.verification.servlet;

import com.authy.AuthyApiClient;
import com.twilio.verification.lib.RequestParametersValidator;
import com.twilio.verification.lib.SessionManager;
import com.twilio.verification.model.User;
import com.twilio.verification.repository.UsersRepository;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class RegistrationServlet extends HttpServlet {

    private final UsersRepository usersRepository;
    private final SessionManager sessionManager;
    private final AuthyApiClient authyClient;

    @SuppressWarnings("unused")
    public RegistrationServlet() {
       this(
               new UsersRepository(),
               new SessionManager(),
               new AuthyApiClient(System.getenv("AUTHY_API_KEY"))
       );
    }

    public RegistrationServlet(UsersRepository usersRepository, SessionManager sessionManager, AuthyApiClient authyClient) {
        this.usersRepository = usersRepository;
        this.sessionManager = sessionManager;
        this.authyClient = authyClient;
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        String name = request.getParameter("name");
        String email = request.getParameter("email");
        String password = request.getParameter("password");
        String countryCode = request.getParameter("countryCode");
        String phoneNumber = request.getParameter("phoneNumber");

        if (validateRequest(request)) {

            com.authy.api.User authyUser = authyClient.getUsers().createUser(email, phoneNumber, countryCode);

            // Create user remotely
            if (authyUser.isOk()) {
                int authyUserId = authyUser.getId();
                // Create user locally
                User user = usersRepository.create(new User(name, email, password, countryCode, phoneNumber, authyUserId));

                // Request SMS authentication
                authyClient.getUsers().requestSms(authyUserId);

                sessionManager.partialLogIn(request, user.getId());
                response.sendRedirect("/verify-code");
            }
        } else {
            preserveStatusRequest(request, name, email, countryCode, phoneNumber);
            request.getRequestDispatcher("/registration.jsp").forward(request, response);
        }
    }

    private boolean validateRequest(HttpServletRequest request) {
        RequestParametersValidator validator = new RequestParametersValidator(request);

        return validator.validatePresence("name", "email", "password", "countryCode", "phoneNumber")
                && validator.validateEmail("email");
    }

    private void preserveStatusRequest(
            HttpServletRequest request,
            String name,
            String email,
            String countryCode,
            String phoneNumber) {
        request.setAttribute("name", name);
        request.setAttribute("email", email);
        request.setAttribute("countryCode", countryCode);
        request.setAttribute("phoneNumber", phoneNumber);
    }
}
package com.twilio.verification.servlet;

import com.authy.AuthyApiClient;
import com.twilio.verification.lib.RequestParametersValidator;
import com.twilio.verification.lib.SessionManager;
import com.twilio.verification.model.User;
import com.twilio.verification.repository.UsersRepository;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class RegistrationServlet extends HttpServlet {

    private final UsersRepository usersRepository;
    private final SessionManager sessionManager;
    private final AuthyApiClient authyClient;

    @SuppressWarnings("unused")
    public RegistrationServlet() {
       this(
               new UsersRepository(),
               new SessionManager(),
               new AuthyApiClient(System.getenv("AUTHY_API_KEY"))
       );
    }

    public RegistrationServlet(UsersRepository usersRepository, SessionManager sessionManager, AuthyApiClient authyClient) {
        this.usersRepository = usersRepository;
        this.sessionManager = sessionManager;
        this.authyClient = authyClient;
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        String name = request.getParameter("name");
        String email = request.getParameter("email");
        String password = request.getParameter("password");
        String countryCode = request.getParameter("countryCode");
        String phoneNumber = request.getParameter("phoneNumber");

        if (validateRequest(request)) {

            com.authy.api.User authyUser = authyClient.getUsers().createUser(email, phoneNumber, countryCode);

            // Create user remotely
            if (authyUser.isOk()) {
                int authyUserId = authyUser.getId();
                // Create user locally
                User user = usersRepository.create(new User(name, email, password, countryCode, phoneNumber, authyUserId));

                // Request SMS authentication
                authyClient.getUsers().requestSms(authyUserId);

                sessionManager.partialLogIn(request, user.getId());
                response.sendRedirect("/verify-code");
            }
        } else {
            preserveStatusRequest(request, name, email, countryCode, phoneNumber);
            request.getRequestDispatcher("/registration.jsp").forward(request, response);
        }
    }

    private boolean validateRequest(HttpServletRequest request) {
        RequestParametersValidator validator = new RequestParametersValidator(request);

        return validator.validatePresence("name", "email", "password", "countryCode", "phoneNumber")
                && validator.validateEmail("email");
    }

    private void preserveStatusRequest(
            HttpServletRequest request,
            String name,
            String email,
            String countryCode,
            String phoneNumber) {
        request.setAttribute("name", name);
        request.setAttribute("email", email);
        request.setAttribute("countryCode", countryCode);
        request.setAttribute("phoneNumber", phoneNumber);
    }
}
package com.twilio.verification.servlet;

import com.authy.AuthyApiClient;
import com.authy.api.Token;
import com.twilio.verification.lib.RequestParametersValidator;
import com.twilio.verification.lib.Sender;
import com.twilio.verification.lib.SessionManager;
import com.twilio.verification.model.User;
import com.twilio.verification.repository.UsersRepository;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class VerifyCodeServlet extends HttpServlet {

    private final UsersRepository usersRepository;
    private final SessionManager sessionManager;
    private final AuthyApiClient authyClient;
    private final Sender sender;

    @SuppressWarnings("unused")
    public VerifyCodeServlet() {
        this(
                new UsersRepository(),
                new SessionManager(),
                new AuthyApiClient(System.getenv("AUTHY_API_KEY")),
                new Sender()
        );
    }

    public VerifyCodeServlet(
            UsersRepository usersRepository, SessionManager sessionManager, AuthyApiClient authyClient, Sender sender) {
        this.usersRepository = usersRepository;
        this.authyClient = authyClient;
        this.sessionManager = sessionManager;
        this.sender = sender;
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        request.getRequestDispatcher("/verifyCode.jsp").forward(request, response);
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        String code = request.getParameter("code");

        if (validateRequest(request)) {
            int userId = sessionManager.getLoggedUserId(request);
            User user = usersRepository.find(userId);

            Token token = authyClient.getTokens().verify(user.getAuthyId(), code);
            if (token.isOk()) {
                user.setVerified(true);
                usersRepository.update(user);
                // Send SMS confirmation
                sender.send(user.getFullPhoneNumber(), "You did it! Sign up complete :3");

                sessionManager.logIn(request, userId);
                response.sendRedirect("/account");
            } else {
                request.setAttribute("codeError", "Incorrect code, please try again");
                request.getRequestDispatcher("/verifyCode.jsp").forward(request, response);
            }
        } else {
            request.getRequestDispatcher("/verifyCode.jsp").forward(request, response);
        }
    }


    private boolean validateRequest(HttpServletRequest request) {
        RequestParametersValidator validator = new RequestParametersValidator(request);

        return validator.validatePresence("code");
    }
}
package com.twilio.verification.servlet;

import com.authy.AuthyApiClient;
import com.twilio.verification.lib.SessionManager;
import com.twilio.verification.model.User;
import com.twilio.verification.repository.UsersRepository;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class ResendTokenServlet extends HttpServlet {

    private final UsersRepository usersRepository;
    private final SessionManager sessionManager;
    private final AuthyApiClient authyClient;

    @SuppressWarnings("unused")
    public ResendTokenServlet() {
        this(
                new UsersRepository(),
                new SessionManager(),
                new AuthyApiClient(System.getenv("AUTHY_API_KEY"))
        );
    }

    public ResendTokenServlet(
            UsersRepository usersRepository, SessionManager sessionManager, AuthyApiClient authyClient) {
        this.usersRepository = usersRepository;
        this.sessionManager = sessionManager;
        this.authyClient = authyClient;
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        int userId = sessionManager.getLoggedUserId(request);
        User user = usersRepository.find(userId);

        // Request SMS authentication
        authyClient.getUsers().requestSms(user.getAuthyId());

        response.sendRedirect("/verify-token");
    }
}
package com.twilio.verification.lib;

import com.twilio.http.TwilioRestClient;
import com.twilio.rest.api.v2010.account.MessageCreator;
import com.twilio.type.PhoneNumber;
import com.twilio.verification.lib.Twilio.Config;

public class Sender {

    private final TwilioRestClient client;

    public Sender() {
        client = new TwilioRestClient.Builder(Config.getAccountSid(), Config.getAuthToken()).build();
    }

    public Sender(TwilioRestClient client) {
        this.client = client;
    }

    public void send(String to, String message) {
        new MessageCreator(
                new PhoneNumber(to),
                new PhoneNumber(Config.getPhoneNumber()),
                message
        ).create(client);
    }

}