Django Sudo

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
from django.shortcuts import get_object_or_404
from django.contrib.auth import SESSION_KEY
from django import http
from django.contrib.auth.models import User
from django.contrib.auth.decorators import user_passes_test

@user_passes_test(lambda u: u.is_staff)
def su(request, username, redirect_url='/'):
    su_user = get_object_or_404(User, username=username)
    if su_user.is_active:
        request.session[SESSION_KEY] = su_user.id
        return http.HttpResponseRedirect(redirect_url)

# In urls.py
from django.conf.urls.defaults import url

urlpatterns += patterns('',
    url(r'^su/(?P<username>.*)/$', 'my_app.views.su', {'redirect_url': '/'}),
)

More like this

  1. Restrict staff access to admin pages by slink 3 years, 6 months ago
  2. staff_or_404 Decorator by bkeating 2 years, 5 months ago
  3. Email or username authentication with masquerading by petrilli 4 years, 9 months ago
  4. is_staff decorator by munhitsu 5 years, 8 months ago
  5. Fixture for test users by V 5 years, 7 months ago

Comments

leosh (on December 14, 2011):

This needs to check that you're not sudoing to a superuser. Otherwise it could be a massive escalation vulnerability.

#

readevalprint (on December 20, 2011):

absolutely, but no one runs random code in their production environment without undertanding it right? right?

#

gisle (on January 13, 2012):

If you change the test to u.is_superuser it should be safe, shouldn't it? You can also remove the if-test from the function body by adding the condition to the filter. That makes the view function:

@user_passes_test(lambda u: u.is_superuser)
def su(request, username, redirect_url='/'):
    su_user = get_object_or_404(User, username=username, is_active=True)
    request.session[SESSION_KEY] = su_user.id
    return http.HttpResponseRedirect(redirect_url)

#

readevalprint (on December 31, 2012):

yes, that's the correct thing to do

#

(Forgotten your password?)