Django REST framework with JWT Authentication(part-1)


 


Django REST framework is a powerful and flexible toolkit for building Web APIs. Some reasons you might want to use REST framework: The Web browsable API is a huge usability win for your developers. Authentication policies including packages for OAuth1a and OAuth2.

Let's begin our journey....  🧑🏻‍✈️ 🧑🏻‍✈️ 🧑🏻‍✈️

I assume that you are already an experience with creating virtual Environment and setting up your projects. Your project structure seems like this.

GIT Repo link: pyJWT

 


 What we cover here?

  1. Creating Custom user.
  2. Sign-in/sign up
  3. JWT Setup
  4. Serializations
  5. Testing with Postman

 

 

 

Installation & Setup:

For this tutorial we are going to use the pyJWT library.

 
pip install django djangorestframework pyjwt   

 After installations completes, let's create a new app name accounts.

 
     python manage.py startapp accounts
 

 Let's register accounts app in settings.py file of main project.

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    
    'rest_framework',

    # my_app
    'accounts'

]

Before we go further let's config our urls file. Create a urls.py file inside accounts app.

from django.urls import path

urlpatterns = [
    
]


In our main app urls, add little code. which are as follow:

from django.contrib import admin
from django.urls import pathinclude

urlpatterns = [
    path('admin/'admin.site.urls),
    path('api/'include('accounts.urls'))
]


Okay, here we go to another round....😤💪 😤💪 😤 💪😤💪 😤 💪😤💪 😤  

 

👊🏼👊🏼👊🏼👊🏼👊🏼👊🏼👊🏼👊🏼👊🏼👊🏼👊🏼 ROUND 1 BEGIN 👊🏼👊🏼👊🏼👊🏼👊🏼👊🏼👊🏼👊🏼👊🏼👊🏼👊🏼👊🏼👊🏼

Creating a Model

Let's create a custom user  using AbstractBaseUser. There are two ways to create a custom user model in Django: AbstractUser and AbstractBaseUser

For more details : CLICK HERE, i won't be lecturing here.

What is ? and what is not ?..... Read yourself......... 😁😁😁😁😁😁😁😁




Our custom user model seems like this:

 
from django.db import models
from django.core.validators import RegexValidator
from django.contrib.auth.models import (
    AbstractBaseUser,
    PermissionsMixin,
)

USERNAME_REGEX = "^[a-zA-Z0-9.+-]*$"

class MyUser(AbstractBaseUserPermissionsMixin):
    email = models.EmailField(max_length=255unique=Trueverbose_name="Email Address")
    username = models.CharField(max_length=255validators=[
        RegexValidator(regex=USERNAME_REGEX,
        message='Username must be alphanumeric or contains numbers',
        code='Invalid Username'
        )
    ],
    unique=True
    )
    is_admin = models.BooleanField(default=False)
    is_staff = models.BooleanField(default=False)

    USERNAME_FIELD = "username"
    REQUIRED_FIELDS = ["email"]

    def has_perm(selfpermobj=None):
        return True

    def has_module_perms(selfapp_label):
        return True

    def __str__(self):
        return self.email

Let's create our base user manager.......

Overall, our codes looks like this:

 
from django.db import models
from django.core.validators import RegexValidator
from django.contrib.auth.models import (
    AbstractBaseUser,
    PermissionsMixin,
    BaseUserManager
)

USERNAME_REGEX = "^[a-zA-Z0-9.+-]*$"

''' Baseuser manager which creates new user and create_superuser '''
class MyUserManager(BaseUserManager):
    def create_user(selfusernameemailpassword=None):
        if not email:
            raise ValueError("User must have an Email address")
        user = self.model(username=username, email=self.normalize_email(email))
        user.set_password(password)
        user.save(using=self._db)
        return user
    
    def create_superuser(selfusernameemailpassword=None):
        user = self.create_user(username, email, password=password)
        user.is_admin = True
        user.is_staff = True
        user.save(using=self._db)
        return user

""" Custom User which supports both email and username """
class MyUser(AbstractBaseUserPermissionsMixin):
    email = models.EmailField(max_length=255unique=Trueverbose_name="Email Address")
    username = models.CharField(max_length=255validators=[
        RegexValidator(regex=USERNAME_REGEX,
        message='Username must be alphanumeric or contains numbers',
        code='Invalid Username'
        )
    ],
    unique=True
    )
    is_admin = models.BooleanField(default=False)
    is_staff = models.BooleanField(default=False)

    objects = MyUserManager()

    USERNAME_FIELD = 'username'
    REQUIRED_FIELDS = ['email']

    def has_perm(selfpermobj=None):
        return True

    def has_module_perms(selfapp_label):
        return True

    def __str__(self):
        return self.email

so we need to do a little tweak to recognize our custom user by django, let's march to the main app of settings.py file. At the very bottom of file write this very code.

 
AUTH_USER_MODEL = "accounts.MyUser"
 

so in string quotes where we define  accounts which means our very created app and MyUser refers to the custom user model which we created.

Before testing our app let's migrate to database.

 
python manage.py makemigrations
python manage.py migrate
python manage.py createsuperuser 
 

 Hope You guys made it ......

Okay, now we register our user models to admin.py file, in order to view on admin panel.... Let's march towards admin.py file of our accounts app...

admin.py file should looks like this:

from django.contrib import admin
from .models import MyUser
# Register your models here.

admin.site.register(Myuser)

So login and see magic......💯 [Note: actually it is not magic]

Banjai 👏👏👏👏👏👏 we finished this session see you on next one


⏭️Django REST framework with JWT Authentication(part-2)⏭️


Post a Comment

Previous Post Next Post