Akshay
Akshay

Reputation: 2785

request.user always returns AnonymousUser - Django

I have an app authy_me and wrote a custom URL

url(r'^login/$', authy_views.log_me_in, name="login")

the log_me_in view has the following:

from django.contrib.auth.forms import AuthenticationForm
from django.contrib.auth.views import login as auth_login
def log_me_in(request):

    if request.user.is_staff and not has_2fa(request):
        logger.info('is staff but does not have 2FA, redirecting to Authy account creator')
        return redirect('admin/authy_me/authenticatormodel/')
    elif request.user.is_staff and has_2fa(request):
        logger.info("is staff and 2FA enabled redirecting to Authy verification")
        return redirect('2fa')
    elif not request.user.is_staff and not has_2fa(request):
        logger.info('is not staff and does not have 2FA')

    defaults = {
        'authentication_form': AuthenticationForm,
        'template_name': 'login.html',
    }
    return auth_login(request, **defaults)

When I print request.user I get it as AnonymousUser but the thing is that it was working and I did not change anything! I am not sure what the problem is.

Help!!

Upvotes: 2

Views: 2748

Answers (1)

Akash Wankhede
Akash Wankhede

Reputation: 618

You need to authenticate user before passing request to auth_login(),

from django.contrib.auth import authenticate

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

Check, If user is valid user,

if not user:
    return False

Now, you can pass your request to auth_login()

Hope this helps

Upvotes: 1

Related Questions