Login

Django Sudo

Author:
readevalprint
Posted:
December 14, 2011
Language:
Python
Version:
Not specified
Score:
3 (after 5 ratings)

Staff can log in as a user, from a url to help with customer support or debugging.

 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. Template tag - list punctuation for a list of items by shapiromatron 10 months, 3 weeks ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 11 months ago
  3. Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
  5. Help text hyperlinks by sa2812 1 year, 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

#

Please login first before commenting.