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': '/'}),
)
Comments
This needs to check that you're not sudoing to a superuser. Otherwise it could be a massive escalation vulnerability.
#
absolutely, but no one runs random code in their production environment without undertanding it right? right?
#
If you change the test to
u.is_superuserit 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:#
yes, that's the correct thing to do
#