Coder Social home page Coder Social logo

curiouslearner / django-phone-verify Goto Github PK

View Code? Open in Web Editor NEW
257.0 10.0 61.0 177 KB

A Django app to support phone number verification using security code / One-Time-Password (OTP) sent via SMS.

Home Page: https://www.sanyamkhurana.com/django-phone-verify/

License: GNU General Public License v3.0

Python 100.00%
hacktoberfest phone-number-verification one-time-password phone-verification phone-verification-code

django-phone-verify's Introduction

django-phone-verify

https://github.com/github/docs/actions/workflows/main.yml/badge.svg?branch=master https://coveralls.io/repos/github/CuriousLearner/django-phone-verify/badge.svg?branch=master License https://static.pepy.tech/badge/django-phone-verify?period=total&units=international_system&left_color=black&right_color=darkgreen&left_text=Downloads https://img.shields.io/badge/PRs-welcome-brightgreen.svg?style=flat-square

A Django app to support phone number verification using the security code sent via SMS.

Salient Features

  • Let's devs verify phone numbers via SMS.
  • Extensibility to provide tokens with varying lengths.
  • Comes with Twilio and Nexmo already integrated.
  • Set expiration time on tokens.
  • Provides an interface for writing custom SMS sending backend for easy extensibility.
  • Does not mess up with existing AUTH_USER_MODEL at all.
  • Can be used for several potential use-cases, and not just auth.
  • Provides ready endpoints for sending SMS and verification (See api_endpoints.rst).

Installation

pip install django-phone-verify

Configuration

  • Add app to INSTALLED_APPS
# In settings.py:

# Add app to `INSTALLED_APPS`
INSTALLED_APPS = [
    ...
    "phone_verify",
    ...
]
  • Add settings for Phone Verify as you desire:
# In settings.py
# Add settings for phone_verify to work
PHONE_VERIFICATION = {
    "BACKEND": "phone_verify.backends.twilio.TwilioBackend",
    "OPTIONS": {
        "SID": "fake",
        "SECRET": "fake",
        "FROM": "+14755292729",
        "SANDBOX_TOKEN": "123456",
    },
    "TOKEN_LENGTH": 6,
    "MESSAGE": "Welcome to {app}! Please use security code {security_code} to proceed.",
    "APP_NAME": "Phone Verify",
    "SECURITY_CODE_EXPIRATION_TIME": 3600,  # In seconds only
    "VERIFY_SECURITY_CODE_ONLY_ONCE": False,  # If False, then a security code can be used multiple times for verification
}

Usage

  • To explore more about how to use, integrate and leverage the existing functionality of Django Phone Verify, have a look at getting_started.rst

Note: Django Phone Verify also provides Nexmo as a backend service other than Twilio. To switch to Nexmo, replace BACKEND within your PHONE_VERIFICATION setting with phone_verify.backends.nexmo.NexmoBackend and define KEY within OPTIONS of PHONE_VERIFICATION setting, with your Nexmo API key, in place of already available SID.

Compatibility

  • Python 3.6+
  • Django 2.1+
  • Django REST Framework 3.9+

Contributing

No code is bug-free and I'm sure this app will have bugs. If you find any bugs, please create an issue on GitHub.

Licence

GPLv3

Release Notes

[Dev]

Added

  • Support for Python 3.11.
  • CI tests for Py{311}-Django{2x,3x,4x}.

[3.0.0]

Added

  • Support for Django 4.x.
  • Support for Django 3.2.

Changed

  • Method phone_verify.backends.nexmo.NexmoBackend.send_sms changes parameter name from numbers to number to be consistent with rest of the inherited classes.

[2.0.1]

Added

  • Support for Python 3.8 & Python 3.9.
  • CI tests for Py{36,37,38,39}-Django{20,21,22,30,31}.

Changed

  • Fixed issue generate_session_token to handle cases in Py38, Py39 when the session_token is already string instead of bytes.

[2.0.0]

NOTE: The previous version of this library provided the security_code in the JWT session_token. You would have to re-verify phone_numbers in this version to ensure they are authentically verified.

Added

  • Tests added to provide 100% coverage on the package.
  • Add nexmo.errors.ClientError as exception class in phone_verify.backends.nexmo.NexmoBackend & phone_verify.backends.nexmo.NexmoSandboxBackend.

Changed

  • Method signature changed for phone_verify.backends.BaseBackend.generate_session_token. It now accepts only phone_number instead of combination of phone_number and security_code.
  • Remove the security_code from JWT session_token to avoid leaking information.
  • Add nonce in session_token to generate unique tokens for each phone_number.
  • Fixes call to phone_verify.backends.nexmo.NexmoBackend.send_sms method.

[1.1.0]

Added

  • Support Nexmo as a backend service along with Twilio.
  • Add docs for writing a custom backend.

Changed

  • Update backends.base.BaseBackend.validate_security_code to use save() instead of update() to allow Django to emit its post_save() signal.

[1.0.0]

Added

  • Add coverage report through coveralls.
  • Support for One-Time Passwords (OTP) using VERIFY_SECURITY_CODE_ONLY_ONCE as True in the settings.
  • Script to support makemigrations for development.
  • BaseBackend status now have SECURITY_CODE_VERIFIED and SESSION_TOKEN_INVALID status to support new states.

Changed

  • Rename TWILIO_SANDBOX_TOKEN to SANDBOX_TOKEN.
  • Fix signature for send_bulk_sms method in TwilioBackend and TwilioSandboxBackend.
  • Response for /api/phone/register contains key session_token instead of session_code.
  • Request payload for /api/phone/verify now expects session_token key instead of session_code.
  • Response for /api/phone/verify now sends additional response of Security code is already verified in case VERIFY_SECURITY_CODE_ONLY_ONCE is set to True.
  • Rename otp to security_code in code and docs to be more consistent.
  • Rename BaseBackend status from VALID, INVALID, EXPIRED to SECURITY_CODE_VALID, SECURITY_CODE_INVALID, and SECURITY_CODE_EXPIRED respectively.
  • Rename session_code to session_token to be consistent in code and naming across the app.
  • Rename service send_otp_and_generate_session_code to send_security_code_and_generate_session_token.
  • Rename method BaseBackend.generate_token to BaseBackend.generate_security_code.
  • Rename method create_otp_and_session_token to create_security_code_and_session_token.
  • Rename method BaseBackend.validate_token to BaseBackend.validate_security_code with an additional parameter of session_token.

[0.2.0]

Added

  • pre-commit-config to maintain code quality using black and other useful tools.
  • Docs for integration and usage in getting_started.rst.
  • Tox for testing on py{37}-django{20,21,22}.
  • Travis CI for testing builds.

Changed

  • Convert *.md docs to reST Markup.
  • Fix issue with installing required package dependencies via install_requires.

[0.1.1]

Added

  • README and documentation of API endpoints.
  • setup.cfg to manage coverage.
  • phone_verify app including backends, requirements, tests.
  • Initial app setup.

django-phone-verify's People

Contributors

arnav13081994 avatar curiouslearner avatar dependabot[bot] avatar geekyshacklebolt avatar gutsytechster avatar mnrudkovskyi avatar russell310 avatar sepehrhasanabadi avatar storymode7 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

django-phone-verify's Issues

Update "ugettext_lazy" Import in Package Models

When installing django-phone-verify with a new Django application, the following error is encountered when running the python manage.py migrate command to create the django-phone-verify tables in the database:

/site-packages/phone_verify/models.py", line 6, in <module> from django.utils.translation import ugettext_lazy as _ ImportError: cannot import name 'ugettext_lazy' from 'django.utils.translation'

There is a pull request (#71) open to address this but it doesn't look like it's been deployed. The models.py and serializers.py that were installed with version 2.0.1 did not have the changes from that pull request included causing the error above.

Rename SANDBOX_TOKEN for settings

Currently, if we change the SANDBOX BACKEND, we also need to change the need of the key in case the corresponding sandbox is used.

"OPTIONS": {
        "SID": "fake",
        "SECRET": "fake",
        "FROM": "+14755292729",
        "TWILIO_SANDBOX_TOKEN": "123456",
    },

A better idea is to keep the name consistent as SANDBOX_TOKEN

RemovedInDjango41Warning: 'phone_verify' defines default_app_config = 'phone_verify.apps.PhoneVerificationConfig'

#91
``RemovedInDjango41Warning: 'phone_verify' defines default_app_config = 'phone_verify.apps.PhoneVerificationConfig'. Django now detects this configuration automatically. You can remove default_app_config.

More about this https://docs.djangoproject.com/en/3.2/releases/3.2/#automatic-appconfig-discovery

fix for phone_verify/init.py

import django


if django.VERSION < (3, 2):
    default_app_config = "phone_verify.apps.PhoneVerificationConfig"

Add expired status to admin

Would be awesome if

  1. You could see if a registration code has expired in the admin area
  2. If you could set a date where they are cleared from the DB
  3. Some more clarification of how each backend works, e.g how to switch between sandbox to prod.

TwilioSandboxBackend returns only single value in validate_security_code method

TwilioSandboxBackend inherits BaseBackend and overrides validate_security_code method of it. However, in BaseBackend, the validate_security_code method returns two values[1]. However, the overridden method only returns the single value[2].

This would make it non-uniform and could lead exceptions to be raised. One such case would be here[3] when unpacking the arguments. Hence it should return two arguments as well.

The other argument could be None. As the Sandbox class is created for testing purpose, we don't bother performing any validation.

[1] https://github.com/CuriousLearner/django-phone-verify/blob/master/phone_verify/backends/base.py#L141
[2] https://github.com/CuriousLearner/django-phone-verify/blob/master/phone_verify/backends/twilio.py#L58
[3] https://github.com/CuriousLearner/django-phone-verify/blob/master/phone_verify/serializers.py#L34

Package this for other distributions, maybe?

Hey,

While one can install this via pip, it'd be great to do a system based installation via apt, dnf, aur, et al?
I am not sure if you need this or not, but guess it's nice to have different ways of installing the modules.

Add docs for writing custom backend

Currently, Twilio is already integrated into the package, but one can write a custom backend plugging another third-party service to send an SMS.

Write docs to explain the process of writing a custom backend and integrating it with the app.

Integrate Travis CI

Add Travis ci file to trigger automatic builds and run the tests on each consecutive PR/push.

Dependency error with twilio

Is there any way not to include twilio/nexmo dependencies? Twilio has strict version, which breaks my environment.

There are incompatible versions in the resolved dependencies:
  pyjwt<3,>=2 (from djangorestframework-simplejwt==4.7.2->-r /tmp/pipenv6rgd0e3brequirements/pipenv-c9i29072-constraints.txt (line 2))
  pyjwt==1.7.1 (from twilio==6.62.1->django-phone-verify==2.0.1->-r /tmp/pipenv6rgd0e3brequirements/pipenv-c9i29072-constraints.txt (line 15))
  pyjwt>=1.7.1 (from django-phone-verify==2.0.1->-r /tmp/pipenv6rgd0e3brequirements/pipenv-c9i29072-constraints.txt (line 15))
  pyjwt[crypto]>=1.6.4 (from nexmo==2.5.2->django-phone-verify==2.0.1->-r /tmp/pipenv6rgd0e3brequirements/pipenv-c9i29072-constraints.txt (line 15))

Django OTP login

I want to set a session for every call on the verify method once the session expires the user needs to verify again. my user doesn't have a password set and the username is mobile number

Add ability to customize message format in the

Hi, currently you can customize DPV by extending BaseBackend. Would it be possible to allow PhoneVerificationService to check whether the backend wants to supply the message directly, instead of having it only pull from settings.PHONE_VERIFICATION['MESSAGE']?

Specifically, allow the backend to replace this logic:

def _generate_message(self, security_code):
    return self.verification_message.format(
        app=settings.PHONE_VERIFICATION.get("APP_NAME", DEFAULT_APP_NAME),
        security_code=security_code,
    )

Add coverage information through coveralls

Currently, there is no indication of coverage for the package unless they run the test locally.

Coveralls needs to be integrated so that one can visually see how the coverage is affected.

fields

What should be added to sandbox token and secret field in the settings.py file?

validate_security_code method of TwilioSandboxBackend class return int instead of tuple

It leads to an error during phone verification with TwilioSandboxBackend

Traceback:

File "/usr/local/lib/python3.7/site-packages/django/core/handlers/exception.py" in inner
  34.             response = get_response(request)

File "/usr/local/lib/python3.7/site-packages/django/core/handlers/base.py" in _get_response
  115.                 response = self.process_exception_by_middleware(e, request)

File "/usr/local/lib/python3.7/site-packages/django/core/handlers/base.py" in _get_response
  113.                 response = wrapped_callback(request, *callback_args, **callback_kwargs)

File "/usr/local/lib/python3.7/site-packages/django/views/decorators/csrf.py" in wrapped_view
  54.         return view_func(*args, **kwargs)

File "/usr/local/lib/python3.7/site-packages/rest_framework/viewsets.py" in view
  116.             return self.dispatch(request, *args, **kwargs)

File "/usr/local/lib/python3.7/site-packages/rest_framework/views.py" in dispatch
  495.             response = self.handle_exception(exc)

File "/usr/local/lib/python3.7/site-packages/rest_framework/views.py" in handle_exception
  455.             self.raise_uncaught_exception(exc)

File "/usr/local/lib/python3.7/site-packages/rest_framework/views.py" in dispatch
  492.             response = handler(request, *args, **kwargs)

File "/usr/local/lib/python3.7/site-packages/phone_verify/api.py" in verify
  36.         serializer.is_valid(raise_exception=True)

File "/usr/local/lib/python3.7/site-packages/rest_framework/serializers.py" in is_valid
  236.                 self._validated_data = self.run_validation(self.initial_data)

File "/usr/local/lib/python3.7/site-packages/rest_framework/serializers.py" in run_validation
  437.             value = self.validate(value)

File "/usr/local/lib/python3.7/site-packages/phone_verify/serializers.py" in validate
  37.             session_token=session_token,

Exception Type: TypeError at /api/phone/verify/
Exception Value: cannot unpack non-iterable int object

No module named 'phonenumber_field' Getting error

hi ,
i want to used your package and i installed it go through the documentation but while running server i m getting error ...
from phonenumber_field.modelfields import PhoneNumberField
ModuleNotFoundError: No module named 'phonenumber_field'

not able to use your package.

Security Code is returned in Session Token?

I'm concerned about the security of this application. (or maybe I'm just confused?)

Why do you include the Security Code in the payload of the session token when responding to the register endpoint? This is not encrypted and can easily be decoded.

The end user would not need access to the phone number in order to type in the security code and "verify" they own the phone number.

Add a layer on top of Django All-Auth that supports phone number based authentication

Description

Build on top of Django Allauth, a mobile-based authentication backend with Twilio.

Rationale

Everyone has mobiles these days and a whole lot more people in developing countries own phones than desktops. For such mobile users, a Phone number is the only thing they have in common. Most don't have emails and probably will never have one. The only way to reach such people would be to create a Phone number based authentication backend.

Use case(s) / visualization(s)

A person who wants to login into a mobile website can simply receive a One Time Password on their phone number and once they enter it correctly they get signed up and an associated user is created for them in the backend.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.