On May 14, 1:17 pm, Sam Chuparkoff <s...@sadach.org> wrote: > On Wed, 2009-05-13 at 05:21 -0700, DaveBrueckwrote: > > Has anyone in this group implemented any sort of login-as-another-user > > functionality with Django? > > I implemented "sticky superuser logins" about a year ago (the last > time I worked with django until now), so I can attest it is a neat > trick, at least for demos. But I probably don't undertand it > anymore. And unfortunately, a brief look at the code shows some > changes since django-gis r7229, which I was using then. > > I was working under the premise that the only special priviledge the > superuser retains after changing effective id to another user is the > ability to login as another user without a password. But nothing > prevents granting other special powers. Anyhow I too suspect someone > else has thought about this, no? > > My approach was to hack a new SUPERUSER_SESSION_KEY and > SUPERUSER_BACKEND_SESSION_KEY into contrib/auth/__init__.py , and add > a new 'superuser' attribute in AuthenticationMiddleware. I guessed > this wasn't the most clever way but didn't want to confuse myself too > much, because I still had a logical consequences to deal with. If > you're interested in seeing some of this code, reply directly.
Thanks for the reply Sam. For the sake of writing this down somewhere, here's what I ended up doing: 1) Created a new authentication backend that authenticates based on a user ID: class LoginAsBackend(ModelBackend): '''Special-case backend for when the admin needs to login as another user''' def authenticate(self, id=None, curUser=None, forReals=False, **kwargs): # we require a few extra args just to prevent the accidental use of this backend # in other contexts if id is None or not forReals or curUser is None: return None try: return User.objects.get(id=id) except User.DoesNotExist: return None 2) Mark the user's session when we login as another user: user = authenticate(id=id, curUser=r.user, forReals=True) # this calls our special backends.LoginAsBackend assert user login(r, user) r.session['was_admin'] = True 3) Use a special decorator on all views that are viewable by site admins: def admin_required(func): def decorated(req, *args, **kwargs): if req.user.has_perm('is_admin') or req.session.get ('was_admin'): return func(req, *args, **kwargs) return HttpResponseRedirect(settings.LOGIN_URL) return decorated It's not the prettiest solution, but it seems to work. Take care, -Dave --~--~---------~--~----~------------~-------~--~----~ You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-users@googlegroups.com To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/django-users?hl=en -~----------~----~----~----~------~----~------~--~---