having trouble getting user authentication to work in Python

Viewed 23

I am building a django/react app and having trouble with the backend user authentication, have not been able to debug the issue.

After successfully creating an account I am now trying to login. This is the the login route I have built.

@csrf_exempt
@api_view(['POST'])
def loginUser(request):
    data = request.data
    if request.method == 'POST':
        email = data['email']
        password = data['password']

        try:
            user = User.objects.get(email=email)
        except:
            message = {'detail': 'email does not match a user'}
            return Response(message, status=status.HTTP_400_BAD_REQUEST)

    username = user.username
    user = authenticate(request, username=username, password=password)
    
    # Returning correct username and password
    print('This is the username:', username)
    print('This is the password:', password)

    # returning None, even though username and password are matching the info used for signup. (confirmed on admin page)
    print('This is the user:', user)

    

    if user is not None:
        login(request, user)
        serializer = UserSerializer(user, many=False)
        message = {'detail': 'user has been logged in'}
        return Response(serializer.data)
    else:
        message = {'detail': 'Username or password is incorrect'}
        return Response(message, status=status.HTTP_400_BAD_REQUEST)

Any help would be greatly appreciate it since I have been stuck on this for 2 days.

1 Answers

It may be due to the Try-Except or due to the fact that you use email instead of username (but I dont think that matters). You could try something like this:

from django.contrib.auth import authenticate
from django.contrib.auth.models import auth

def loginUser(request):
    if request.method == 'POST':
        username = request.POST['name']
        password = request.POST['password']

        user = authenticate(request, username=username, password=password)

        if user is not None:
            auth.login(request, user)
            return redirect('index')
        else:
            messages.info(request, 'Invalid Username or Password')
            return redirect('login')
    else:
        return render(request, 'login.html')

Hopefully this helps.

If you use this code and the problem still persists, it could be that your template or urls may not be correct.

Related