How can I login users without password in Django?

1.64K viewsDjango

How can I login users without password in Django?

I hope you can help me figure out the best way to implement a manual (server-side initiated) login without using the password. Let me explain the workflow:

  • User registers
  • Thank you! An email with an activation link has been sent blablabla
  • (Account now exists but is marked not enabled)
  • The user opens the email, clicks the link
  • (Account is enabled)
  • Thank you! You can now use the site

What I’m trying to do is log in to the user after he has clicked the email link so he can start using the website right away.

I can’t use his password since it’s encrypted in the DB, is the only option writing a custom authentication backend?

Farjanul Nayem Answered question July 19, 2022

There are times when you are not worried about user authentication but still want to have each user sees only his/her stuff. Then you need a way to login to a user without the password.

Normally, when logging a user with the password, authenticate() has to be called before login():

username = request.POST['username']
password = request.POST['password']
user = authenticate(username=username, password=password)
login(request, user)

What authenticate does is to add an attribute called backend with the value of the authentication backend, take a look at the line of the source code. The solution is to add this attribute yourself:

#assuming the user name is passed in via get
username = self.request.GET.get('username')
user = User.objects.get(username=username)
 #manually set the backend attribute
user.backend = 'django.contrib.auth.backends.ModelBackend'
login(request, user)

That’s it!

Farjanul Nayem Changed status to publish July 19, 2022