Package: django-impersonate
django-impersonateSimple application to allow superusers to “impersonate” other
non-superuser accounts.Version:1.9.2Project Links:Issues-Mailing
List-ContributingAuthor:Peter Sanchez (https://petersanchez.com)Python / Django SupportPython 3.7+ for Django versions 3.2+Note:As of version 1.4 we are only officially supporting Python and
Django versions that are supported by the official projects. So if a
Python or Django version is End-of-Life’d, then we will no longer
support that version either.DependenciesDepends on your project using the django.contrib.session framework.NOTE:Version 1.6has officially removed support for the old settings
format. Please see thesettingssection for how
settings should be configured.Version 1.5 is now only officially supporting Django’s 1.11, 2.2,
and 3.0Version 1.4 is now officially supporting Python 3.6+ and Django
1.11+Version 1.3 adds a settings format change.Please see the
Settings section for details.Version 1.0 adds new functionality by default.Please see theDISABLE_LOGGINGsettings option.If you need to use this with Django older than 1.8, please use
version django-impersonate == 1.0.1If you need to use this with Django older than 1.7, please use
version django-impersonate == 0.9.2Version 0.9.2 partially reverts work completed in version 0.9.1.This is because work done to address a request inIssue
#17broke default behavior for all previous versions.Issue
#24was opened and the fix was released in 0.9.2 to address it. Please
see the newUSE_HTTP_REFERERsettings option.If you need to use this with Django older than 1.4, please use
version django-impersonate == 0.5.3InstallationPIP:pip install django-impersonateBasic Manual Install:$ python setup.py build
$ sudo python setup.py installAlternative Install (Manually):Place impersonate directory in your Python path. Either in your Python
installs site-packages directory or set your $PYTHONPATH environment
variable to include a directory where the impersonate directory lives.UseAddimpersonateto your INSTALLED_APPSAddimpersonate.middleware.ImpersonateMiddlewareto yourMIDDLEWAREsetting.Addimpersonate.urlssomewhere in your url structure. Example:urlpatterns = patterns('',
    url(r'^admin/', include(admin.site.urls)),
    url(r'^impersonate/', include('impersonate.urls')),
    ... (all your other urls here) ...
)Note:TheImpersonationMiddlewareclass should be placed AFTER
thedjango.contrib.auth.*middleware classesFunctionalityYou can now impersonate another user by hitting the following path:/impersonate/<user-id>/Replace <user-id> with the user id of the user you want to impersonate.While in impersonation “mode” therequest.userobject will have anis_impersonateattribute set toTrueas well asimpersonator(and alsorequest.impersonator) set to the original user. So if you
wanted to check in your templates or view, you just do something
like…:{% if user.is_impersonate %} .... {% endif %}The original user is available asuser.impersonatororrequest.impersonator:{{ request.user }} ({{ request.impersonator }})The real user is available asrequest.real_user- this is equivalent
to callinggetattr(request, 'impersonator', request.user):assert request.real_user == getattr(request, 'impersonator', request.user)You can reference this URL withreverseor the{% url %}template tag asimpersonate-startand expects the argument of the
user ID. Example:reverse('impersonate-start', args=[user.id])
reverse('impersonate-start', uid=user.id)To remove the impersonation, hit the following path:/impersonate/stop/You can reference this URL withreverseor the{% url %}template tag asimpersonate-stop. When you call this URL, you will
be redirected to the page that you used to start impersonating a user
(eg, some search results or the user list).To list all users you can go to:/impersonate/list/This will render the templateimpersonate/list_users.htmland will
pass the following in the context:users- queryset of all userspaginator- Django Paginator instancepage- Current page of objects (from Paginator)page_number- Current page number, defaults to 1You can reference this URL withreverseor the{% url %}template tag asimpersonate-list.To search all users you can go to:/impersonate/search/This will render the template ‘impersonate/search_users.html’ and will
pass the following in the context:users- queryset of all userspaginator- Django Paginator instancepage- Current page of objects (from Paginator)page_number- Current page number, defaults to 1query- The search query that was enteredThe view will expect a GET request and look for theqvariable being
passed. If present, it will search the user entries with the value ofq. The default fields searched are:User.username,User.first_name,User.last_name,User.emailYou can reference this URL withreverseor the{% url %}template tag asimpersonate-search.To allow some users to impersonate other usersYou can optionally allow only some non-superuser and non-staff users to
impersonate by adding aCUSTOM_ALLOWsetting option. Create a
function that takes a request object, and based on your rules, returnsTrueif the user is allowed to impersonate or not.To limit what users a user can impersonateBy, optionally, setting theCUSTOM_USER_QUERYSEToption you can
control what users can be impersonated. It takes a request object of the
user, and returns a QuerySet of users. This is used when searching for
users to impersonate, when listing what users to impersonate, and when
trying to start impersonation.SignalsIf you wish to hook into the impersonation session (for instance, in
order to audit access), there are two signals that are fired by
django-impersonate, at the beginning and end of a session:session_begin- sent when calling theimpersonateviewsession_end- sent when calling thestop_impersonateviewBoth of these signals send the same arguments:sender- this is a Django signal requirement, and is always set
to Noneimpersonator- a reference to the User object of the person doing
the impersonationimpersonating- a reference to the User object of the person
being impersonatedrequest- the Django HttpRequest object from which the
impersonation was invokedThe request object is included as it contains pertinent information that
you may wish to audit - such as client IP address, user-agent string,
etc.For an example of how to hook up the signals, see the relevant test -test_successful_impersonation_signals.Thesession_endsignal will only be fired if the impersonator
explicitly ends the session.SettingsThe following settings are available for django-impersonate. All
settings should be set as variables in a dictionary assigned to the
attribute namedIMPERSONATE.For example:IMPERSONATE = {
    'REDIRECT_URL': '/some-path/',
    'PAGINATE_COUNT': 10,
}Here are the options available…REDIRECT_URLThis is the URL you want to be redirected toafteryou have chosen to
impersonate another user. If this is not present it will check for theLOGIN_REDIRECT_URLsetting and fall back to ‘/’ if neither is
present. Value should be a string containing the redirect path.READ_ONLYA boolean that if set toTrueany requests that are not eitherGETorHEADorOPTIONSwill result in a “Bad Request”
response (status code 405). Use this if you want to limit your
impersonating users to read only impersonation sessions.Value should be a boolean, defaults toFalseIf theCUSTOM_READ_ONLYis set, then that custom function is used,
and this setting is ignored.CUSTOM_READ_ONLYA string that represents a function (e.g.module.submodule.mod.function_name) that allows more fine grained
control over who has read only access. It takes one argument, the
request object, and should return True to restrict the user to only
allowGET,HEADandOPTIONSrequests.It is optional, and if it is not present,READ_ONLYsetting value
applies.USE_HTTP_REFERERIf this is set toTrue, then the app will attempt to be redirect you
to the URL you were at when the impersonation began once you havestoppedthe impersonation. For example, if you were at the url
‘/foo/bar/’ when you began impersonating a user, once you end the
impersonation, you will be redirected back to ‘/foo/bar/’ instead of the
value inREDIRECT_URL.Value should be a boolean, defaults toFalsePAGINATE_COUNTThis is the number of users to paginate by when using the list or search
views. This defaults to 20. Value should be an integer.REQUIRE_SUPERUSERIf this is set toTrue, then only users who haveis_superuserset toTruewill be allowed to impersonate other users. Default isFalse. IfFalse, then anyis_staffuser will be able to
impersonate other users.Note:Regardless of this setting, ais_staffuser willnotbe allowed to impersonate ais_superuseruser.Value should be a booleanIf theCUSTOM_ALLOWis set, then that custom function is used, and
this setting is ignored.ALLOW_SUPERUSERBy default, superusers cannot be impersonated; this setting allows for
that.Note:Even when this is true, only superusers can impersonate other
superusers, regardless of the value of REQUIRE_SUPERUSER.Value should be a boolean and the default isFalse.URI_EXCLUSIONSSet to a list/tuple of url patterns that, if matched, user impersonation
is not completed. It defaults to:(r'^admin/',)If you do not want to use even the default exclusions then set the
setting to an empty list/tuple.CUSTOM_USER_QUERYSETA string that represents a function (e.g.module.submodule.mod.function_name) that allows more fine grained
control over what users a user can impersonate. It takes one argument,
the request object, and should return a QuerySet. Only the users in this
queryset can be impersonated.This function will not be called when the request has an unauthorised
users, and will only be called when the user is allowed to impersonate
(cf.REQUIRE_SUPERUSERandCUSTOM_ALLOW).Regardless of what this function returns, a user cannot impersonate a
superuser, even if there are superusers in the returned QuerySet.It is optional, and if it is not present, the user can impersonate any
user (i.e. the default isUser.objects.all()).CUSTOM_ALLOWA string that represents a function (e.g.module.submodule.mod.function_name) that allows more fine grained
control over who can use the impersonation. It takes one argument, the
request object, and should return True to allow impersonation.
Regardless of this setting, the user must be logged in to impersonate.
If this setting is used,REQUIRE_SUPERUSERis ignored.It is optional, and if it is not present, the previous rules about
superuser andREQUIRE_SUPERUSERapply.REDIRECT_FIELD_NAMEA string that represents the name of a request (GET) parameter which
contains the URL to redirect to after impersonating a user. This can be
used to redirect to a custom page after impersonating a user. Example:# in settings.py
IMPERSONATE = {'REDIRECT_FIELD_NAME': 'next'}

# in your template
<a href="{% url 'impersonate-list' %}?next=/some/url/">switch user</a>To return always to the current page after impersonating a user, use
request.path:`<a href="{% url 'impersonate-list' %}?next={{request.path}}">switch user</a>`Each use case is different so obviously set the next value to whatever
your case requires.SEARCH_FIELDSArray of user model fields used for building searching query. Default
value is [User.USERNAME_FIELD,first_name,last_name,email]. If the User model doesn’t have theUSERNAME_FIELDattribute, it falls back to ‘username’ (< Django 1.5).LOOKUP_TYPEA string that represents SQL lookup type for searching users by query on
fields above. It isicontainsby default.DISABLE_LOGGINGA boolean that can be used to disable the logging of impersonation
sessions. By default each impersonationsession_beginsignal will
create a newImpersonationLogobject, which is closed out (duration
calculated) at the correspondingsession_endsignal.It is optional, and defaults to False (i.e. logging is enabled).MAX_FILTER_SIZEThe max number of items acceptable in the admin list filters. If the
number of items exceeds this, then the filter list is the size of the
settings value. This is used by the “Filter by impersonator” filter.It is optional, and defaults to 100.ADMIN_DELETE_PERMISSIONA boolean to enable/disable deletion of impersonation logs in the Django
admin.Default isFalseADMIN_ADD_PERMISSIONA boolean to enable/disable ability to add impersonation logs in the
Django admin.Default isFalseADMIN_READ_ONLYA boolean to enable/disable “read only” mode of impersonation logs in
the Django admin. Generally you want to leave this enabled otherwise
admin users can alter logs within the Django admin area.Default isTrueMAX_DURATIONA number specifying the maximum allowed duration of impersonation
sessions inseconds.Default isNoneAdminAs of version 1.3 django-impersonate now includes a helper admin mixin,
located atimpersonate.admin.UserAdminImpersonateMixin, to include
in your User model’s ModelAdmin. This provides a direct link to
impersonate users from your user model’s Django admin list view. Using
it is very simple, however if you’re using the defaultdjango.contrib.auth.models.Usermodel you will need to unregister
the old ModelAdmin before registering your own.TheUserAdminImpersonateMixinhas a attribute namedopen_new_windowthatdefaults to ``False``. If this is set to
True a new window will be opened to start the new impersonation session
when clicking the impersonate link directly in the admin.Here’s an example:# yourapp/admin.py
from django.contrib import admin
from django.contrib.auth.models import User
from django.contrib.auth.admin import UserAdmin
from impersonate.admin import UserAdminImpersonateMixin


class NewUserAdmin(UserAdminImpersonateMixin, UserAdmin):
    open_new_window = True
    pass

admin.site.unregister(User)
admin.site.register(User, NewUserAdmin)TestingFrom the repo checkout, ensure you have Django in yourPYTHONPATHand run:$ python runtests.pyTo get test coverage, use:$ coverage run --branch runtests.py
$ coverage html  <- Pretty HTML files for you
$ coverage report -m  <- Ascii reportIf you’re bored and want to test all the supported environments, you’ll
need tox.:$ pip install tox
$ toxAnd you should see:py37-django2.2: commands succeeded
py37-django3.2: commands succeeded
py38-django2.2: commands succeeded
py38-django3.2: commands succeeded
py39-django2.2: commands succeeded
py39-django3.2: commands succeeded
py38-django4.0: commands succeeded
py39-django4.0: commands succeeded
py310-django3.2: commands succeeded
py310-django4.0: commands succeeded
congratulations :)ContributingWe accept patches submitted viahg emailwhich is thepatchbombextension included with Mercurial.The mailing list where you submit your patches is~petersanchez/public-inbox@lists.code.netlandish.com. You can also
view the archives on the web here:https://lists.code.netlandish.com/~petersanchez/public-inboxTo quickly setup your clone ofdjango-impersonateto submit to the
mailing list just edit your.hg/hgrcfile and add the following:[email]
to = ~petersanchez/public-inbox@lists.code.netlandish.com

[patchbomb]
flagtemplate = {separate(' ', 'django-impersonate', flags)}

[diff]
git = 1We have more information on the topic here:ContributingUsing email with
MercurialMailing list
etiquetteCopyright & WarrantyAll documentation, libraries, and sample code are Copyright 2011 Peter
Sanchez <petersanchez@gmail.com>. The library and sample code are made
available to you under the terms of the BSD license which is contained
in the included file, BSD-LICENSE.Commercial SupportThis software, and lots of other software like it, has been built in
support of many of Netlandish’s own projects, and the projects of our
clients. We would love to help you on your next project so get in touch
by dropping us a note athello@netlandish.com.