API One Time Password (O.T.P.) Implementation Using Africa's Talking Short...

One Time Password (O.T.P.) Implementation Using Africa’s Talking Short Code API in Django

-

- Advertisment -

Introduction

This article explores the implementation of One Time Passwords (O.T.P.) when users log into a web app. A randomly generated code is sent to the user’s phone, that’s then inputted upon request to authenticate the user. This authentication method can be used when a developer wants a more secure Log In process e.g. banking or payment processing web apps.

Intended audience: Who the article is for

This article targets python/Django developers who would want to build a web app that incorporates O.T.P. in its log in process and would want to know how to integrate with Africa’s Talking SMS short code to support this functionality.

Case Study: What the article is going to cover

The web application to be designed will have a log in page for users to log in after which they are then redirected to the O.T.P. page while a text message is sent to Africa’s Talking phone simulator.

This web app will also have other pages only accessible to logged in users, and the article/project will showcase how to prevent users from bypassing the O.T.P / Log In page when accessing pages requiring log in.

This technology can be used by developers who would want some added security on their platform.

The application will be built using python programming language in Django Framework.

Requirements:

  1. Some knowledge of Python and Django
  2. Africa’s Talking Account create one HERE if you don’t have one.
  3. Africa’s Talking API Key
  4. Africa’s Talking SMS Short Code
  5. Python3 in your computer

Structure of the Article

Code sections of the article are first preceded by a brief description of what the codes are intended to do, then the code snippets in Github and finally an in-depth explanation of the logic or pseudocode behind the code

Acquiring Africa’s Talking Credentials

  1. Head over to Africa’s talking and create an account or login if you already have one.
  2. Using the navigation bar on the left side
  3. Select SMS, then Select “Shortcodes“
  4. Inside “Shortcodes” menu click “Create Shortcode”
  5. Click “My Shortcodes” to verify your shortcode has been created
  6. On the same navigation bar select the “Settings” menu
  7. Inside “Settings” drop-down menu, click on API Key to get your API Key
  8. Save the SMS Shortcode and API key as you will need them later on

Creating a Django Project

  1. From your terminal navigate to the folder/location your project is to reside
  2. We will create a Django project called “django_otp_login”, type the command: django-admin startproject django_otp_login
  3. From the terminal navigate into the created project folder, where you will create and then activate your project’s virtual environment
  4. Type “python3 -m venv venv” in the terminal to create the virtual environment
  5. In windows, type “venv\Scripts\activate” in the terminal
  6. In Mac/Linux, type ”source venv/bin/activate” in the terminal
  7. After your virtual environment has been activated, run the code below in the terminal to install the following python packages
    • “pip install Django” : django python package
    • “pip install requests” : python package used in managing HTTP requests
    • “pip install django-crispy-forms”  : to be used rendering bootstrap styles in HTML templates
  8. Create your first Django app by typing in the terminal the command: “python manage.py startapp users”
  9. Create a SQLite database that will used by the project by typing in the terminal the command: “python manage.py makemigrations”
  10. Apply database changes by typing in the terminal the command: “python manage.py migrate”
  11. Start your server by typing on the terminal the command: “python manage.py runserver”
  12. If the server starts successfully there should be a webpage up and running on the location: http://127.0.0.1:8000
  13. While in the terminal type Ctrl+C to stop the server
  14. Everything from now on will be performed inside this python activated environment
  15. We are stopping the server so that we can create the database tables first and then apply the changes before restarting the server

Creating Project CSS File

  1. Open the Django project folder in your code editor
  2. Open the “users” app folder
  3. In the “users” app folder, create a folder labelled “static”
  4. Inside the created “static” folder create another folder labelled “users”
  5. Inside the “users” folder just created inside the “static” folder, create a CSS file labelled “main.css”
  6. Copy the code below into the “main.css” file

Creating Database Tables

  1. Open your Django project folder in your code editor
  2. We will start by creating database tables related to the “users” app we created, which are:
    • OTP: This table will hold the OTP codes generated, it will have the following fields, otp_code {it will hold the randomly generated code}, user {it will hold the user who logged in and initiated the generation of the O.T.P. code} and date_created (date the OTP code was created)
    • Client: This table will hold the name of the registered users and their details, it will inherit from the User table its fields and also add a new field called phone {to hold the users phone number}
  3. To create the above “users” tables, in your project folder navigate into the “users” folder and open a file labeled “models.py” and paste the code below:

OTP Table Logic

  1. OTP: This table will hold the OTP codes generated, it will have the following fields, otp_code –This column will hold the randomly generated code, it will allow for null values by setting the null property to true and have a maximum length of six, which the length of the code to be generated

user – This column will hold the user who logged in and initiated the generation of the O.T.P. code, the column will have a relationship with the User model, which is why its labeled as a ForeginKey in the OTP table, will also set the table record to me deleted incase a user is delete from the system, by setting the on_delete=models.CASCADE

date_create – The date the OTP code was created, it will be a date time field that will hold the exact date and time the record was made and it will take a default value of the current timestamp it the record was created

The table class will also inherit a method called __str__ from its super class, this method returns the string version of object instantiated by this class. If a record is saved in the DB it is saved as an OTP object, so to make the object readable the object is cast into a string to get the string version of it. So when an OTP data object from the DB is cast into a string, it will return the object’s otp_code

Client Table Logic

  • Client: This table will hold the name of the registered users and their details, it will inherit from the User table its fields and also add a new field called phone to hold the users phone number}

The reason we are inheriting from the User table is because the User table does not come with a Phone Number field, hence this filed has to be added to it, Django allows us to extend the fields and functionality of another table by inheriting it and adding our own fields and methods, also known as Object Oriented Programming.

Apart from the Client table adding the phone field, it overrides the method __str__ from its super class and returns the user’s full name by calling the superclass’ get_full_name method. This table also creates its own method called full_name that returns the users’ fullname, but it then places a method decorator on the method so that this method is accessed as an object’s property “otp_object.full_name” instead of an executable method “otp_object.full_name()”

Africa’s Talking API Integration

  1. You first start by creating an Africa’s Talking API Key
  2. Create an Africa’s Talking SMS shortcode
  3. Open the “users” app folder
  4. Create a python filed labelled “send_message.py”
  5. Paste the code below

Send Message Logic

You will need to import the requests library/module, this is a HTTP library used to send POST, GET, PUT etc. requests to APIs or websites to retrieve information.

We will also define a send method that takes two parameters, the phone number and message to send, we are providing the message with a default value here. From Africa’s Talking documentation the Short Code API expects a Payload and Header.

The Payload takes:

  • Username: Since we are running a test, we will use the sandbox username
  • To: the phone number we are sending the message to, I am using an “F-String”, this is a python string syntax that allows one to include python variables in the string
  • From: This is the short code the message is to be sent from, assuming you created one in Africa’s Talking developer page

The header takes two standard parameters “Accept” and “Content-Type”, the parameter that will need to be edited is the “apiKey”, this is the API key that was generated on your developer dashboard Once the request is executed with the payload and headers, it returns a JSON response, from this response we will retrieve the data inside the JSON object “SMSMessageData”, we will then retrieve the data inside the JSON Object “Recipients” which is a list, we then access the first data of the list which contains a JSON Object “status”, that informs us if the message was sent successfully, which is what we return once the send method is executed.

  1. Enter your short code and A.P.I. key in the appropriate fields

OTP Code Generator Implementation

  1. Open the “users” app folder
  2. Create a python filed labeled “generate_code.py”
  3. Paste the code below

Code Generator Logic

We will import the string and random modules, for manipulating strings and creating random choices respectively. The defined method “get_code” returns the random string, we first set the length of the random string. The String will be a concatenation of uppercase letters and numbers that will all total to six and be joined together to form a single six character string

Configure Project Settings

  1. In order to apply the database changes we just made we need to register the apps we have created in the projects settings. Here is how to do so:
  2. Open your Django project folder: “django_otp_login”
  3. Locate a folder with a similar name to your Django project folder, this folder is in the same directory as your “users” app folder
  4. Inside this folder is a python file labeled “settings.py”
  5. Open the “settings.py” file and locate the variable INSTALLED_APPS
  6. The variable INSTALLED_APPS is a list where you will insert the apps we just created, we have two apps to register:
  • users – This is the app we created to handle user log ins, sign ups etc.
  • crispy_forms – This is an app from the django-crispy-forms python package that is used to style our html templates, we have to register it so as to use it.
  1. Insert the code below inside the list:

Apply Database Changes

  1. In your terminal ensure you have activate your project’s virtual environment
  2. While in your projects activated virtual environment in your terminal
  3. Create database changes to be made by typing in the terminal the command: python manage.py makemigrations
  4. Apply database changes by typing in the terminal the command: python manage.py migrate

Creating “Users” HTML Templates

  1. On these HTML templates is where the different users data will be displayed
  2. We will start by creating HTML templates related to the “users” app we created, which are:
    • login.html – The log in page
    • logout.html – The log out page
    • otp.html – This is the page that will display a form for the user to enter the O.T.P. password sent via text message
    • index.html – The default home page for the web app with brief instructions on how the web app works
    • base.html – This is the page that will be inherited/extended by all other HTML template pages
    • about.html – The web app’s about page
    • account_created.html – The page a user is redirected to after a successful sign up
    • profile.html – This page will be used to display the user’s profile info
  3. To create the above “users” HTML templates do the following:
    • In your project folder navigate into the “users” folder
    • Create a folder labeled “templates”
    • Inside the “templates” folder create another folder and label it “users”
    • Inside the “users” folder you have just created inside the “templates” folder
    • Create the following blank HTML pages; login.html, logout.html, otp.html, index.html, base.html, about.html, account_created.html and profile.html.
  4. Below is a screenshot of the “users” directory tree:
  1. Below are the HTML codes to be placed on each HTML page

Create User Profile Forms

These are the forms used to render user data onto their profile pages and the OTP confirmation page

  1. Open the “users” app folder
  2. Locate/create a python filed labeled “forms.py”
  3. Paste the code below

User Python Forms Logic

We start by importing Django forms and user database tables we created. We create an OTPForm class that inherits from the “forms.ModelForm” class, this class transforms our class into a form that interacts with a specific model or database table, in this case the “OTPForm” class will work with the OTP model.

The form will have one field called otp_code, which accepts a string with a maximum length of 6 characters, it overrides the inner class “Meta” where you link it with the model to be associated with, OTP, and the fields to interact with “otp_code”

Client Update Form Logic This class inherits from the “forms.ModelForm” class, making it a model form. It is set to interact with the model or database table Client and fields first_name, last_name, username, email and phone. We will make the email and phone filed mandatory by instantiating them inside the class as variables.

Creating your business logic for Users App

These are the functions that will be executed by the web app URLs in order to return a HTML page. They are usually placed in a file called “views.py”. Do the following to edit this file:

  1. Open the “users” app folder
  2. Locate a python filed labeled “views.py”
  3. Paste the code below

Views Code Logic

We start by importing the following methods:

  • Render – This method is used to return a HTML page to the user
  • Redirect – This method is used to redirect a user to a different page
  • CreateView – This is a Django built in class that can be used to create a database table entry by associating it with another class
  • UpdateView– This is a Django built in class that can be used to update a database table entry by associating it with another class
  • User – The built in django database table or model called “User”
  • Client and OTP – The two database tables or models we created
  • Messages – This is a built in Django method that allows one to send messages back to the template they are rendering
  • TPForm, ClientUpdateForm – The two forms or model forms we created
  • Reverse- a built in Django method that accepts the name of a URL and returns its url path
  • Send and get_code – the methods we created to send messages and generate a random six character code
  • login – a built in Django method that logs in a user into the web app
  • logout – a built in Django method that logs out a user from the web app

We now build the views/functions or methods below:

  • Home – This is a method or function view that accepts a web request and returns back the index HTML page render
  • About – This is a method or function view that accepts a web request and first checks whether the user has logged in, if so return back the about HTML page, if the user has not logged in redirect them back to the log in page
  • Account Create – This is a method or function view that accepts a web request and returns back a page informing the user that their account has been successfully registered
  • Client Create View – This is a class based view or a class that inherits its functionalities from another class view, in this case django’s built in “CreateView” class. In this class we have to specify the model or database table the class will work with which is the “Client”, the fields it’s to work with which are ‘first_name’, ‘last_name’, ‘username’, ‘phone’, the template that will render the data/form.

The class will also override its super class method “get_context_data”, what this method does, is that it allow us to get access to the data that will be passed to the template, before it’s sent to the template for rendering, the data is passed as a context object. After getting access to the context we add a new object variable with a value in it and return the context back.

We also override the form valid method that validates the form before saving the form data, we do so in order to save the form manually, which returns the saved user for us to set a password for and save the new password.

The final method we override is the “get_success_url” method which is supposed to return the URL the user is to be redirected to after they are created successfully

  • Otp – This is the view that is to display the OTP form. When a user logs in they are redirected to this view via a GET request, this view is also executed if the request is a POST which happens if a user submits the form that’s on this view.

If the request is a POST,

  1. Generate an OTP form with the POST data,
  2. Check if the form is valid, meaning all the fields are filled in,
  3. Get the OTP code entered,
  4. Get the user id passed into the HTML page
  5. Using the OTP code provided and the user id, query the OTP table to see if there exists a record for the specified user with the specified OTP code,
  6. If the records are more than zero
  7. User the user id to get the User from the table
  8. Log in this user (in the background) by calling the login in method
  9. Finally send a message to the HTML page

If the request is a GET,

  1. get the id of the user who logged in
  2. get the phone number of the logged in user, which is stored in the Client table
  3. invoke the get_code() method to generate and return a random string
  4. check if there is any OTP codes related to the currently logged in user in the OTP table
  5. if they are more than zero
  6. delete all the related OTP codes
  7. save the generated OTP code and related user in the OTP Table
  8. send the OTP code to the user’s mobile phone
  9. generate the OTP form to be filled in by the user
  10. log the user out (in the background), so that you can log them in once they enter correct OTP Password and this also prevents them from accessing pages they are not allowed to until they log in. Once you log the user out all their session data is erased, so we have to save the id of the user first and pass it to the template, which will then pass it to the view as POST data
  11. pass the OTP form and the user id into the HTML template as you won’t access once you logout a user

Creating the Users App URLs

These are the URLs that will be used by the user to navigate the “users” web app. They are usually placed in a file called “urls.py”. Do the following to create/edit this file:

  1. Open the “users” app folder
  2. Locate/create a python filed labeled “urls.py”
  3. Paste the code below

URLs Code Logic

We will import the views we created and the built in Django authentication view module. All URLs are placed inside a list that will contain the URL paths to the specific view, the path is a method that takes the URL name, this name will be used to access this URL inside the HTML templates, the view the URL associates with and the URL that will be displayed on the browser’s URL bar. You can include other URL paths inside a URL if they will be using part of the same URL path name, by using the include tag as it is displayed in the ‘login/’ URL

Configure Settings

Here we will perform some final settings configurations, which are:

  1. Configure the Crispy package/app to use bootstart4 in its styling
  2. Set the Log In URL
  3. Set the URL a user will be redirected to once they log in

To perform the above:

  1. Open your Django project folder
  2. Locate a folder with a similar name to your Django project folder, this folder is in the same directory as your “users” app folder
  3. Inside this folder is a python file labeled “settings.py”
  4. Open the “settings.py” file and paste code below at the very end of the file

Settings Code Logic

We will need to inform our Django web application to use bootstrap four when working with the python package called ‘csripy’

We also have to set the path to the location where media uploaded by the user will be stored and the URL name the location will be referred to by The log in URL and the page a user is redirected to after log in have to also be set

Project Tree

Below is a screenshot of how your project tree should look like, assuming the name of your Django project is “django_otp_login”:

Run the server

  1. cd/navigate into the “django_otp_login” Django project via the terminal
  2. Activate the virtual environment
  3. Start the server by typing the command: python manage.py runserver
  4. If there’s nothing wrong, the server should be up on http:127.0.0.1:8000

Testing the System

  1. Once the server is up
  2. Sign Up
  3. Enter phone number on the Sign Up Page
  4. Open the Africa’s Talking Simulator and enter the phone number used during sign up in the simulator
  5. Open the “Messages” app in the simulator
  6. Log into your web app using the created username and default password: 123456
  7. A message with the O.T.P. code should be displayed on the “Messages” app of Africa’s Talking Simulator
  8. Enter this code in the form of redirected O.T.P. page
  9. You should now be logged in and be able to view the about and profile pages

Conclusion

This application gives the user a different understanding in implementing security measures during logging in apart from other known methods. I also sheds light away from the use of SMS short codes for SMS campaigns and alert services and into security authentication.

Further improvements could be done on the project such as, allowing users to enter their password of choice during sign up instead of being provided a predefined password, another alternative would be for the system to provide a random password that is sent to the users email address and also allow a user to reset their password. Finally, you can find the code snippets in this @repo.

Quick Guide

If you just want to clone the project and get it up running, below is how to do so in minutes:

  1. Clone it:
    • git clone https://bitbucket.org/dans0l/django_otp_login.git
  2. Cd into it:
    • cd django_otp_login
  3. Create a venv:
    • python3 -m venv venv
  4. Activate venv:
    • Mac/Linux: source venv/bin/activate
    • Windows: venv\Scripts\activate
  5. Install the requirements:
    • pip install -r requirements.txt
  6. Create DB
    • python manage.py makemigrations
  7. Apply DB Changes:
    • python manage.py migrate
  8. Configure your Africa’s Talking SMS Shortcode and API Key:
    • Open the cloned project
    • Open the “users” folder
    • Open a python file labelled “send_message.py”
    • Enter the credentials in the file
  9. Run the server:
    • python manage.py runserver
  10. Navigate to the site: http://127.0.0.1:8000
  11. Follow the instructions on the home page to start using the site
  12. Navigate to Africa’s Talking Simulator to view Messages Sent

Please Let me know how your experience was, Thank you.

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Latest Posts

How To Use Gmail as an Email Client for your Django Web App

Introduction The project looks into how you can use Gmail as an Email Client for your website, this can be...

How To Build A Subscription App Using Django, HTML, CSS, Javascript and Stripe API.

What we are building We are going to build a subscription-based app where users have to create an account, pay...

One Time Password (O.T.P.) Implementation Using Africa’s Talking Short Code API in Django

Introduction This article explores the implementation of One Time Passwords (O.T.P.) when users log into a web app. A randomly...

Google Map API Setup & Geo-Coding with R

A step by step process from Google Map API creation, integration with R and visualization of spatial statistical data
- Advertisement -

Building Application using Node.js HTTPS Module and Africa’s Talking SMS API

Introduction For a long time, HTTP (Hypertext Transfer Protocol) was responsible for communication between a client application and a server...

Building an Exam Enrollment and Grade Notification System using Africa’s Talking SMS Shortcode API in Django

Introduction This article explores the application of SMS shortcodes to create transparency and improve the quality of education in learning...
- Advertisement -

You might also likeRELATED
Recommended to you