kpako1998
kpako1998

Reputation: 161

During testing, when tested with correct user input, I get "Invalid credentials"

I am using just phone number alone as the only field for login. Authentication does not seem to work well even when supplied with correct user input.

ERROR WHEN I CONFIGURE THE AUTH BACKENDS:

 File "C:\Users\UBITEK\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\conf\__init__.py", line 161, in __init__
    raise ImproperlyConfigured("The SECRET_KEY setting must not be empty.")
django.core.exceptions.ImproperlyConfigured: The SECRET_KEY setting must not be empty.
@csrf_exempt
@api_view(["POST"])
@permission_classes((AllowAny,))
def logins(request):
    phone_number = request.data.get("phone_number")
    if phone_number is None:
        return Response({'error': 'Please provide your phone number'},
                        status=HTTP_400_BAD_REQUEST)
    user = authenticate(phone_number=phone_number)
    if not user:
        return Response({'error': 'Invalid Credentials'},
                        status=HTTP_404_NOT_FOUND)
    token, _ = Token.objects.get_or_create(user=user)
    return Response({'token': token.key},
                    status=HTTP_200_OK)

backends.py

from django.contrib.auth.backends import ModelBackend
from .models import User

class LoginBackend(ModelBackend):
    def authenticate(self, request, **kwargs):
        phone_number= kwargs['phone_number']
        user = User.objects.get(phone_number=phone_number)
        if user:
            return user
        else:
            return None

settings.py

from .backends import LoginBackend
from django.contrib.auth.backends import ModelBackend
AUTHENTICATION_BACKENDS = ['django.contrib.auth.backends.ModelBackend',
    'findr.backends.LoginBackend']

Upvotes: 0

Views: 235

Answers (1)

KrazyMax
KrazyMax

Reputation: 959

Regarding the comments on your question, I suggest you to write your own django authentification backend:

https://docs.djangoproject.com/en/3.0/topics/auth/customizing/#writing-an-authentication-backend

You have to tell Django how someone should be authenticated:

  • with username and password?
  • with phone_number and password?

This has to be explicit (and do not forget to add this new backend to your settings.py file!).

Upvotes: 1

Related Questions