Hello Devs, In this blog you will learn how to create User Authentication, login and signup API's in djangorestframework using SimpleJWT.
Source Code:- https://github.com/ShivamRohilllaa/DjangoRestFramework-UserAuthentication/
Post Link:- https://pythondjangogeek.com/django/streamlined-user-authentication-with-django-and-si/
I hope you guys knows how to create a django project so I am skipping those steps and let's jump on code directly.
Create virtual enviornment,
python3 -m venv envname
Install these packages:-
django
djangorestframework
djangorestframework-simplejwt
Add restframework in your installed apps in settings.py file:
INSTALLED_APPS = [
'rest_framework',
]
and add these settings for rest_framework and simpleJWT.
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework_simplejwt.authentication.JWTAuthentication',
)
}
SIMPLE_JWT = {
'ACCESS_TOKEN_LIFETIME': timedelta(days=15),
'AUTH_HEADER_TYPES': ('Bearer',),
'AUTH_TOKEN_CLASSES': ('rest_framework_simplejwt.tokens.AccessToken',),
}
Create Model for a student
class Student(models.Model):
auth = models.OneToOneField(User, on_delete=models.CASCADE, related_name='student_profile')
name = models.CharField(max_length=100)
email = models.EmailField(max_length=100)
def __str__(self):
return self.name
and now we will create user signup and user profile serializers for signup and login
from rest_framework import serializers
from userapp.models import Student
from django.contrib.auth.models import User
class UserSignupSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = ('first_name', 'last_name', 'email', 'password')
extra_kwargs = {
'first_name': {'required': True, 'allow_blank': False},
'last_name': {'required': True, 'allow_blank': False},
'email': {'required': True, 'allow_blank': False},
'password': {'required': True, 'allow_blank': False},
}
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = ('id', 'first_name', 'last_name', 'email', 'username')
now write views for utilise the serializers
from django.shortcuts import render
from .models import Student
from .serializers import UserSignupSerializer, UserSerializer
from rest_framework.decorators import api_view
from rest_framework.response import Response
from rest_framework import status
from django.contrib.auth.hashers import make_password
from django.contrib.auth.models import User
@api_view(['POST'])
def signup(request):
data = request.data
serializer = UserSignupSerializer(data=data)
if serializer.is_valid():
if not User.objects.filter(username=data['email']).exists():
user = User.objects.create(first_name=data['first_name'], last_name=data['last_name'], username=data['email'], email=data['email'], password=make_password(data['password']))
user.save()
student = Student.objects.create(auth=user, name=data['first_name'], email=data['email'])
return Response({'message':'User Created Successfully'}, status=status.HTTP_201_CREATED)
else:
return Response({'message':'User Already Exists'}, status=status.HTTP_400_BAD_REQUEST)
else:
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
@api_view(['GET'])
def login(request):
data = request.data
if User.objects.filter(username=data['email']).exists():
user = User.objects.get(username=data['email'])
if user.check_password(data['password']):
return Response(UserSerializer(instance=user).data, status=status.HTTP_200_OK)
else:
return Response({'message':'Invalid Password'}, status=status.HTTP_400_BAD_REQUEST)
else:
return Response({'message':'User Does Not Exist'}, status=status.HTTP_400_BAD_REQUEST)
Now map these views in urls.py
urlpatterns = [
path('signup/', views.signup, name='signup'),
path('login/', views.login, name='login'),
and for testing these endpoints use postman and pass these responses
for singup api
{
"first_name": "demo",
"last_name": "demo",
"email": "demo@gmail.com",
"password": "demo"
}
for login
{
"email": "demo@gmail.com",
"password": "demo"
}
Source Code
Source Code:- https://github.com/ShivamRohilllaa/DjangoRestFramework-UserAuthentication/
Thank You
Shivam Rohilla | Python Developer
DM me your queries:-
https://www.linkedin.com/in/shivamrohillaa/
Top comments (0)