Out-of-the-box support register, sign in, email verification and password recovery workflows for websites based on Django and MongoDB

Overview

Using djmongoauth

What is it?

djmongoauth provides out-of-the-box support for basic user management and additional operations including user registration, login, logout, email verification, password recovery for backends built with the Django web framework and MongoDB.

djmongoauth is based on djongo, a MongoDB ORM for Django.

Installation

Install djmongoauth through pip:

haotian@u8fZOlcHP:~$ sudo pip3 install djmongoauth

PyPI package can be found at https://pypi.org/project/djmongoauth/0.0.1/

Use cases

User object

User object is the core of the djmongoauth. It represents a authenticable entity. The primary attributes of a default user instance are:

  • username
  • email
  • password
  • email_verified
  • email_verified_at

Register a new user

def register(request):
    req_body = json.loads(request.body.decode("UTF-8"))
    user = User()
    user.username = req_body["username"]
    user.email = req_body["email"]
    user.password = req_body["password"]
    try:
        user.register()
    except Exception as e:
        return JsonResponse({"error": str(e)}, status=400)
    return HttpResponse(status=201)
  • request.method must be POST
  • Body of request must have these attributes and they must be well-formed: username, email, password. Password can be cleartext (djmongoauth takes care of hashing / decryption)

Log in

def login(request):
    try:
        req_body = json.loads(request.body.decode("UTF-8"))
        x_auth_token = User.login(req_body["username"], req_body["password"])
    except Exception as e:
        return JsonResponse({"error": str(e)}, status=400)
    return JsonResponse({"token": x_auth_token})
  • request.method must be POST
  • Body of request must have these attributes: username and password
  • login() call returns a x_auth_token. This token should be returned to your site's frontend and serve as a basic auth token in the HTTP_AUTHORIZATION header for all subsequent requests till the token expires

Log out

def logout(request):
    try:
        User.logout(request)
    except Exception as e:
        return JsonResponse({"error": str(e)}, status=400)
    return HttpResponse(status=204)
  • request must have its HTTP_AUTHORIATION header set to the x_auth_token returned from login call

Email verification

# handler for verifying email address
def verify_email(request):
    if request.method == "POST":
        return _send_verify_email(request)
    elif request.method == "PUT":
        return _handle_email_verification(request)
    else:
        return HttpResponse(status=405)

def _send_verify_email(request):
    try:
        User.send_email(request, type=EmailTypes.VERIFY)
        return HttpResponse(status=201)
    except Exception as e:
        return JsonResponse({"error": str(e)}, status=400)

def _handle_email_verification(request):
    try:
        User.handle_email_request(request, EmailTypes.VERIFY)
        return HttpResponse(status=200)
    except Exception as e:
        return JsonResponse({"error": str(e)}, status=400)

A verification email will be sent to the user's registered email address. Following is a sample verification email:

Hello test_user:

Please use the following link to verify your email address on test.com

https://test.com/verify?a=wMw_qmXu8fZOlcHP1Xpku4e8nuo8rCQim0AHzp5Taqtk0CWq2sThbEMu5kVCcy5leVYDpHKfY6-fMc_4HZBbQg

This link will expire on 2021-09-12 02:04:21 UTC

Thank you for using test.com!
  • request must have its HTTP_AUTHORIATION header set to the x_auth_token returned from login call
  • To send a verification email, POST this endpoint; to handle a email verification request, PUT this endpoint with parameter a set. Example: PUT https://api.test.com/verify?a=wMw_qmXu8fZOlcHP1Xpku4e8nuo8rCQim0AHzp5Taqtk0CWq2sThbEMu5kVCcy5leVYDpHKfY6-fMc_4HZBbQg
  • If using a hosted email domain service (example: GSuite), please ensure that options such as less secure apps are enabled (Gmail)

Password reset

def reset_password(request):
    if request.method == "POST":
        return _send_recovery_email(request)
    elif request.method == "PUT":
        return _handle_password_recovery(request)
    else:
        return HttpResponse(status=405)

def _send_recovery_email(request):
    try:
        User.send_email(request, type=EmailTypes.RESET)
        return HttpResponse(status=200)
    except Exception as e:
        return JsonResponse({"error": str(e)}, status=400)

def _handle_password_recovery(request):
    try:
        User.handle_email_request(request, EmailTypes.RESET)
        return HttpResponse(status=200)
    except Exception as e:
        return JsonResponse({"error": str(e)}, status=400)

A password reset email will be sent to the user's registered email address. Following is a sample password reset email:

Hello test_user,

A request has been received to change the password for your account on test.com

Please follow this link to reset your password: https://test.com/reset?a=XfNKZT-OXXvvto3fDAyo5l46Ssmx1wQkXzlYGxQKyhFq3FTNve4vrvNYu8b8ha2erghRWtWfwFT5TT7O9xgM6Q

This link will expire on 2021-09-12 02:34:45 UTC

If you did not initiate this request, please ignore this email.
  • To send a password reset email, POST this endpoint; to handle a password reset request, PUT this endpoint with parameter a set. Example: PUT https://api.test.com/reset?a=wMw_qmXu8fZOlcHP1Xpku4e8nuo8rCQim0AHzp5Taqtk0CWq2sThbEMu5kVCcy5leVYDpHKfY6-fMc_4HZBbQg
  • When PUTting this endpoint, body of request must have these attributes: new_password. new_password can be cleartext (djmongoauth takes care of hashing / decryption)

Decorator

@authenticated

Use this decorator on request handlers, etc. to ensure a user is already logged in

from djmongoauth.decorators.authenticated import authenticated

@authenticated
def my_other_view_handler(request):
    pass 

If a user is not properly authenticated (e.g. not logged in / login session has expired), a DjMongoAuthError will be raised

You might also like...
python-social-auth and oauth2 support for django-rest-framework

Django REST Framework Social OAuth2 This module provides OAuth2 social authentication support for applications in Django REST Framework. The aim of th

JSON Web Token Authentication support for Django REST Framework

REST framework JWT Auth Notice This project is currently unmaintained. Check #484 for more details and suggested alternatives. JSON Web Token Authenti

JSON Web Token Authentication support for Django REST Framework

REST framework JWT Auth JSON Web Token Authentication support for Django REST Framework Overview This package provides JSON Web Token Authentication s

An enhanced permission system which support object permission in Django

django-permission Author Alisue [email protected] Supported python versions Python 2.7, 3.3, 3.4, 3.5, 3.6 Supported django versions Django 1

JWT Key Confusion PoC (CVE-2015-9235) Written for the Hack the Box challenge - Under Construction
JWT Key Confusion PoC (CVE-2015-9235) Written for the Hack the Box challenge - Under Construction

JWT Key Confusion PoC (CVE-2015-9235) Written for the Hack the Box challenge - Under Construction This script performs a Java Web Token Key Confusion

Python One-Time Password Library
Python One-Time Password Library

PyOTP - The Python One-Time Password Library PyOTP is a Python library for generating and verifying one-time passwords. It can be used to implement tw

A simple username/password database authentication solution for Streamlit
A simple username/password database authentication solution for Streamlit

TL;DR: This is a simple username/password login authentication solution using a backing database. Both SQLite and Airtable are supported.

Graphical Password Authentication System.
Graphical Password Authentication System.

Graphical Password Authentication System. This is used to increase the protection/security of a website. Our system is divided into further 4 layers of protection. Each layer is totally different and diverse than the others. This not only increases protection, but also makes sure that no non-human can log in to your account using different activities such as Brute Force Algorithm and so on.

Django-react-firebase-auth - A web app showcasing OAuth2.0 + OpenID Connect using Firebase, Django-Rest-Framework and React
Django-react-firebase-auth - A web app showcasing OAuth2.0 + OpenID Connect using Firebase, Django-Rest-Framework and React

Demo app to show Django Rest Framework working with Firebase for authentication

Owner
hao
hao
it's a Django application to register and authenticate users using phone number.

django-phone-auth It's a Django application to register and authenticate users using phone number. CustomUser model created using AbstractUser class.

MsudD 4 Nov 29, 2022
Django-registration (redux) provides user registration functionality for Django websites.

Description: Django-registration provides user registration functionality for Django websites. maintainers: Macropin, DiCato, and joshblum contributor

Andrew Cutler 920 Jan 8, 2023
Mock authentication API that acceccpts email and password and returns authentication result.

Mock authentication API that acceccpts email and password and returns authentication result.

Herman Shpryhau 1 Feb 11, 2022
Extending the Django authentication system with a phone verification step.

Extending the Django authentication system with a phone verification step.

Miguel Grinberg 50 Dec 4, 2022
🔐 Login & Register System

?? Login & Register System This is a developable login and register system. Enter your username and password to register or login to account. Automati

Firdevs Akbayır 10 Dec 12, 2022
Django CAS 1.0/2.0/3.0 client authentication library, support Django 2.0, 2.1, 2.2, 3.0 and Python 3.5+

django-cas-ng django-cas-ng is Django CAS (Central Authentication Service) 1.0/2.0/3.0 client library to support SSO (Single Sign On) and Single Logou

django-cas-ng 347 Dec 18, 2022
An extension of django rest framework, providing a configurable password reset strategy

Django Rest Password Reset This python package provides a simple password reset strategy for django rest framework, where users can request password r

Anexia 363 Dec 24, 2022
This python package provides a simple password reset strategy for django rest framework

Django Rest Password Reset This python package provides a simple password reset strategy for django rest framework, where users can request password r

Anexia 363 Dec 24, 2022
Django Auth Protection This package logout users from the system by changing the password in Simple JWT REST API.

Django Auth Protection Django Auth Protection This package logout users from the system by changing the password in REST API. Why Django Auth Protecti

Iman Karimi 5 Oct 26, 2022
python-social-auth and oauth2 support for django-rest-framework

Django REST Framework Social OAuth2 This module provides OAuth2 social authentication support for applications in Django REST Framework. The aim of th

null 1k Dec 22, 2022