0

I have an API view (using DJ Rest Framework) that I am posting to via React in my frontend. request.user.is_authenticated returns True here (and returns the user I have attempted to sign-in as), however, in my view for rendering the login page template, request.user.is_authenticated returns False, and the user object is an AnonymousUser.

Why is this?

I've checked this question, but it only has information on templates.

Here's the API view code:

@api_view(['POST'])
def login_api_view(request, *args, **kwargs):
    if request.user and request.user.is_authenticated:
        return Response({'message': 'User is already authenticated'}, status=400)

    username = request.data.get('username')
    password = request.data.get('password')
    if username is None or password is None:
        return Response({'message': 'Please specify a username and password'}, status=400)

    user = authenticate(request, username=username, password=password)
    if user is None:
        return Response({'message': 'Invalid credentials'}, status=401)
    login(request, user)

    return Response({'message': 'Successfully authenticated user'}, status=200)

And here's the code for the template:

def login_view(request, *args, **kwars):
    if request.user.is_authenticated:
        return redirect('/')
    
    return render(request, 'users/login.html')
sebtheiler
  • 2,159
  • 3
  • 16
  • 29
  • 1
    I don't get it, is `login_view` being called by the `login_api_view` function? – Rfroes87 Sep 07 '20 at 23:05
  • No, `login_view` is what is rendering the login form page. In my React code, I'm POSTing an XHR to `login_api_view` with the provided credentials. – sebtheiler Sep 07 '20 at 23:16
  • Just to make sure, is the decorator for the `login_view` GET request missing or is it just omitted from your question? – Rfroes87 Sep 07 '20 at 23:21
  • 1
    You don't need decorator's for regular, non-rest-framework, Django views, right? Sorry, I'm a bit of a newbie. If you do, I have no clue how any of my code is working. – sebtheiler Sep 07 '20 at 23:24
  • Sorry, I think you're right. I could be misremembering things. – Rfroes87 Sep 07 '20 at 23:27

1 Answers1

0

After stopping work on this for a few days and coming back to it, I've found that my Dev Authentication class (rest_framework.authentication.BasicAuthentication) was messing with my results.

sebtheiler
  • 2,159
  • 3
  • 16
  • 29