Login

LoginAsForm - Login as any User without a password

Author:
johnboxall
Posted:
June 4, 2009
Language:
Python
Version:
1.0
Tags:
forms login auth authenticate form auth.contrib
Score:
7 (after 7 ratings)

Sometimes the only way to reproduce a bug on a production site is to login as the User who encountered it. This form allows you to login as any user on the site.

Usage

@staff_member_required
def login_as(request, template="login_as.html"):
    data = request.POST or None
    form = LoginAsForm(data, request=request)
    if form.is_valid()
        form.save()
        return HttpResponseRedirect(settings.LOGIN_REDIRECT_URL)
    ...
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
from django.contrib.auth import login, get_backends
from django.contrib.auth.models import User

class LoginAsForm(forms.Form):
    """
    Sometimes to debug an error you need to login as a specific User.
    This form allows you to log as any user in the system. You can restrict
    the allowed users by passing a User queryset paramter, `qs` when the
    form is instantiated.
    """
    user = forms.ModelChoiceField(User.objects.all())
    
    def __init__(self, data=None, files=None, request=None, qs=None, *args,
                 **kwargs):
        if request is None:
            raise TypeError("Keyword argument 'request' must be supplied")                 
        super(LoginAsForm, self).__init__(data=data, files=files, *args, **kwargs)
        self.request = request
        if qs is not None:
            self.fields["user"].queryset = qs


    def save(self):
        user = self.cleaned_data["user"]

        # In lieu of a call to authenticate()
        backend = get_backends()[0]
        user.backend = "%s.%s" % (backend.__module__, backend.__class__.__name__)
        login(self.request, user)
        
        message = "Logged in as %s" % self.request.user        
        self.request.user.message_set.create(message=message)

More like this

  1. SignedForm: CSRF-protect forms with a hidden token field by exogen 6 years, 6 months ago
  2. newforms self-contained login form by miracle2k 7 years, 8 months ago
  3. Get the referer view of a request by arthurfurlan 5 years, 11 months ago
  4. Memento by manelvf 4 years, 2 months ago
  5. Require login across entire site by SuperJared 8 years ago

Comments

xhenxhe (on June 22, 2011):

This is awesome. Just what I needed. Thanks!

#

Please login first before commenting.