3

I created a user with

 new_user = create_user(
            username=username, email=email, first_name=first_name,
            last_name=last_name)
new_user.set_unusable_password()

But the authenticate() returns None for that user

auth_user = authenticate(
            username=new_user.username, password=new_user.password)

Login fails for that user

AttributeError: "'AnonymousUser' object has no attribute 'backend'"

How should I go about authenticating these users?

kguest
  • 3,804
  • 3
  • 29
  • 31
navyad
  • 3,752
  • 7
  • 47
  • 88

2 Answers2

1

Try writing a custom authentication backend that doesn't require password.

Try this:

You can then simply use your custom authenticate function:

auth_user = authenticate(username=new_user.username)
Community
  • 1
  • 1
Bidhan Bhattarai
  • 1,040
  • 2
  • 12
  • 20
1

You need to authenticate(**credential) the user when the user having no password.

django.contrib.auth.authenticate() is to authenticate a given username and password.

So you should create your own authentication backend given only username. Basically the only authentication you need to do is to check if the user is in the database. But it is pretty obvious that the user is in the database. So alternatively, you can just fake the authentication process by setting the user.backend = 'django.contrib.auth.backends.ModelBackend' directly.

Followed by login() to login a given user.

When you’re manually logging a user in, you must successfully authenticate the user with authenticate() before you call login(). authenticate() sets an attribute on the User noting which authentication backend successfully authenticated that user (see the backends documentation for details), and this information is needed later during the login process.

def autologin(request):

    # ...
    # ...
    # ...

    new_user = create_user(
        username=username,
        email=email,
        first_name=first_name,
        last_name=last_name)
    user = authenticate(new_user)
    if user.is_authenticated():
        login(request, user)
    return render(request, 'template.html')
Yeo
  • 11,416
  • 6
  • 63
  • 90
  • for the `user.backend` it is good if you can avoid hard coding the backend. and use the `django.conf.settings.AUTHENTICATION_BACKEND` instead – Yeo May 04 '15 at 07:30