LoginAsForm - Login as any User without a password

 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 5 years, 6 months ago
  2. newforms self-contained login form by miracle2k 6 years, 9 months ago
  3. Get the referer view of a request by arthurfurlan 4 years, 11 months ago
  4. Memento by manelvf 3 years, 3 months ago
  5. Require login across entire site by SuperJared 7 years ago

Comments

xhenxhe (on June 22, 2011):

This is awesome. Just what I needed. Thanks!

#

(Forgotten your password?)