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.

Alejandro Veintimilla
  • 10,743
  • 23
  • 91
  • 180
  • 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. – Daniel Roseman Jan 12 '17 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. – Alejandro Veintimilla Jan 12 '17 at 18:21
  • 2
    You can implement your own Authentication Backend to authenticate user without password. There is an example with token authentication here - https://docs.djangoproject.com/en/1.10/topics/auth/customizing/#writing-an-authentication-backend . – nmb.ten Jan 12 '17 at 18:42
  • 1
    Or, use one of the third-party libraries that integrate Facebook login with Django: django-allauth or python-social-auth. – Daniel Roseman Jan 12 '17 at 18:52

1 Answers1

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.

Raz
  • 7,508
  • 4
  • 27
  • 25