1

I have this code:

 from django.contrib.auth import logout, login, authenticate
 ...
   if User.objects.filter(email=email).exists():
        existing_user = User.objects.get(email=email)

        user = authenticate(username=existing_user.username, password=existing_user.password)

        login(request, user)

According to the docs, this should work, but it doesn't, it gives me the error:

request.session[SESSION_KEY] = user._meta.pk.value_to_string(user) AttributeError: 'AnonymousUser' object has no attribute '_meta'

Maybe the problem happens becouse I am using JWT Authentication with Django Rest Framework? It is just an django-powered API, so I guess it is a different scenario, but I don't understand what could be causing the problem.

4
  • 4
    Show the full traceback. But your code makes no sense; authenticate is what gets the user, by comparing with the hashed password saved in the database. There is no point in getting the user separately, and here authenticate will always fail. Commented Jan 12, 2017 at 18:03
  • Hi @DanielRoseman . Then how can I login the user in the view without having its password at hand?. The app sends me a facebook token, I confirm the token with Fb's API, then, I get the email and check if it already exists (the rest is in the code I pasted), if the a user with that email exists, I need to login that user. I thought that using authenticate and login would solve it but now I see it doesn't. Commented Jan 12, 2017 at 18:21
  • 2
    You can implement your own Authentication Backend to authenticate user without password. There is an example with token authentication here - docs.djangoproject.com/en/1.10/topics/auth/customizing/… . Commented Jan 12, 2017 at 18:42
  • 1
    Or, use one of the third-party libraries that integrate Facebook login with Django: django-allauth or python-social-auth. Commented Jan 12, 2017 at 18:52

1 Answer 1

2

In DRF user should be authenticated inside Authentication class. This library provides one for JWT auth. It provides both token generation and verification.

You will get user as self.request.user in your View or ViewSet class. You just need to allow JWT auth:

class ExampleView(APIView):
    authentication_classes = (BasicAuthentication, JSONWebTokenAuthentication)

Or better set is as DEFAULT_AUTHENTICATION_CLASSES as documented here.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.