gamer
gamer

Reputation: 613

Use Email instead of Username to authenticate user

I know this answer have a lot of answers and many different ways to do that , But As of today in Django 3 I want to know which one is best and reliable way to use only email for authentication .

EDIT: I found a link but not confirmed if it have any drawback

https://www.fomfus.com/articles/how-to-use-email-as-username-for-django-authentication-removing-the-username

Upvotes: 0

Views: 360

Answers (2)

satyajit
satyajit

Reputation: 694

You can create your custom serializers and then put the logic to check via authenticated by email like this:

serializers.py :


from rest_framework import serializers
from django.db.models import Q
from django.contrib.auth import get_user_model
User = get_user_model()

class UserLoginSerializers(serializers.ModelSerializer):
    email = serializers.CharField()
    password = serializers.CharField(write_only=True)
    class Meta:
        model = User
        fields = [
            "email",
            "password",
        ]

    def validate(self, data):
        email = data['email']
        password = data['password']
        user_queryset = User.objects.filter(Q(email__iexact=email) | Q(username__iexact=email)).distinct()

        if user_queryset.exists() and user_queryset.count() == 1:
            user_set = user_queryset.first()
            if user_set.check_password(password):
                user = user_set
                print(user)

            else:
                raise serializers.ValidationError("Incorrect Password!")

        else:
            raise serializers.ValidationError("Not Valid User!")

        return data

views.py :

from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.status import (
    HTTP_200_OK, HTTP_201_CREATED, HTTP_400_BAD_REQUEST
    )
from .serializers import (UserLoginSerializers)

class UserLoginAPIView(APIView):
    serializer_class = UserLoginSerializers

    def post(self, request, format=None):
        data = request.data
        user_serilaizer = UserLoginSerializers(data=data)
        if user_serilaizer.is_valid():
            new_data = user_serilaizer.data
            return Response(new_data, status=HTTP_200_OK)
        else:
            return Response({"msg":"invalid user"}, status=HTTP_400_BAD_REQUEST)

urls.py :

from django.urls import path

from account.api.views import (UserLoginAPIView)

urlpatterns = [
    path('api/login', UserLoginAPIView.as_view(), name='login_api'),
]

Upvotes: 1

from_the_docs
from_the_docs

Reputation: 117

from_the_docs:

USERNAME_FIELD

A string describing the name of the field on the user model that is used as the unique identifier. This will usually be a username of some kind, but it can also be an email address, or any other unique identifier.

Upvotes: 0

Related Questions