Building authentication into an application is a tedious task. However, making sure this authentication is bulletproof is even harder. As developers, it’s beyond our control what the users do with their passwords, how they protect them, who they give them to, or how they generate them, for that matter. All we can do is get close enough to ensure that the authentication request was made by our user and not someone else. OTPs certainly help with that, and services like Twilio Verify help us to generate secured OTPs quickly without having to bother about the logic.
What’s Wrong With Passwords?
There are several problems faced by developers when using password-based authentication alone since it has the following issues:
- Users might forget passwords and write them down (making them steal-able);
- Users might reuse passwords across services (making all their accounts vulnerable to one data breach);
- Users might use easy passwords for remembrance purposes, making them relatively easy to hack.
Enter OTPs
A one-time password (OTP) is a password or PIN valid for only one login session or transaction. Once it can only be used once, I’m sure you can already see how the usage of OTPs makes up for the shortcomings of traditional passwords.
OTPs add an extra layer of security to applications, which the traditional password authentication system cannot provide. OTPs are randomly generated and are only valid for a short period of time, avoiding several deficiencies that are associated with traditional password-based authentication.
OTPs can be used to substitute traditional passwords or reinforce the passwords using the two-factor authentication (2FA) approach. Basically, OTPs can be used wherever you need to ensure a user’s identity by relying on a personal communication medium owned by the user, such as phone, mail, and so on.
This article is for developers who want to learn about:
- Learn how to build a Full-stack express.js application;
- Implement authentication with passport.js;
- How to Twilio Verify for phone-based user verification.
To achieve these objectives, we’ll build a full-stack application using node.js, express.js, EJS with authentication done using passport.js and protected routes that require OTPs for access.
Note: I’d like to mention that we’ll be using some 3rd-party (built by other people) packages in our application. This is a common practice, as there is no need to re-invent the wheel. Could we create our own node server? Yes, of course. However, that time could be better spent on building logic specifically for our application.
Table Of Contents
- Basic overview of Authentication in web applications;
- Building an Express server;
- Integrating MongoDB into our Express application;
- Building the views of our application using EJS templating engine;
- Basic authentication using a passport number;
- Using Twilio Verify to protect routes.
Requirements
- Node.js
- MongoDB
- A text editor (e.g. VS Code)
- A web browser (e.g. Chrome, Firefox)
- An understanding of HTML, CSS, JavaScript, Express.js
Although we will be building the whole application from scratch, here’s the GitHub Repository for the project.
Basic Overview Of Authentication In Web Applications #
What Is Authentication?
Authentication is the whole process of identifying a user and verifying that a user has an account on our application.
Authentication is not to be confused with authorization. Although they work hand in hand, there’s no authorization without authentication.
That being said, let’s see what authorization is about.
What Is Authorization?
Authorization at its most basic, is all about user permissions — what a user is allowed to do in the application. In other words:
- Authentication: Who are you?
- Authorization: What can you do?
Authentication comes before Authorization.
There is no Authorization without Authentication.
The most common way of authenticating a user is via username
and password
.
Setting Up Our Application
To set up our application, we create our project directory:
Building An Express Server
We’ll be using Express.js to build our server.
Why Do We Need Express?
Building a server in Node
could be tedious, but frameworks make things easier for us.
Express
is the most popular Node
web framework. It enables us to:
- Write handlers for requests with different
HTTP
verbs at differentURL
paths (routes); - Integrate with
view
rendering engines in order to generate responses by inserting data into templates; - Set common web application settings — like the
port
used for connecting, and the location of templates used for rendering the response; - Add additional request processing
middleware
at any point within the request handling pipeline.
In addition to all of these, developers have created compatible middleware packages to address almost any web development problem.
In our authWithTwilioVerify
directory, we initialize a package.json
that holds information concerning our project.
In Keeping with the Model View Controller(MVC) architecture, we have to create the following folders in our authWithTwilioVerify
directory:
Many developers have different reasons for using the MVC architecture, but for me personally, it’s because:
- It encourages separation of concerns;
- It helps in writing clean code;
- It provides a structure to my codebase, and since other developers use it, understanding the codebase won’t be an issue.
Controllers
directory houses the controllers;Models
directory holds our database models;Public
directory holds our static assets e.g. CSS files, images e.t.c.;Views
directory contains the pages that will be rendered in the browser;Routes
directory holds the different routes of our application;Config
directory holds information that is peculiar to our application.
We need to install the following packages to build our app:
nodemon
automatically restarts our server when we make changes;express
gives us a nice interface to handle routes;express-session
allows us to handle sessions easily in our express application;connect-flash
allows us to display messages to our users.
Add the script below in the package.json
file to start our server using nodemon
.
Create an index.js
file and add the necessary packages for our app.
We have to require
the installed packages into our index.js
file so that our application runs well then we configure the packages as follows:
Let’s break down the segment of code above.
Apart from the require
statements, we make use of the app.use()
function — which enables us to use application level middleware
.
Middleware functions are functions that have access to the request object, response object, and the next middleware function in the application’s request and response cycle.
Most packages that have access to our application’s state (request and response objects) and can alter those states are usually used as middleware. Basically, middleware adds functionality to our express application.
It’s
like handing the application state over to the middleware function,
saying here’s the state, do what you want with it, and call the next()
function to the next middleware.
Finally, we tell our application server to listen for requests to port 3000.
Then in the terminal run:
If you see app is running on port 3000
in the terminal, that means our application is running properly.
Integrating MongoDB Into Our Express Application
MongoDB stores data as documents. These documents are stored in MongoDB in JSON (JavaScript Object Notation) format. Since we’re using Node.js, it’s pretty easy to convert data stored in MongoDB to JavaScript objects and manipulate them.
To install MongoDB in your machine visit the MongoDB documentation.
In order to integrate MongoDB into our express application, we’ll be using Mongoose. Mongoose is an ODM(which is the acronym for object data mapper
).
Basically, Mongoose makes it easier for us to use MongoDB in our application by creating a wrapper around Native MongoDB functions.
In index.js
, it requires mongoose
:
The mongoose.connect()
function allows us to set up a connection to our MongoDB database using the connection string.
The format for the connection string is mongodb://localhost:27017/{database_name}
.
mongodb://localhost:27017/
is MongoDB’s default host, and the database_name
is whatever we wish to call our database.
Mongoose connects to the database called database_name
. If it doesn’t exist, it creates a database with database_name
and connects to it.
Mongoose.connect()
is a promise, so it’s always a good practice to log a message to the console in the then()
and catch()
methods to let us know if the connection was successful or not.
We create our user model in our models
directory:
user.js
requires mongoose and create our user schema:
A schema
provides a structure for our data. It shows how data should be
structured in the database. Following the code segment above, we specify
that a user object in the database should always have name
, username
, password
, phonenumber
, and email
.
Since those fields are required, if the data pushed into the database
lack any of these required fields, mongoose throws an error.
Though
you could create schemaless data in MongoDB, it is not advisable to do
so — trust me, your data would be a mess. Besides, schemas are great.
They allow you to dictate the structure and form of objects in your
database — who wouldn’t want such powers?
Encrypting Passwords
Warning: never store users’ passwords as plain text in your database.
Always encrypt the passwords before pushing them to the database.
The
reason we need to encrypt user passwords is this: in case someone
somehow gains access to our database, we have some assurance that the
user passwords are safe — because all this person would see would be a hash
. This provides some level of security assurance, but a sophisticated hacker may still be able to crack this hash
if they have the right tools. Hence the need for OTPs, but let’s focus on encrypting user passwords for now.
bcryptjs
provides a way to encrypt and decrypt users’ passwords.
In models/user.js
, it requires bcryptjs
:
The code above does a couple of things. Let’s see them.
The userSchema.pre('save', callback)
is a mongoose hook
that allows us to manipulate data before saving it to the database. In the callback function
, we return a promise which tries to hash(encrypt) bcrypt.hash()
the password using the bcrypt.genSalt()
we generated. If an error occurs during this hashing
, we reject
or we resolve
by setting this.password = hash
. this.password
being the userSchema password
.
Next, mongoose
provides a way for us to append methods to schemas using the schema.methods.method_name
. In our case, we’re creating a method that allows us to validate user passwords. Assigning a function value to *userSchema.methods.validPassword*
, we can easily use bcryptjs compare method bcryprt.compare()
to check if the password is correct or not.
bcrypt.compare()
takes two arguments and a callback. The password
is the password that is passed when calling the function, while this.password
is the one from userSchema.
I prefer this method of validating users’ password because it’s like a property on the user object. One could easily call User.validPassword(password)
and get true or false as a response.
Hopefully, you can see the usefulness of mongoose. Besides creating a schema that gives structure to our database objects, it also provides nice methods for manipulating those objects — that would have been otherwise somewhat though using native MongoDB alone.
Express is to Node, as Mongoose is to MongoDB.
Building The Views Of Our Application Using EJS Templating Engine
Before we start building the views of our application, let’s take a look at the front-end architecture of our application.
Front-end Architecture
EJS
is a templating engine that works with Express directly. There’s no need for a different front-end framework. EJS
makes the passing of data very easy. It also makes it easier to keep
track of what’s going on since there is no switching from back-end to
front-end.
We’ll have a views
directory, which will contain the files to be rendered in the browser. All we have to do is call the res.render()
method from our controller. For example, if we wish to render the login page, it’s as simple as res.render('login')
. We could also pass data to the views by adding an additional argument — which is an object to the render()
method, like res.render('dashboard', { user })
. Then, in our view
, we could display the data with the evaluation syntax <%= %>
. Everything with this tag is evaluated — for instance, <%= user.username %>
displays the value of the username property of the user object. Aside from the evaluation syntax, EJS
also provides a control syntax (<% %>
), which allows us to write program control statements such as conditionals, loops, and so forth.
Basically, EJS
allows us to embed JavaScript in our HTML.
In index.js
, it requires express-ejs-layouts
:
Then:
In views/layout.ejs
,
The layout.ejs
file serves like an index.html
file, where we can include all our scripts and stylesheets. Then, in the div
with classes ui container
, we render the body
— which is the rest of our application views.
We’ll be using semantic UI as our CSS framework.
Building The Partials
Partials are where we store re-usable code, so that we don’t have to rewrite them every single time. All we do is include them wherever they are needed.
You could think of partials like components in front-end frameworks: they encourage DRY code, and also code re-usability. Think of partials as an earlier version of components.
For example, we want partials for our menu, so that we do not have to write code for it every single time we need the menu on our page.
We’ll create two files in the /views/partials
folder:
In menu.ejs
,
In message.ejs
,
Building The Dashboard Page
In our views folder, we create a dashboard.ejs
file:
Here, we include the menu partials
so we have the menu on the page.
Building The Error Page
In our views folder, we create an error.ejs
file:
Building The Home Page
In our views folder, we create a home.ejs
file:
Building The Login Page
In our views folder, we create a login.ejs
file:
Building The Verify Page
In our views folder, we create a login.ejs
file:
Here, we provide a form for users to enter the verification code that will be sent to them.
Building The Sign Up Page
We
need to get the user’s mobile number, and we all know that country
codes differ from country to country. Therefore, we’ll use the [intl-tel-input](https://intl-tel-input.com/)
to help us with the country codes and validation of phone numbers.
In our public folder, we create a css
directory, js
directory and img
directory:
We copy the
intlTelInput.css
file fromnode_modules\intl-tel-input\build\css\
file into ourpublic/css
directory.We copy both the
intlTelInput.js
andutils.js
fromnode_modules\intl-tel-input\build\js\
folder into ourpublic/js
directory.We copy both the
flags.png
andflags@2x.png
fromnode_modules\intl-tel-input\build\img\
folder into ourpublic/img
directory.
We create an app.css in our public/css
folder:
In app.css
, add the styles below:
Finally, we create a signup.ejs
file in our views folder:
Basic Authentication With Passport
Building authentication into an application can be really complex and time-draining, so we need a package to help us with that.
Remember: do not re-invent the wheel, except if your application has a specific need.
passport
is a package that helps out with authentication in our express application.
passport
has many strategies we could use, but we’ll be using the local-strategy
— which basically does username and password authentication
.
One advantage of using passport is that, since it has many strategies, we can easily extend our application to use its other strategies.
In index.js
we add the following code:
We’re adding some application level middleware
to our index.js
file — which tells the application to use the passport.initialize()
and the passport.session()
middleware.
Passport.initialize()
initializes passport
, while the passport.session()
middleware let’s passport
know that we’re using session
for authentication.
Do not worry much about the localAuth()
function. That takes the passport
object as an argument, and we’ll create the function just below.
Next, we create a config
folder and create the needed files:
In passportLogic.js
,
Let’s understand what is going on in the code above.
Apart from the require statements, we create the localAuth()
function, which will be exported from the file. In the function, we call the passport.use()
function that uses the LocalStrategy()
for username
and password
based authentication.
We specify that our usernameField
should be email
. Then, we find a user that has that particular email
— if none exists, then we return an error in the done()
function. However, if a user exists, we check if the password is valid using the validPassword
method on the User
object. If it’s invalid, we return an error. Finally, if everything is successful, we return the user
in done(null, user)
.
passport.serializeUser()
and passport.deserializeUser()
helps in order to support login sessions. Passport will serialize and deserialize user
instances to and from the session.
In middleware.js
,
Our middleware file contains two(2) route level middleware
, which will be used later in our routes.
Route-level middleware is used by our routes, mostly for route protection and validation, such as authorization, while application level middleware is used by the whole application.
isLoggedIn
and notLoggedIn
are route level middleware
that checks if a user is logged in. We use these middlewares to block
access to routes that we want to make accessible to logged-in users.
Building The Sign-Up Controllers #
In signUpController.js
, we:
- Check for users’ credentials;
- Check if a user with that detail(email or phone-number) exists in our database;
- Create an error if the user exists;
- Finally, if such a user does not exist, we create a new user with the given details and redirect to the
login
page.
In loginController.js
,
- We use the
passport.authenticate()
method with the local scope (email and password) to check if the user exists; - If the user doesn’t exist, we give out an error message and redirect the user to the same route;
- if the user exists, we log the user in using the
req.logIn
method, send them a verification using thesendVerification()
function, then redirect them to theverify
route.
Right now, sendVerification()
doesn’t exactly work. That’s because we’ve not written the function, so we need Twilio
for that. Let’s install Twilio and get started.
Using Twilio Verify To Protect Routes
In order to use Twilio Verify, you:
- Head over to
https://www.twilio.com/
; - Create an account with Twilio;
- Login to your dashboard;
- Select create a new project;
- Follow the steps to create a new project.
To install the Twilio SDK
for node.js:
Next, we need to install dotenv
to help us with environment variables
.
We create a file in the root of our project and name it .env
. This file is where we keep our credentials
, so we don’t push it to git. In order to do that, we create a .gitignore
file in the root of our project, and add the following lines to the file:
This tells git to ignore both the node_modules
folder and the .env
file.
To get our Twilio account credentials, we login into our Twilio console, and copy our ACCOUNT SID
and AUTH TOKEN
. Then, we click on get trial number
and Twilio generates a trial number for us, click accept number
. Now from the console copy, we copy our trial number.
In .env
,
TWILIO_ACCOUNT_SID = <YOUR_ACCOUNT_SID>
TWILIO_AUTH_TOKEN = <YOUR_AUTH_TOKEN>
TWILIO_PHONE_NUMBER = <TOUR_TWILIO_NUMBER>
Don’t forget to replace <YOUR_ACCOUNT_SID>
, <YOUR_AUTH_TOKEN>
, and <TOUR_TWILIO_NUMBER>
with your actual credentials.
We create a file named twilioLogic.js
in the config
directory:
In twilioLogic.js
,
In the code snippet above, we create a new verify
service.
Run:
The string that gets logged to our screen is our TWILIO_VERIFICATION_SID
— we copy that string.
In .env
, add the line TWILIO_VERIFICATION_SID = <YOUR_TWILIO_VERIFICATION_SID>
.
In config/twilioLogic.js
, we remove the createService()
line, since we need to create the verify
service only once. Then, we add the following lines of code:
sendVerification
is an asynchronous function that returns a promise that sends a verification OTP to the number provided using the sms
channel.
checkVerification
is also an asynchronous function that returns a promise that checks the status of the verification. It checks if the OTP
provided by the users is the same OTP
that was sent to them.
In config/middleware.js
, add the following:
We’ve created two more route level middleware
, which will be used later in our routes.
isVerified
and notVerified
check if a user is verified. We use these middlewares to block access
to routes that we want to make accessible to only verified users.
In verifyController.js
,
resendCode()
re-sends the verification code to the user.
verifyUser
uses the checkVerification
function created in the previous section. If the status is approved
, we set the verified
value on req.session
to true.
req.session
just provides a nice way to access the current session. This is done by
express-session, which adds the session object to our request object.
Hence the reason I said that most application level middleware do affect our applications state (request and response objects)
Building The User Routes #
Basically, our application is going to have the following routes:
/user/login
: for user login;/user/signup
: for user registration;/user/logout
: for log out;/user/resend
: to resend a verification code;/user/verify
: for input of verification code;/user/dashboard
: the route that is protected usingTwilio Verify
.
In routes/user.js
, it requires the needed packages:
We’re creating our routes in the piece of code above, let’s see what’s going on here:
router.route()
specifies the route. If we specify router.route('/login')
, we target the login
route. .all([middleware])
allows us specify that all request to that route should use those middleware
.
The router.route('/login').all([middleware]).get(getController).post(postController)
syntax is an alternative to the one most developers are used to.
It does the same thing as router.get('/login', [middleware], getController)
and router.post('/login, [middleware], postController)
.
The syntax used in our code is nice because it makes our code very DRY — and it’s easier to keep up with what’s going on in our file.
Now, if we run our application by typing the command below in our terminal:
Our full-stack express application should be up and running.
Conclusion
What we have done in this tutorial was to:
- Build out an express application;
- Add passport for authentication with sessions;
- Use Twilio Verify for route protection.
I surely hope that after this tutorial, you are ready to rethink your password-based authentication and add that extra layer of security to your application.
What you could do next:
- Try to explore passport, using JWT for authentication;
- Integrate what you’ve learned here into another application;
- Explore more Twilio products. They provide services that make development easier(Verify is just one of the many services).
No comments:
Post a Comment