Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to manually authenticate after get django user?

Im writing a facebook-connect app that login user after authenticate session on facebook, question is how can i authenticate user on django after get user object?

user = User.objects.get(email=email)
user = authenticate(username=user.username, password=user.password)
login(request, user)

Is there another way to achieve this ?

like image 375
marman Avatar asked Jan 21 '11 03:01

marman


People also ask

How do I authenticate a user in Django?

from django.contrib.auth import authenticate, login def my_view(request): username = request.POST['username'] password = request.POST['password'] user = authenticate(request, username=username, password=password) if user is not None: login(request, user) # Redirect to a success page. ... else: # Return an 'invalid ...

How do I know if a user is authenticated Django?

By calling request. user, we are able to access the user that is currently logged in. We then can use the is_authenticated property to determine if a user is currently authenticated (logged into the account). Basically, we do this all in the views.py file, which is the file where our main Python code always goes.


3 Answers

You don't actually need to authenticate() first if you do this (but I didn't tell you!):

user.backend = 'django.contrib.auth.backends.ModelBackend'

login(request, user)

like image 198
Lyle Pratt Avatar answered Sep 20 '22 13:09

Lyle Pratt


There are two things you should look at and be aware of based on your question and example.

First, the way you handle alternate authentication methods (e.g. facebook oauth) are authentication backends. You can look at djangopackages.com for existing options or write your own. The backend(s) you have configured are what will define what parameters authenticate() is expecting to receive (e.g. a facebook backend wouldn't expect a password as a password doesn't make sense in that context).

Second, doing user.password won't get you the user's actual password. As a security measure, Django stores passwords as salted one-way hashes. This means that, by design, you cannot determine a user's password based on what is stored in the database.

like image 44
SeanOC Avatar answered Sep 20 '22 13:09

SeanOC


authenticate() and login() each provide different tasks, and both (or the equivalent pulled from the Django code and updated for each version of Django) are required in order to log a user in.

like image 28
Ignacio Vazquez-Abrams Avatar answered Sep 23 '22 13:09

Ignacio Vazquez-Abrams