├── otp ├── __init__.py ├── asgi.py ├── wsgi.py ├── urls.py └── settings.py ├── verification ├── __init__.py ├── migrations │ ├── __init__.py │ └── 0001_initial.py ├── tests.py ├── apps.py ├── admin.py ├── urls.py ├── models.py └── views.py ├── README.md ├── manage.py └── .gitignore /otp/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /verification/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /verification/migrations/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /verification/tests.py: -------------------------------------------------------------------------------- 1 | from django.test import TestCase 2 | 3 | # Create your tests here. 4 | -------------------------------------------------------------------------------- /verification/apps.py: -------------------------------------------------------------------------------- 1 | from django.apps import AppConfig 2 | 3 | 4 | class VerificationConfig(AppConfig): 5 | name = 'verification' 6 | -------------------------------------------------------------------------------- /verification/admin.py: -------------------------------------------------------------------------------- 1 | from django.contrib import admin 2 | from .models import phoneModel 3 | 4 | # Register your models here. 5 | 6 | admin.site.register(phoneModel) 7 | -------------------------------------------------------------------------------- /verification/urls.py: -------------------------------------------------------------------------------- 1 | from django.urls import path, include 2 | from .views import getPhoneNumberRegistered, getPhoneNumberRegistered_TimeBased 3 | 4 | urlpatterns = [ 5 | path("/", getPhoneNumberRegistered.as_view(), name="OTP Gen"), 6 | path("time_based//", getPhoneNumberRegistered_TimeBased.as_view(), name="OTP Gen Time Based"), 7 | ] -------------------------------------------------------------------------------- /otp/asgi.py: -------------------------------------------------------------------------------- 1 | """ 2 | ASGI config for otp project. 3 | 4 | It exposes the ASGI callable as a module-level variable named ``application``. 5 | 6 | For more information on this file, see 7 | https://docs.djangoproject.com/en/3.0/howto/deployment/asgi/ 8 | """ 9 | 10 | import os 11 | 12 | from django.core.asgi import get_asgi_application 13 | 14 | os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'otp.settings') 15 | 16 | application = get_asgi_application() 17 | -------------------------------------------------------------------------------- /otp/wsgi.py: -------------------------------------------------------------------------------- 1 | """ 2 | WSGI config for otp project. 3 | 4 | It exposes the WSGI callable as a module-level variable named ``application``. 5 | 6 | For more information on this file, see 7 | https://docs.djangoproject.com/en/3.0/howto/deployment/wsgi/ 8 | """ 9 | 10 | import os 11 | 12 | from django.core.wsgi import get_wsgi_application 13 | 14 | os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'otp.settings') 15 | 16 | application = get_wsgi_application() 17 | -------------------------------------------------------------------------------- /verification/models.py: -------------------------------------------------------------------------------- 1 | from django.db import models 2 | 3 | 4 | # Create your models here. 5 | 6 | # this model Stores the data of the Phones Verified 7 | class phoneModel(models.Model): 8 | Mobile = models.IntegerField(blank=False) 9 | isVerified = models.BooleanField(blank=False, default=False) 10 | counter = models.IntegerField(default=0, blank=False) # For HOTP Verification 11 | 12 | def __str__(self): 13 | return str(self.Mobile) 14 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # OTP-in-django 2 | Quick and simple technique to implement the OTP functionality in your Django Project. 3 | 4 | ### Python Packages required: ```pyotp, base64, django, django-rest-framework``` 5 | 6 | ## API Calls 7 | 8 | #### GET 9 | This is to register the mobile number into the database and generate OTP. 10 | 11 | ```http://127.0.0.1:8000/verify/9999999999/``` 12 | 13 | #### POST 14 | This is to verify the mobile number using OTP. 15 | 16 | ```http://127.0.0.1:8000/verify/9999999999/``` 17 | 18 | Data: 19 | ``` 20 | { 21 | "otp":040301 22 | } 23 | ``` 24 | -------------------------------------------------------------------------------- /manage.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | """Django's command-line utility for administrative tasks.""" 3 | import os 4 | import sys 5 | 6 | 7 | def main(): 8 | os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'otp.settings') 9 | try: 10 | from django.core.management import execute_from_command_line 11 | except ImportError as exc: 12 | raise ImportError( 13 | "Couldn't import Django. Are you sure it's installed and " 14 | "available on your PYTHONPATH environment variable? Did you " 15 | "forget to activate a virtual environment?" 16 | ) from exc 17 | execute_from_command_line(sys.argv) 18 | 19 | 20 | if __name__ == '__main__': 21 | main() 22 | -------------------------------------------------------------------------------- /verification/migrations/0001_initial.py: -------------------------------------------------------------------------------- 1 | # Generated by Django 3.0.3 on 2020-02-22 10:48 2 | 3 | from django.db import migrations, models 4 | 5 | 6 | class Migration(migrations.Migration): 7 | 8 | initial = True 9 | 10 | dependencies = [ 11 | ] 12 | 13 | operations = [ 14 | migrations.CreateModel( 15 | name='phoneModel', 16 | fields=[ 17 | ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), 18 | ('Mobile', models.IntegerField()), 19 | ('isVerified', models.BooleanField(default=False)), 20 | ('counter', models.IntegerField(default=0)), 21 | ], 22 | ), 23 | ] 24 | -------------------------------------------------------------------------------- /otp/urls.py: -------------------------------------------------------------------------------- 1 | """otp URL Configuration 2 | 3 | The `urlpatterns` list routes URLs to views. For more information please see: 4 | https://docs.djangoproject.com/en/3.0/topics/http/urls/ 5 | Examples: 6 | Function views 7 | 1. Add an import: from my_app import views 8 | 2. Add a URL to urlpatterns: path('', views.home, name='home') 9 | Class-based views 10 | 1. Add an import: from other_app.views import Home 11 | 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') 12 | Including another URLconf 13 | 1. Import the include() function: from django.urls import include, path 14 | 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) 15 | """ 16 | from django.contrib import admin 17 | from django.urls import path, include 18 | 19 | urlpatterns = [ 20 | path('verify/', include('verification.urls')), 21 | path('admin/', admin.site.urls), 22 | ] 23 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | 2 | # Created by https://www.gitignore.io/api/django 3 | # Edit at https://www.gitignore.io/?templates=django 4 | 5 | ### Django ### 6 | *.log 7 | *.pot 8 | *.pyc 9 | __pycache__/ 10 | local_settings.py 11 | db.sqlite3 12 | db.sqlite3-journal 13 | media 14 | venv 15 | .idea 16 | # If your build process includes running collectstatic, then you probably don't need or want to include staticfiles/ 17 | # in your Git repository. Update and uncomment the following line accordingly. 18 | # /staticfiles/ 19 | 20 | ### Django.Python Stack ### 21 | # Byte-compiled / optimized / DLL files 22 | *.py[cod] 23 | *$py.class 24 | 25 | # C extensions 26 | *.so 27 | 28 | # Distribution / packaging 29 | .Python 30 | build/ 31 | develop-eggs/ 32 | dist/ 33 | downloads/ 34 | eggs/ 35 | .eggs/ 36 | lib/ 37 | lib64/ 38 | parts/ 39 | sdist/ 40 | var/ 41 | wheels/ 42 | pip-wheel-metadata/ 43 | share/python-wheels/ 44 | *.egg-info/ 45 | .installed.cfg 46 | *.egg 47 | MANIFEST 48 | 49 | # PyInstaller 50 | # Usually these files are written by a python script from a template 51 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 52 | *.manifest 53 | *.spec 54 | 55 | # Installer logs 56 | pip-log.txt 57 | pip-delete-this-directory.txt 58 | 59 | # Unit test / coverage reports 60 | htmlcov/ 61 | .tox/ 62 | .nox/ 63 | .coverage 64 | .coverage.* 65 | .cache 66 | nosetests.xml 67 | coverage.xml 68 | *.cover 69 | .hypothesis/ 70 | .pytest_cache/ 71 | 72 | # Translations 73 | *.mo 74 | 75 | # Scrapy stuff: 76 | .scrapy 77 | 78 | # Sphinx documentation 79 | docs/_build/ 80 | 81 | # PyBuilder 82 | target/ 83 | 84 | # pyenv 85 | .python-version 86 | 87 | # pipenv 88 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. 89 | # However, in case of collaboration, if having platform-specific dependencies or dependencies 90 | # having no cross-platform support, pipenv may install dependencies that don't work, or not 91 | # install all needed dependencies. 92 | #Pipfile.lock 93 | 94 | # celery beat schedule file 95 | celerybeat-schedule 96 | 97 | # SageMath parsed files 98 | *.sage.py 99 | 100 | # Spyder project settings 101 | .spyderproject 102 | .spyproject 103 | 104 | # Rope project settings 105 | .ropeproject 106 | 107 | # Mr Developer 108 | .mr.developer.cfg 109 | .project 110 | .pydevproject 111 | 112 | # mkdocs documentation 113 | /site 114 | 115 | # mypy 116 | .mypy_cache/ 117 | .dmypy.json 118 | dmypy.json 119 | 120 | # Pyre type checker 121 | .pyre/ 122 | 123 | # End of https://www.gitignore.io/api/django 124 | -------------------------------------------------------------------------------- /otp/settings.py: -------------------------------------------------------------------------------- 1 | """ 2 | Django settings for otp project. 3 | 4 | Generated by 'django-admin startproject' using Django 3.0.3. 5 | 6 | For more information on this file, see 7 | https://docs.djangoproject.com/en/3.0/topics/settings/ 8 | 9 | For the full list of settings and their values, see 10 | https://docs.djangoproject.com/en/3.0/ref/settings/ 11 | """ 12 | 13 | import os 14 | 15 | # Build paths inside the project like this: os.path.join(BASE_DIR, ...) 16 | BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) 17 | 18 | 19 | # Quick-start development settings - unsuitable for production 20 | # See https://docs.djangoproject.com/en/3.0/howto/deployment/checklist/ 21 | 22 | # SECURITY WARNING: keep the secret key used in production secret! 23 | SECRET_KEY = '-_@=eq_y866c&!++o*=0_w8c469l7qtt)e0mpfcp&yk&5ra4jg' 24 | 25 | # SECURITY WARNING: don't run with debug turned on in production! 26 | DEBUG = True 27 | 28 | ALLOWED_HOSTS = [] 29 | 30 | 31 | # Application definition 32 | 33 | INSTALLED_APPS = [ 34 | 'django.contrib.admin', 35 | 'django.contrib.auth', 36 | 'django.contrib.contenttypes', 37 | 'django.contrib.sessions', 38 | 'django.contrib.messages', 39 | 'django.contrib.staticfiles', 40 | 'rest_framework', 41 | 'verification' 42 | ] 43 | 44 | MIDDLEWARE = [ 45 | 'django.middleware.security.SecurityMiddleware', 46 | 'django.contrib.sessions.middleware.SessionMiddleware', 47 | 'django.middleware.common.CommonMiddleware', 48 | 'django.middleware.csrf.CsrfViewMiddleware', 49 | 'django.contrib.auth.middleware.AuthenticationMiddleware', 50 | 'django.contrib.messages.middleware.MessageMiddleware', 51 | 'django.middleware.clickjacking.XFrameOptionsMiddleware', 52 | ] 53 | 54 | ROOT_URLCONF = 'otp.urls' 55 | 56 | TEMPLATES = [ 57 | { 58 | 'BACKEND': 'django.template.backends.django.DjangoTemplates', 59 | 'DIRS': [], 60 | 'APP_DIRS': True, 61 | 'OPTIONS': { 62 | 'context_processors': [ 63 | 'django.template.context_processors.debug', 64 | 'django.template.context_processors.request', 65 | 'django.contrib.auth.context_processors.auth', 66 | 'django.contrib.messages.context_processors.messages', 67 | ], 68 | }, 69 | }, 70 | ] 71 | 72 | WSGI_APPLICATION = 'otp.wsgi.application' 73 | 74 | 75 | # Database 76 | # https://docs.djangoproject.com/en/3.0/ref/settings/#databases 77 | 78 | DATABASES = { 79 | 'default': { 80 | 'ENGINE': 'django.db.backends.sqlite3', 81 | 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), 82 | } 83 | } 84 | 85 | # DEFAULT_AUTO_FIELD defined because verification.phoneModel Auto-created primary key used 86 | # when not defining a primary key type, by default 'django.db.models.AutoField'. 87 | DEFAULT_AUTO_FIELD = 'django.db.models.AutoField' 88 | 89 | # Password validation 90 | # https://docs.djangoproject.com/en/3.0/ref/settings/#auth-password-validators 91 | 92 | AUTH_PASSWORD_VALIDATORS = [ 93 | { 94 | 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', 95 | }, 96 | { 97 | 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', 98 | }, 99 | { 100 | 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', 101 | }, 102 | { 103 | 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', 104 | }, 105 | ] 106 | 107 | 108 | # Internationalization 109 | # https://docs.djangoproject.com/en/3.0/topics/i18n/ 110 | 111 | LANGUAGE_CODE = 'en-us' 112 | 113 | TIME_ZONE = 'UTC' 114 | 115 | USE_I18N = True 116 | 117 | USE_L10N = True 118 | 119 | USE_TZ = True 120 | 121 | 122 | # Static files (CSS, JavaScript, Images) 123 | # https://docs.djangoproject.com/en/3.0/howto/static-files/ 124 | 125 | STATIC_URL = '/static/' 126 | -------------------------------------------------------------------------------- /verification/views.py: -------------------------------------------------------------------------------- 1 | from datetime import datetime 2 | from django.core.exceptions import ObjectDoesNotExist 3 | import pyotp 4 | from rest_framework.response import Response 5 | from rest_framework.views import APIView 6 | from .models import phoneModel 7 | import base64 8 | 9 | 10 | # This class returns the string needed to generate the key 11 | class generateKey: 12 | @staticmethod 13 | def returnValue(phone): 14 | return str(phone) + str(datetime.date(datetime.now())) + "Some Random Secret Key" 15 | 16 | 17 | class getPhoneNumberRegistered(APIView): 18 | # Get to Create a call for OTP 19 | @staticmethod 20 | def get(request, phone): 21 | try: 22 | Mobile = phoneModel.objects.get(Mobile=phone) # if Mobile already exists the take this else create New One 23 | except ObjectDoesNotExist: 24 | phoneModel.objects.create( 25 | Mobile=phone, 26 | ) 27 | Mobile = phoneModel.objects.get(Mobile=phone) # user Newly created Model 28 | Mobile.counter += 1 # Update Counter At every Call 29 | Mobile.save() # Save the data 30 | keygen = generateKey() 31 | key = base64.b32encode(keygen.returnValue(phone).encode()) # Key is generated 32 | OTP = pyotp.HOTP(key) # HOTP Model for OTP is created 33 | print(OTP.at(Mobile.counter)) 34 | # Using Multi-Threading send the OTP Using Messaging Services like Twilio or Fast2sms 35 | return Response({"OTP": OTP.at(Mobile.counter)}, status=200) # Just for demonstration 36 | 37 | # This Method verifies the OTP 38 | @staticmethod 39 | def post(request, phone): 40 | try: 41 | Mobile = phoneModel.objects.get(Mobile=phone) 42 | except ObjectDoesNotExist: 43 | return Response("User does not exist", status=404) # False Call 44 | 45 | keygen = generateKey() 46 | key = base64.b32encode(keygen.returnValue(phone).encode()) # Generating Key 47 | OTP = pyotp.HOTP(key) # HOTP Model 48 | if OTP.verify(request.data["otp"], Mobile.counter): # Verifying the OTP 49 | Mobile.isVerified = True 50 | Mobile.save() 51 | return Response("You are authorised", status=200) 52 | return Response("OTP is wrong", status=400) 53 | 54 | 55 | # Time after which OTP will expire 56 | EXPIRY_TIME = 50 # seconds 57 | 58 | class getPhoneNumberRegistered_TimeBased(APIView): 59 | # Get to Create a call for OTP 60 | @staticmethod 61 | def get(request, phone): 62 | try: 63 | Mobile = phoneModel.objects.get(Mobile=phone) # if Mobile already exists the take this else create New One 64 | except ObjectDoesNotExist: 65 | phoneModel.objects.create( 66 | Mobile=phone, 67 | ) 68 | Mobile = phoneModel.objects.get(Mobile=phone) # user Newly created Model 69 | Mobile.save() # Save the data 70 | keygen = generateKey() 71 | key = base64.b32encode(keygen.returnValue(phone).encode()) # Key is generated 72 | OTP = pyotp.TOTP(key,interval = EXPIRY_TIME) # TOTP Model for OTP is created 73 | print(OTP.now()) 74 | # Using Multi-Threading send the OTP Using Messaging Services like Twilio or Fast2sms 75 | return Response({"OTP": OTP.now()}, status=200) # Just for demonstration 76 | 77 | # This Method verifies the OTP 78 | @staticmethod 79 | def post(request, phone): 80 | try: 81 | Mobile = phoneModel.objects.get(Mobile=phone) 82 | except ObjectDoesNotExist: 83 | return Response("User does not exist", status=404) # False Call 84 | 85 | keygen = generateKey() 86 | key = base64.b32encode(keygen.returnValue(phone).encode()) # Generating Key 87 | OTP = pyotp.TOTP(key,interval = EXPIRY_TIME) # TOTP Model 88 | if OTP.verify(request.data["otp"]): # Verifying the OTP 89 | Mobile.isVerified = True 90 | Mobile.save() 91 | return Response("You are authorised", status=200) 92 | return Response("OTP is wrong/expired", status=400) 93 | --------------------------------------------------------------------------------