django-hijack
django-hijack is a Django app that enables administrators or authorized users to log in as another user, allowing them to work on behalf of that user without knowing their password. It provides both admin integration (via `hijack_admin`) and programmatic API. It is currently at version 3.7.7 and maintains an active release cadence, often aligning with Django's release cycle for compatibility.
Warnings
- breaking Django-hijack version 3.7.5 and later dropped support for Python 3.9 and Django versions older than 5.1. Ensure your project environment uses Python >=3.10 and Django >=5.1.
- gotcha The `hijack.middleware.HijackMiddleware` must be placed correctly in your `settings.py`'s `MIDDLEWARE` list. It should come *after* `django.contrib.sessions.middleware.SessionMiddleware` and `django.contrib.auth.middleware.AuthenticationMiddleware` to ensure proper session and authentication context.
- gotcha Implementing robust permission checks for who can initiate a hijack is critical. Merely checking `request.user.is_superuser` might be insufficient in production environments and poses a significant security risk if not carefully managed. Use `HIJACK_CAN_HIJACK` or a custom `can_hijack` method on the user model.
- gotcha Ensure users have a clear and visible way to release a hijack session. This is typically done via the notification bar provided by django-hijack or a direct link to `reverse('hijack:release')`. Without it, users might be stuck impersonating another user.
Install
-
pip install django-hijack django-hijack-admin
Imports
- HijackMiddleware
from hijack.middleware import HijackMiddleware
- hijack_user
from hijack.helpers import hijack_user
- release_hijack
from hijack.helpers import release_hijack
Quickstart
import os
from django.conf import settings
# Configure settings for a minimal Django setup (for demonstration)
# In a real project, these go into your settings.py
if not settings.configured:
settings.configure(
DEBUG=True,
SECRET_KEY=os.environ.get('DJANGO_SECRET_KEY', 'a-very-secret-key-for-dev'),
INSTALLED_APPS=[
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'hijack',
'hijack_admin', # For admin integration
],
MIDDLEWARE=[
'django.contrib.sessions.middleware.SessionMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'hijack.middleware.HijackMiddleware', # Essential for hijacking
'django.contrib.messages.middleware.MessageMiddleware', # Needed for hijack messages
],
ROOT_URLCONF=__name__,
TEMPLATES=[
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
],
HIJACK_LOGIN_REDIRECT_URL='/admin/', # Redirect after hijacking
HIJACK_LOGOUT_REDIRECT_URL='/admin/', # Redirect after releasing
STATIC_URL='/static/',
DATABASES={'default': {'ENGINE': 'django.db.backends.sqlite3', 'NAME': ':memory:'}},
)
import django
django.setup()
from django.urls import path, include
from django.contrib import admin
from django.contrib.auth import get_user_model
from django.shortcuts import redirect
from hijack.helpers import hijack_user
User = get_user_model()
def hijack_example_view(request, user_id):
# This is a very basic example; implement robust permission checks!
if not request.user.is_superuser: # Only superusers can initiate hijack here
return redirect('/')
try:
user_to_hijack = User.objects.get(pk=user_id)
hijack_user(request, user_to_hijack)
return redirect(settings.HIJACK_LOGIN_REDIRECT_URL)
except User.DoesNotExist:
# Handle case where user_id does not exist
return redirect('/admin/')
urlpatterns = [
path('admin/', admin.site.urls),
path('hijack/', include('hijack.urls')), # Essential for hijack actions and release
path('start-hijack/<int:user_id>/', hijack_example_view, name='start_hijack'),
path('', lambda request: redirect('/admin/'), name='home') # Simple homepage redirect
]
# To run this (in a real Django project):
# 1. Add 'hijack' and 'hijack_admin' to INSTALLED_APPS
# 2. Add 'hijack.middleware.HijackMiddleware' to MIDDLEWARE (after Auth/Session)
# 3. Include 'hijack.urls' in your project's urls.py
# 4. Implement a view like `hijack_example_view` with proper permission checks
# and link it in urls.py to initiate hijacks programmatically.
# 5. Ensure `HIJACK_LOGIN_REDIRECT_URL` and `HIJACK_LOGOUT_REDIRECT_URL` are set.
# Example usage in a shell after setting up and running server:
# Go to /admin/, log in as superuser. Then navigate to /start-hijack/<user_id>/