././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1700765883.9885788 django-impersonate-1.9.2/0000755000175000017500000000000014527720274013535 5ustar00pjspjs././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1583548731.0 django-impersonate-1.9.2/AUTHORS0000664000175000017500000000107613630604473014607 0ustar00pjspjsCreator: Peter Sanchez HUGE THANKS to the following contributors: Dan Han - dhan@cycle88.com Rory McCann - rory@technomancy.org Tom Clancy Chris Vigelius Michael van Tellingen Hugo Rodger-Brown - hugo@yunojuno.com Berislav Lopac Paul Melnikow Jannis Vajen - jvajen@gmail.com Erik Telepovský - erik.telepovsky@email.com Chris Wood - chris@wood.is Brent O'Connor - epicserve Steve Jalim Yuri Prezument - y@yprez.com Ben Tappin - ben@mrben.co.uk thijsdezoete Federico Bond federicobond@gmail.com Aymeric Augustin Adam Taylor - ataylor32 J - r-w-x ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1676920800.0 django-impersonate-1.9.2/CHANGELOG0000644000175000017500000001052414374743740014754 0ustar00pjspjsChanges ------- 1.9.1 (2023-02-20) - Prevent redirect loop when MAX_DURATION is used. Refs ~petersanchez/django-impersonate#67 - Allow OPTIONS requests when READ_ONLY is True. Refs ~petersanchez/django-impersonate#69 - Added CUSTOM_READ_ONLY to customise when to restrict to read only access. Refs ~petersanchez/django-impersonate#70 1.8.1 (2022-02-17) - Patch version bump for README updates. I know... I'm shameful. 1.8.0 (2022-02-17) - Adding support for Django 4.0 - Adding 'default_auto_field' definition. Refs ~petersanchez/django-impersonate#62 1.7.3 (2021-02-05) Added `impersonator` object to `request.user` https://lists.code.netlandish.com/~petersanchez/public-inbox/patches/8 1.7.2 (2021-01-04) Removing smart quotes from README.rst for edge cases on systems with odd unicode settings. 1.7.1 (2020-12-23) https://todo.code.netlandish.com/~petersanchez/django-impersonate?search=status%3Aclosed+label%3A%221.7.1%22 1.7.0 (2020-11-25) https://todo.code.netlandish.com/~petersanchez/django-impersonate?search=status%3Aclosed+label%3A%221.7%22 1.6.0 (2020-11-18) https://todo.code.netlandish.com/~petersanchez/django-impersonate?search=status%3Aclosed%20label%3A%221.6%22 1.4.0 (2019-01-12) - Officially support Python 3.6+ and Django 1.11+ - "friendly_name" function now users USERNAME_FIELD. (Pull Request #30) - Add admin support for exception NotSupportedError. (Pull Request #34) 1.3 (2017-12-14) - Django 2.0 compatable (Issue #46) - Consolidate settings into a single IMPERSIONATE dictionary (Issue #20) - Add admin Mixin to offer quick shortcut to user impersonation via Django admin. (Issue #19) 1.2.1 (2017-11-13) - TODO Issue #19 - Make search results distinct. (Pull Request #31) - Add request.real_user for convenience. (Pull Request #32) - Ensure default user queries are ordered to ensure consistency. (Pull Request #33) 1.1 (2017-01-26) - Django 1.10 compatibility (get rid of deprecation warnings). (Issue #36) - Use USERNAME_FIELD for sorting in admin to avoid custom User model issues. (Issue #37) - Added test coverage and refactoring for admin filters. - Updated data sent to signal_end signal to be uniform with signal_begin and documentation. (Issue #34) - Updated middleware documentation. (Issue #33) 1.0.1 (2016-04-10) - Fix migration issues with custom User models. (Issue #31, Pull Request #26) 1.0 (2016-02-14) - Update to use User PK instead of ID. (Pull Request #20) - Use proper URL tag for user search, listing templates. (Pull Requests #21, #22) - Add Impersonation Log support. (Issue #7, Issue #28, Pull Request #23) - Add support for Django 1.9 (Pull Request #24) - Adding unicode_literals for Py3 compatibility. (Issue #29) 0.9.2 (2015-08-24) - Add http refer specific setting because it broke prevoius usage. (Issue #24, Refs Issue #17) 0.9.1 (2015-04-16) - Fix unicode issue with redirect variables. (Issue #21) - Add redirect to previous impersonation screen. (Issue #17, Pull Request #17) - Django 1.8 compatibility. (Pull Request #19) 0.9.0 (2014-09-30) - Split search query into terms. (Pull Request #15) - Edge case bug addressing different versions of Django in different environments. (Issue #15) - Moved LOGIN_URL to function to avoid circular import issues. (Pull Request #14) - Customize search fields and query type. (Issue #14, Pull Request #13) - Django 1.7 compat changes. (Refs Pull Request #16) 0.8.1 (2013-11-09) - Store user ID for Django 1.6 serialization support. (Issue #12, Pull Request #11) - Updated Authors & Changelog - Updated tox config to include Django 1.6 environments 0.8.0 (2013-08-24) - Added "impersonator" to request object. (Issue #5) - Ditched custom import method for django importlib. (Issue #6) - Updated Authors & Changelog - Added session_begin and session_end signals. (Issue #8, Pull Request #7) 0.7.0 (2013-03-28) - Added Python 3.3 support. 0.6.0 (2013-03-21) - Added Django 1.5 support - Added full test coverage support (Issue #1) 0.5.3 (2012-06-20) - Fixed Issue impersonating with a staff user (Issue #4) 0.5.2 (2012-03-20) - Minor updates. Authors and changelog file 0.5.1 (2012-03-04): - Fixed Django 1.1 compatibility problem (Issue #2) - Fixed missing templates directory (Issue #3) - Updated AUTHORS file PREVIOUS VERSIONS: I've been a bad boy and haven't been keeping a changelog. I'll keep this updated moving forward. If you're really interested, read the commit history ;) ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1601663170.0 django-impersonate-1.9.2/LICENSE0000664000175000017500000000301013735670302014532 0ustar00pjspjsCopyright (c) 2009, Peter Sanchez All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of Peter Sanchez nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1698496703.0 django-impersonate-1.9.2/MANIFEST.in0000600000175000017500000000013714517200277015257 0ustar00pjspjsinclude CHANGELOG include LICENSE include README.rst recursive-include impersonate/templates * ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1700765883.9885788 django-impersonate-1.9.2/PKG-INFO0000644000175000017500000004566514527720274014652 0ustar00pjspjsMetadata-Version: 2.1 Name: django-impersonate Version: 1.9.2 Summary: Django app to allow superusers to impersonate other users. Home-page: https://code.netlandish.com/~petersanchez/django-impersonate Author: Peter Sanchez Author-email: pjs@petersanchez.com License: BSD License Platform: any Classifier: Development Status :: 5 - Production/Stable Classifier: Intended Audience :: Developers Classifier: License :: OSI Approved :: BSD License Classifier: Natural Language :: English Classifier: Operating System :: OS Independent Classifier: Framework :: Django Classifier: Framework :: Django :: 3.2 Classifier: Framework :: Django :: 4.0 Classifier: Framework :: Django :: 4.1 Classifier: Framework :: Django :: 4.2 Classifier: Framework :: Django :: 5.0 Classifier: Programming Language :: Python Classifier: Programming Language :: Python :: 3.7 Classifier: Programming Language :: Python :: 3.8 Classifier: Programming Language :: Python :: 3.9 Classifier: Programming Language :: Python :: 3.10 Classifier: Programming Language :: Python :: 3.11 Classifier: Programming Language :: Python :: 3.12 Classifier: Environment :: Web Environment License-File: LICENSE License-File: AUTHORS django-impersonate |nlshield| ----------------------------- Simple application to allow superusers to "impersonate" other non-superuser accounts. **Version:** 1.9.2 **Project Links:** `Issues `__ - `Mailing List `__ - `Contributing <#contributing>`__ **Author:** Peter Sanchez (https://petersanchez.com) Python / Django Support ======================= - Python 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. Dependencies ============ - Depends on your project using the django.contrib.session framework. **NOTE:** - **Version 1.6** has officially removed support for the old settings format. Please see the `settings <#settings>`__ section for how settings should be configured. - **Version 1.5 is now only officially supporting Django's 1.11, 2.2, and 3.0** - **Version 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 the ``DISABLE_LOGGING`` settings option. - If you need to use this with Django older than 1.8, please use version django-impersonate == 1.0.1 - If you need to use this with Django older than 1.7, please use version django-impersonate == 0.9.2 - **Version 0.9.2 partially reverts work completed in version 0.9.1.** This is because work done to address a request in `Issue #17 `__ broke default behavior for all previous versions. `Issue #24 `__ was opened and the fix was released in 0.9.2 to address it. Please see the new ``USE_HTTP_REFERER`` settings option. - If you need to use this with Django older than 1.4, please use version django-impersonate == 0.5.3 Installation ============ PIP: :: pip install django-impersonate Basic Manual Install: :: $ python setup.py build $ sudo python setup.py install Alternative 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. Use === #. Add ``impersonate`` to your INSTALLED_APPS #. Add ``impersonate.middleware.ImpersonateMiddleware`` to your ``MIDDLEWARE`` setting. #. Add ``impersonate.urls`` somewhere 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:** The ``ImpersonationMiddleware`` class should be placed AFTER the ``django.contrib.auth.*`` middleware classes Functionality ============= **You can now impersonate another user by hitting the following path:** :: /impersonate// Replace with the user id of the user you want to impersonate. While in impersonation "mode" the ``request.user`` object will have an ``is_impersonate`` attribute set to ``True`` as well as ``impersonator`` (and also ``request.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 as ``user.impersonator`` or ``request.impersonator``: :: {{ request.user }} ({{ request.impersonator }}) The real user is available as ``request.real_user`` - this is equivalent to calling ``getattr(request, 'impersonator', request.user)``: :: assert request.real_user == getattr(request, 'impersonator', request.user) You can reference this URL with ``reverse`` or the ``{% url %}`` template tag as ``impersonate-start`` and 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 with ``reverse`` or the ``{% url %}`` template tag as ``impersonate-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 template ``impersonate/list_users.html`` and will pass the following in the context: - ``users`` - queryset of all users - ``paginator`` - Django Paginator instance - ``page`` - Current page of objects (from Paginator) - ``page_number`` - Current page number, defaults to 1 You can reference this URL with ``reverse`` or the ``{% url %}`` template tag as ``impersonate-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 users - ``paginator`` - Django Paginator instance - ``page`` - Current page of objects (from Paginator) - ``page_number`` - Current page number, defaults to 1 - ``query`` - The search query that was entered The view will expect a GET request and look for the ``q`` variable being passed. If present, it will search the user entries with the value of ``q``. The default fields searched are: ``User.username``, ``User.first_name``, ``User.last_name``, ``User.email`` You can reference this URL with ``reverse`` or the ``{% url %}`` template tag as ``impersonate-search``. **To allow some users to impersonate other users** You can optionally allow only some non-superuser and non-staff users to impersonate by adding a ``CUSTOM_ALLOW`` setting option. Create a function that takes a request object, and based on your rules, returns ``True`` if the user is allowed to impersonate or not. **To limit what users a user can impersonate** By, optionally, setting the ``CUSTOM_USER_QUERYSET`` option 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. Signals ======= If 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 the ``impersonate`` view - ``session_end`` - sent when calling the ``stop_impersonate`` view Both of these signals send the same arguments: - ``sender`` - this is a Django signal requirement, and is always set to None - ``impersonator`` - a reference to the User object of the person doing the impersonation - ``impersonating`` - a reference to the User object of the person being impersonated - ``request`` - the Django HttpRequest object from which the impersonation was invoked The 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``. The ``session_end`` signal will only be fired if the impersonator explicitly ends the session. Settings ======== The following settings are available for django-impersonate. All settings should be set as variables in a dictionary assigned to the attribute named ``IMPERSONATE``. For example: :: IMPERSONATE = { 'REDIRECT_URL': '/some-path/', 'PAGINATE_COUNT': 10, } Here are the options available... :: REDIRECT_URL This is the URL you want to be redirected to *after* you have chosen to impersonate another user. If this is not present it will check for the ``LOGIN_REDIRECT_URL`` setting and fall back to '/' if neither is present. Value should be a string containing the redirect path. :: READ_ONLY A boolean that if set to ``True`` any requests that are not either ``GET`` or ``HEAD`` or ``OPTIONS`` will 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 to ``False`` If the ``CUSTOM_READ_ONLY`` is set, then that custom function is used, and this setting is ignored. :: CUSTOM_READ_ONLY A 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 allow ``GET``, ``HEAD`` and ``OPTIONS`` requests. It is optional, and if it is not present, ``READ_ONLY`` setting value applies. :: USE_HTTP_REFERER If this is set to ``True``, then the app will attempt to be redirect you to the URL you were at when the impersonation began once you have *stopped* the 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 in ``REDIRECT_URL``. Value should be a boolean, defaults to ``False`` :: PAGINATE_COUNT This 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_SUPERUSER If this is set to ``True``, then only users who have ``is_superuser`` set to ``True`` will be allowed to impersonate other users. Default is ``False``. If ``False``, then any ``is_staff`` user will be able to impersonate other users. **Note:** Regardless of this setting, a ``is_staff`` user will **not** be allowed to impersonate a ``is_superuser`` user. Value should be a boolean If the ``CUSTOM_ALLOW`` is set, then that custom function is used, and this setting is ignored. :: ALLOW_SUPERUSER By 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 is ``False``. :: URI_EXCLUSIONS Set 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_QUERYSET A 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_SUPERUSER`` and ``CUSTOM_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 is ``User.objects.all()``). :: CUSTOM_ALLOW A 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_SUPERUSER`` is ignored. It is optional, and if it is not present, the previous rules about superuser and ``REQUIRE_SUPERUSER`` apply. :: REDIRECT_FIELD_NAME A 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 switch user To return always to the current page after impersonating a user, use request.path: :: `switch user` Each use case is different so obviously set the next value to whatever your case requires. :: SEARCH_FIELDS Array 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 the ``USERNAME_FIELD`` attribute, it falls back to 'username' (< Django 1.5). :: LOOKUP_TYPE A string that represents SQL lookup type for searching users by query on fields above. It is ``icontains`` by default. :: DISABLE_LOGGING A boolean that can be used to disable the logging of impersonation sessions. By default each impersonation ``session_begin`` signal will create a new ``ImpersonationLog`` object, which is closed out (duration calculated) at the corresponding ``session_end`` signal. It is optional, and defaults to False (i.e. logging is enabled). :: MAX_FILTER_SIZE The 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_PERMISSION A boolean to enable/disable deletion of impersonation logs in the Django admin. Default is ``False`` :: ADMIN_ADD_PERMISSION A boolean to enable/disable ability to add impersonation logs in the Django admin. Default is ``False`` :: ADMIN_READ_ONLY A 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 is ``True`` :: MAX_DURATION A number specifying the maximum allowed duration of impersonation sessions in **seconds**. Default is ``None`` Admin ===== As of version 1.3 django-impersonate now includes a helper admin mixin, located at ``impersonate.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 default ``django.contrib.auth.models.User`` model you will need to unregister the old ModelAdmin before registering your own. The ``UserAdminImpersonateMixin`` has a attribute named ``open_new_window`` that **defaults 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) Testing ======= From the repo checkout, ensure you have Django in your ``PYTHONPATH`` and run: :: $ python runtests.py To get test coverage, use: :: $ coverage run --branch runtests.py $ coverage html <- Pretty HTML files for you $ coverage report -m <- Ascii report If you're bored and want to test all the supported environments, you'll need tox.: :: $ pip install tox $ tox And 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 :) Contributing ============ We accept patches submitted via ``hg email`` which is the ``patchbomb`` extension 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-inbox To quickly setup your clone of ``django-impersonate`` to submit to the mailing list just edit your ``.hg/hgrc`` file and add the following: :: [email] to = ~petersanchez/public-inbox@lists.code.netlandish.com [patchbomb] flagtemplate = {separate(' ', 'django-impersonate', flags)} [diff] git = 1 We have more information on the topic here: - `Contributing `__ - `Using email with Mercurial `__ - `Mailing list etiquette `__ Copyright & Warranty ==================== All documentation, libraries, and sample code are Copyright 2011 Peter Sanchez . 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 Support ------------------ This 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 at hello@netlandish.com. .. |nlshield| image:: https://img.shields.io/badge/100%25-Netlandish-blue.svg?style=square-flat :target: http://www.netlandish.com ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1700763546.0 django-impersonate-1.9.2/README.rst0000644000175000017500000004341414527713632015232 0ustar00pjspjsdjango-impersonate |nlshield| ----------------------------- Simple application to allow superusers to "impersonate" other non-superuser accounts. **Version:** 1.9.2 **Project Links:** `Issues `__ - `Mailing List `__ - `Contributing <#contributing>`__ **Author:** Peter Sanchez (https://petersanchez.com) Python / Django Support ======================= - Python 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. Dependencies ============ - Depends on your project using the django.contrib.session framework. **NOTE:** - **Version 1.6** has officially removed support for the old settings format. Please see the `settings <#settings>`__ section for how settings should be configured. - **Version 1.5 is now only officially supporting Django's 1.11, 2.2, and 3.0** - **Version 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 the ``DISABLE_LOGGING`` settings option. - If you need to use this with Django older than 1.8, please use version django-impersonate == 1.0.1 - If you need to use this with Django older than 1.7, please use version django-impersonate == 0.9.2 - **Version 0.9.2 partially reverts work completed in version 0.9.1.** This is because work done to address a request in `Issue #17 `__ broke default behavior for all previous versions. `Issue #24 `__ was opened and the fix was released in 0.9.2 to address it. Please see the new ``USE_HTTP_REFERER`` settings option. - If you need to use this with Django older than 1.4, please use version django-impersonate == 0.5.3 Installation ============ PIP: :: pip install django-impersonate Basic Manual Install: :: $ python setup.py build $ sudo python setup.py install Alternative 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. Use === #. Add ``impersonate`` to your INSTALLED_APPS #. Add ``impersonate.middleware.ImpersonateMiddleware`` to your ``MIDDLEWARE`` setting. #. Add ``impersonate.urls`` somewhere 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:** The ``ImpersonationMiddleware`` class should be placed AFTER the ``django.contrib.auth.*`` middleware classes Functionality ============= **You can now impersonate another user by hitting the following path:** :: /impersonate// Replace with the user id of the user you want to impersonate. While in impersonation "mode" the ``request.user`` object will have an ``is_impersonate`` attribute set to ``True`` as well as ``impersonator`` (and also ``request.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 as ``user.impersonator`` or ``request.impersonator``: :: {{ request.user }} ({{ request.impersonator }}) The real user is available as ``request.real_user`` - this is equivalent to calling ``getattr(request, 'impersonator', request.user)``: :: assert request.real_user == getattr(request, 'impersonator', request.user) You can reference this URL with ``reverse`` or the ``{% url %}`` template tag as ``impersonate-start`` and 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 with ``reverse`` or the ``{% url %}`` template tag as ``impersonate-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 template ``impersonate/list_users.html`` and will pass the following in the context: - ``users`` - queryset of all users - ``paginator`` - Django Paginator instance - ``page`` - Current page of objects (from Paginator) - ``page_number`` - Current page number, defaults to 1 You can reference this URL with ``reverse`` or the ``{% url %}`` template tag as ``impersonate-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 users - ``paginator`` - Django Paginator instance - ``page`` - Current page of objects (from Paginator) - ``page_number`` - Current page number, defaults to 1 - ``query`` - The search query that was entered The view will expect a GET request and look for the ``q`` variable being passed. If present, it will search the user entries with the value of ``q``. The default fields searched are: ``User.username``, ``User.first_name``, ``User.last_name``, ``User.email`` You can reference this URL with ``reverse`` or the ``{% url %}`` template tag as ``impersonate-search``. **To allow some users to impersonate other users** You can optionally allow only some non-superuser and non-staff users to impersonate by adding a ``CUSTOM_ALLOW`` setting option. Create a function that takes a request object, and based on your rules, returns ``True`` if the user is allowed to impersonate or not. **To limit what users a user can impersonate** By, optionally, setting the ``CUSTOM_USER_QUERYSET`` option 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. Signals ======= If 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 the ``impersonate`` view - ``session_end`` - sent when calling the ``stop_impersonate`` view Both of these signals send the same arguments: - ``sender`` - this is a Django signal requirement, and is always set to None - ``impersonator`` - a reference to the User object of the person doing the impersonation - ``impersonating`` - a reference to the User object of the person being impersonated - ``request`` - the Django HttpRequest object from which the impersonation was invoked The 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``. The ``session_end`` signal will only be fired if the impersonator explicitly ends the session. Settings ======== The following settings are available for django-impersonate. All settings should be set as variables in a dictionary assigned to the attribute named ``IMPERSONATE``. For example: :: IMPERSONATE = { 'REDIRECT_URL': '/some-path/', 'PAGINATE_COUNT': 10, } Here are the options available... :: REDIRECT_URL This is the URL you want to be redirected to *after* you have chosen to impersonate another user. If this is not present it will check for the ``LOGIN_REDIRECT_URL`` setting and fall back to '/' if neither is present. Value should be a string containing the redirect path. :: READ_ONLY A boolean that if set to ``True`` any requests that are not either ``GET`` or ``HEAD`` or ``OPTIONS`` will 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 to ``False`` If the ``CUSTOM_READ_ONLY`` is set, then that custom function is used, and this setting is ignored. :: CUSTOM_READ_ONLY A 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 allow ``GET``, ``HEAD`` and ``OPTIONS`` requests. It is optional, and if it is not present, ``READ_ONLY`` setting value applies. :: USE_HTTP_REFERER If this is set to ``True``, then the app will attempt to be redirect you to the URL you were at when the impersonation began once you have *stopped* the 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 in ``REDIRECT_URL``. Value should be a boolean, defaults to ``False`` :: PAGINATE_COUNT This 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_SUPERUSER If this is set to ``True``, then only users who have ``is_superuser`` set to ``True`` will be allowed to impersonate other users. Default is ``False``. If ``False``, then any ``is_staff`` user will be able to impersonate other users. **Note:** Regardless of this setting, a ``is_staff`` user will **not** be allowed to impersonate a ``is_superuser`` user. Value should be a boolean If the ``CUSTOM_ALLOW`` is set, then that custom function is used, and this setting is ignored. :: ALLOW_SUPERUSER By 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 is ``False``. :: URI_EXCLUSIONS Set 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_QUERYSET A 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_SUPERUSER`` and ``CUSTOM_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 is ``User.objects.all()``). :: CUSTOM_ALLOW A 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_SUPERUSER`` is ignored. It is optional, and if it is not present, the previous rules about superuser and ``REQUIRE_SUPERUSER`` apply. :: REDIRECT_FIELD_NAME A 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 switch user To return always to the current page after impersonating a user, use request.path: :: `switch user` Each use case is different so obviously set the next value to whatever your case requires. :: SEARCH_FIELDS Array 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 the ``USERNAME_FIELD`` attribute, it falls back to 'username' (< Django 1.5). :: LOOKUP_TYPE A string that represents SQL lookup type for searching users by query on fields above. It is ``icontains`` by default. :: DISABLE_LOGGING A boolean that can be used to disable the logging of impersonation sessions. By default each impersonation ``session_begin`` signal will create a new ``ImpersonationLog`` object, which is closed out (duration calculated) at the corresponding ``session_end`` signal. It is optional, and defaults to False (i.e. logging is enabled). :: MAX_FILTER_SIZE The 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_PERMISSION A boolean to enable/disable deletion of impersonation logs in the Django admin. Default is ``False`` :: ADMIN_ADD_PERMISSION A boolean to enable/disable ability to add impersonation logs in the Django admin. Default is ``False`` :: ADMIN_READ_ONLY A 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 is ``True`` :: MAX_DURATION A number specifying the maximum allowed duration of impersonation sessions in **seconds**. Default is ``None`` Admin ===== As of version 1.3 django-impersonate now includes a helper admin mixin, located at ``impersonate.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 default ``django.contrib.auth.models.User`` model you will need to unregister the old ModelAdmin before registering your own. The ``UserAdminImpersonateMixin`` has a attribute named ``open_new_window`` that **defaults 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) Testing ======= From the repo checkout, ensure you have Django in your ``PYTHONPATH`` and run: :: $ python runtests.py To get test coverage, use: :: $ coverage run --branch runtests.py $ coverage html <- Pretty HTML files for you $ coverage report -m <- Ascii report If you're bored and want to test all the supported environments, you'll need tox.: :: $ pip install tox $ tox And 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 :) Contributing ============ We accept patches submitted via ``hg email`` which is the ``patchbomb`` extension 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-inbox To quickly setup your clone of ``django-impersonate`` to submit to the mailing list just edit your ``.hg/hgrc`` file and add the following: :: [email] to = ~petersanchez/public-inbox@lists.code.netlandish.com [patchbomb] flagtemplate = {separate(' ', 'django-impersonate', flags)} [diff] git = 1 We have more information on the topic here: - `Contributing `__ - `Using email with Mercurial `__ - `Mailing list etiquette `__ Copyright & Warranty ==================== All documentation, libraries, and sample code are Copyright 2011 Peter Sanchez . 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 Support ------------------ This 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 at hello@netlandish.com. .. |nlshield| image:: https://img.shields.io/badge/100%25-Netlandish-blue.svg?style=square-flat :target: http://www.netlandish.com ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1700765883.9852455 django-impersonate-1.9.2/django_impersonate.egg-info/0000755000175000017500000000000014527720274021077 5ustar00pjspjs././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1700765883.0 django-impersonate-1.9.2/django_impersonate.egg-info/PKG-INFO0000644000175000017500000004566514527720273022213 0ustar00pjspjsMetadata-Version: 2.1 Name: django-impersonate Version: 1.9.2 Summary: Django app to allow superusers to impersonate other users. Home-page: https://code.netlandish.com/~petersanchez/django-impersonate Author: Peter Sanchez Author-email: pjs@petersanchez.com License: BSD License Platform: any Classifier: Development Status :: 5 - Production/Stable Classifier: Intended Audience :: Developers Classifier: License :: OSI Approved :: BSD License Classifier: Natural Language :: English Classifier: Operating System :: OS Independent Classifier: Framework :: Django Classifier: Framework :: Django :: 3.2 Classifier: Framework :: Django :: 4.0 Classifier: Framework :: Django :: 4.1 Classifier: Framework :: Django :: 4.2 Classifier: Framework :: Django :: 5.0 Classifier: Programming Language :: Python Classifier: Programming Language :: Python :: 3.7 Classifier: Programming Language :: Python :: 3.8 Classifier: Programming Language :: Python :: 3.9 Classifier: Programming Language :: Python :: 3.10 Classifier: Programming Language :: Python :: 3.11 Classifier: Programming Language :: Python :: 3.12 Classifier: Environment :: Web Environment License-File: LICENSE License-File: AUTHORS django-impersonate |nlshield| ----------------------------- Simple application to allow superusers to "impersonate" other non-superuser accounts. **Version:** 1.9.2 **Project Links:** `Issues `__ - `Mailing List `__ - `Contributing <#contributing>`__ **Author:** Peter Sanchez (https://petersanchez.com) Python / Django Support ======================= - Python 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. Dependencies ============ - Depends on your project using the django.contrib.session framework. **NOTE:** - **Version 1.6** has officially removed support for the old settings format. Please see the `settings <#settings>`__ section for how settings should be configured. - **Version 1.5 is now only officially supporting Django's 1.11, 2.2, and 3.0** - **Version 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 the ``DISABLE_LOGGING`` settings option. - If you need to use this with Django older than 1.8, please use version django-impersonate == 1.0.1 - If you need to use this with Django older than 1.7, please use version django-impersonate == 0.9.2 - **Version 0.9.2 partially reverts work completed in version 0.9.1.** This is because work done to address a request in `Issue #17 `__ broke default behavior for all previous versions. `Issue #24 `__ was opened and the fix was released in 0.9.2 to address it. Please see the new ``USE_HTTP_REFERER`` settings option. - If you need to use this with Django older than 1.4, please use version django-impersonate == 0.5.3 Installation ============ PIP: :: pip install django-impersonate Basic Manual Install: :: $ python setup.py build $ sudo python setup.py install Alternative 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. Use === #. Add ``impersonate`` to your INSTALLED_APPS #. Add ``impersonate.middleware.ImpersonateMiddleware`` to your ``MIDDLEWARE`` setting. #. Add ``impersonate.urls`` somewhere 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:** The ``ImpersonationMiddleware`` class should be placed AFTER the ``django.contrib.auth.*`` middleware classes Functionality ============= **You can now impersonate another user by hitting the following path:** :: /impersonate// Replace with the user id of the user you want to impersonate. While in impersonation "mode" the ``request.user`` object will have an ``is_impersonate`` attribute set to ``True`` as well as ``impersonator`` (and also ``request.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 as ``user.impersonator`` or ``request.impersonator``: :: {{ request.user }} ({{ request.impersonator }}) The real user is available as ``request.real_user`` - this is equivalent to calling ``getattr(request, 'impersonator', request.user)``: :: assert request.real_user == getattr(request, 'impersonator', request.user) You can reference this URL with ``reverse`` or the ``{% url %}`` template tag as ``impersonate-start`` and 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 with ``reverse`` or the ``{% url %}`` template tag as ``impersonate-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 template ``impersonate/list_users.html`` and will pass the following in the context: - ``users`` - queryset of all users - ``paginator`` - Django Paginator instance - ``page`` - Current page of objects (from Paginator) - ``page_number`` - Current page number, defaults to 1 You can reference this URL with ``reverse`` or the ``{% url %}`` template tag as ``impersonate-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 users - ``paginator`` - Django Paginator instance - ``page`` - Current page of objects (from Paginator) - ``page_number`` - Current page number, defaults to 1 - ``query`` - The search query that was entered The view will expect a GET request and look for the ``q`` variable being passed. If present, it will search the user entries with the value of ``q``. The default fields searched are: ``User.username``, ``User.first_name``, ``User.last_name``, ``User.email`` You can reference this URL with ``reverse`` or the ``{% url %}`` template tag as ``impersonate-search``. **To allow some users to impersonate other users** You can optionally allow only some non-superuser and non-staff users to impersonate by adding a ``CUSTOM_ALLOW`` setting option. Create a function that takes a request object, and based on your rules, returns ``True`` if the user is allowed to impersonate or not. **To limit what users a user can impersonate** By, optionally, setting the ``CUSTOM_USER_QUERYSET`` option 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. Signals ======= If 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 the ``impersonate`` view - ``session_end`` - sent when calling the ``stop_impersonate`` view Both of these signals send the same arguments: - ``sender`` - this is a Django signal requirement, and is always set to None - ``impersonator`` - a reference to the User object of the person doing the impersonation - ``impersonating`` - a reference to the User object of the person being impersonated - ``request`` - the Django HttpRequest object from which the impersonation was invoked The 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``. The ``session_end`` signal will only be fired if the impersonator explicitly ends the session. Settings ======== The following settings are available for django-impersonate. All settings should be set as variables in a dictionary assigned to the attribute named ``IMPERSONATE``. For example: :: IMPERSONATE = { 'REDIRECT_URL': '/some-path/', 'PAGINATE_COUNT': 10, } Here are the options available... :: REDIRECT_URL This is the URL you want to be redirected to *after* you have chosen to impersonate another user. If this is not present it will check for the ``LOGIN_REDIRECT_URL`` setting and fall back to '/' if neither is present. Value should be a string containing the redirect path. :: READ_ONLY A boolean that if set to ``True`` any requests that are not either ``GET`` or ``HEAD`` or ``OPTIONS`` will 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 to ``False`` If the ``CUSTOM_READ_ONLY`` is set, then that custom function is used, and this setting is ignored. :: CUSTOM_READ_ONLY A 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 allow ``GET``, ``HEAD`` and ``OPTIONS`` requests. It is optional, and if it is not present, ``READ_ONLY`` setting value applies. :: USE_HTTP_REFERER If this is set to ``True``, then the app will attempt to be redirect you to the URL you were at when the impersonation began once you have *stopped* the 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 in ``REDIRECT_URL``. Value should be a boolean, defaults to ``False`` :: PAGINATE_COUNT This 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_SUPERUSER If this is set to ``True``, then only users who have ``is_superuser`` set to ``True`` will be allowed to impersonate other users. Default is ``False``. If ``False``, then any ``is_staff`` user will be able to impersonate other users. **Note:** Regardless of this setting, a ``is_staff`` user will **not** be allowed to impersonate a ``is_superuser`` user. Value should be a boolean If the ``CUSTOM_ALLOW`` is set, then that custom function is used, and this setting is ignored. :: ALLOW_SUPERUSER By 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 is ``False``. :: URI_EXCLUSIONS Set 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_QUERYSET A 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_SUPERUSER`` and ``CUSTOM_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 is ``User.objects.all()``). :: CUSTOM_ALLOW A 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_SUPERUSER`` is ignored. It is optional, and if it is not present, the previous rules about superuser and ``REQUIRE_SUPERUSER`` apply. :: REDIRECT_FIELD_NAME A 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 switch user To return always to the current page after impersonating a user, use request.path: :: `switch user` Each use case is different so obviously set the next value to whatever your case requires. :: SEARCH_FIELDS Array 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 the ``USERNAME_FIELD`` attribute, it falls back to 'username' (< Django 1.5). :: LOOKUP_TYPE A string that represents SQL lookup type for searching users by query on fields above. It is ``icontains`` by default. :: DISABLE_LOGGING A boolean that can be used to disable the logging of impersonation sessions. By default each impersonation ``session_begin`` signal will create a new ``ImpersonationLog`` object, which is closed out (duration calculated) at the corresponding ``session_end`` signal. It is optional, and defaults to False (i.e. logging is enabled). :: MAX_FILTER_SIZE The 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_PERMISSION A boolean to enable/disable deletion of impersonation logs in the Django admin. Default is ``False`` :: ADMIN_ADD_PERMISSION A boolean to enable/disable ability to add impersonation logs in the Django admin. Default is ``False`` :: ADMIN_READ_ONLY A 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 is ``True`` :: MAX_DURATION A number specifying the maximum allowed duration of impersonation sessions in **seconds**. Default is ``None`` Admin ===== As of version 1.3 django-impersonate now includes a helper admin mixin, located at ``impersonate.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 default ``django.contrib.auth.models.User`` model you will need to unregister the old ModelAdmin before registering your own. The ``UserAdminImpersonateMixin`` has a attribute named ``open_new_window`` that **defaults 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) Testing ======= From the repo checkout, ensure you have Django in your ``PYTHONPATH`` and run: :: $ python runtests.py To get test coverage, use: :: $ coverage run --branch runtests.py $ coverage html <- Pretty HTML files for you $ coverage report -m <- Ascii report If you're bored and want to test all the supported environments, you'll need tox.: :: $ pip install tox $ tox And 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 :) Contributing ============ We accept patches submitted via ``hg email`` which is the ``patchbomb`` extension 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-inbox To quickly setup your clone of ``django-impersonate`` to submit to the mailing list just edit your ``.hg/hgrc`` file and add the following: :: [email] to = ~petersanchez/public-inbox@lists.code.netlandish.com [patchbomb] flagtemplate = {separate(' ', 'django-impersonate', flags)} [diff] git = 1 We have more information on the topic here: - `Contributing `__ - `Using email with Mercurial `__ - `Mailing list etiquette `__ Copyright & Warranty ==================== All documentation, libraries, and sample code are Copyright 2011 Peter Sanchez . 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 Support ------------------ This 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 at hello@netlandish.com. .. |nlshield| image:: https://img.shields.io/badge/100%25-Netlandish-blue.svg?style=square-flat :target: http://www.netlandish.com ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1700765883.0 django-impersonate-1.9.2/django_impersonate.egg-info/SOURCES.txt0000644000175000017500000000130514527720273022761 0ustar00pjspjsAUTHORS CHANGELOG LICENSE MANIFEST.in README.rst pyproject.toml setup.py django_impersonate.egg-info/PKG-INFO django_impersonate.egg-info/SOURCES.txt django_impersonate.egg-info/dependency_links.txt django_impersonate.egg-info/top_level.txt impersonate/__init__.py impersonate/admin.py impersonate/apps.py impersonate/compat.py impersonate/decorators.py impersonate/helpers.py impersonate/middleware.py impersonate/models.py impersonate/settings.py impersonate/signals.py impersonate/tests.py impersonate/urls.py impersonate/views.py impersonate/migrations/0001_initial.py impersonate/migrations/__init__.py impersonate/templates/impersonate/list_users.html impersonate/templates/impersonate/search_users.html././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1700765883.0 django-impersonate-1.9.2/django_impersonate.egg-info/dependency_links.txt0000644000175000017500000000000114527720273025144 0ustar00pjspjs ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1700765883.0 django-impersonate-1.9.2/django_impersonate.egg-info/top_level.txt0000644000175000017500000000001414527720273023623 0ustar00pjspjsimpersonate ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1700765883.9852455 django-impersonate-1.9.2/impersonate/0000755000175000017500000000000014527720274016063 5ustar00pjspjs././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1700763231.0 django-impersonate-1.9.2/impersonate/__init__.py0000664000175000017500000000130414527713137020174 0ustar00pjspjs# -*- coding: utf-8 -*- VERSION = (1, 9, 2, 'final', 0) # taken from django-registration def get_version(): "Returns a PEP 386-compliant version number from VERSION." assert len(VERSION) == 5 assert VERSION[3] in ('alpha', 'beta', 'rc', 'final') # Now build the two parts of the version number: # main = X.Y[.Z] # sub = .devN - for pre-alpha releases # | {a|b|c}N - for alpha, beta and rc releases parts = 2 if VERSION[2] == 0 else 3 main = '.'.join(str(x) for x in VERSION[:parts]) sub = '' if VERSION[3] != 'final': mapping = {'alpha': 'a', 'beta': 'b', 'rc': 'c'} sub = mapping[VERSION[3]] + str(VERSION[4]) return str(main + sub) ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1698496703.0 django-impersonate-1.9.2/impersonate/admin.py0000600000175000017500000001303514517200277017512 0ustar00pjspjs# -*- coding: utf-8 -*- import logging from django.contrib import admin from django.db.utils import NotSupportedError from django.utils.html import format_html from .compat import reverse from .helpers import User, check_allow_impersonate from .models import ImpersonationLog from .settings import settings logger = logging.getLogger(__name__) def friendly_name(user): '''Return proper name if exists, else username.''' name = None if hasattr(user, 'get_full_name'): name = user.get_full_name() return name or getattr(user, getattr(User, 'USERNAME_FIELD', 'username')) class SessionStateFilter(admin.SimpleListFilter): ''' Custom admin filter based on the session state. Provides two filter values - 'complete' and 'incomplete'. A session that has no session_ended_at timestamp is considered incomplete. This field is set from the session_end signal receiver. ''' title = 'session state' parameter_name = 'session' def lookups(self, request, model_admin): return ( ('incomplete', 'Incomplete'), ('complete', 'Complete'), ) def queryset(self, request, queryset): if self.value() == 'incomplete': return queryset.filter(session_ended_at__isnull=True) if self.value() == 'complete': return queryset.filter(session_ended_at__isnull=False) else: return queryset class ImpersonatorFilter(admin.SimpleListFilter): ''' Custom admin filter based on the impersonator. Provides a set of users who have impersonated at some point. It is assumed that this is a small list of users - a subset of staff and superusers. There is no corresponding filter for users who have been impersonated, as this could be a very large set of users. If the number of unique impersonators exceeds MAX_FILTER_SIZE, then the users are limited to the value of MAX_FILTER_SIZE. ''' title = 'impersonator' parameter_name = 'impersonator' def lookups(self, request, model_admin): ''' Return list of unique users who have been an impersonator. ''' # the queryset containing the ImpersonationLog objects MAX_FILTER_SIZE = settings.MAX_FILTER_SIZE try: # Evaluate here to raise exception if needed ids = list( model_admin.get_queryset(request,) .order_by() .values_list('impersonator_id', flat=True,) .distinct('impersonator_id') )[:MAX_FILTER_SIZE] except (NotSupportedError, NotImplementedError): # Unit tests use sqlite db backend which doesn't support distinct. qs = model_admin.get_queryset(request).only('impersonator_id')[ :MAX_FILTER_SIZE ] ids = set([x.impersonator_id for x in qs]) if len(ids) > MAX_FILTER_SIZE: logger.info( ( 'Limiting admin list filter as number of impersonators ' '[{0}] exceeds MAX_FILTER_SIZE [{1}]' ).format( len(ids), MAX_FILTER_SIZE, ) ) impersonators = User.objects.filter(id__in=ids).order_by( User.USERNAME_FIELD ) for i in impersonators: yield (i.id, friendly_name(i)) def queryset(self, request, queryset): if self.value() in (None, ''): return queryset else: return queryset.filter(impersonator_id=self.value()) class UserAdminImpersonateMixin(object): ''' Mixin to easily add user impersonation support via the Django admin change list page. ''' open_new_window = False def get_list_display(self, request): if not check_allow_impersonate(request): return self.list_display list_display = list(self.list_display) list_display.append('impersonate_user') return list_display def impersonate_user(self, obj): target = '' if self.open_new_window: target = ' target="_blank"' return format_html( 'Impersonate', reverse('impersonate-start', args=[obj.id]), target, ) impersonate_user.short_description = 'Impersonate User' class ImpersonationLogAdmin(admin.ModelAdmin): list_select_related = ['impersonator', 'impersonating'] list_display = ( '_impersonator', '_impersonating', 'session_key', 'session_started_at', 'duration', ) readonly_fields = ( 'impersonator', 'impersonating', 'session_key', 'session_started_at', 'session_ended_at', ) list_filter = ( SessionStateFilter, ImpersonatorFilter, 'session_started_at', ) def _impersonator(self, obj): return friendly_name(obj.impersonator) def _impersonating(self, obj): return friendly_name(obj.impersonating) def has_add_permission(self, request): return settings.ADMIN_ADD_PERMISSION def has_delete_permission(self, request, obj=None): return settings.ADMIN_DELETE_PERMISSION # hack to show records but limit updating. # `return False` hides impersonates module in admin page def has_change_permission(self, request, obj=None): if settings.ADMIN_READ_ONLY: return request.method in ['GET', 'HEAD', 'OPTIONS'] return True admin.site.register(ImpersonationLog, ImpersonationLogAdmin) ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1645108604.0 django-impersonate-1.9.2/impersonate/apps.py0000664000175000017500000000034014203456574017377 0ustar00pjspjs# -*- coding: utf-8 -*- from django.apps import AppConfig class AccountsConfig(AppConfig): name = 'impersonate' default_auto_field = 'django.db.models.AutoField' def ready(self): from . import signals ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1698496703.0 django-impersonate-1.9.2/impersonate/compat.py0000600000175000017500000000031214517200277017677 0ustar00pjspjs# compatibility module for handling Django upgrade namespace changes try: from django.urls import reverse except ImportError: from django.core.urlresolvers import reverse __all__ = ["reverse"] ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1605811461.0 django-impersonate-1.9.2/impersonate/decorators.py0000644000175000017500000000222213755536405020603 0ustar00pjspjs# -*- coding: utf-8 -*- from urllib.parse import quote from django.conf import settings from django.utils.encoding import force_str from django.shortcuts import redirect, resolve_url from django.contrib.auth import REDIRECT_FIELD_NAME from .helpers import get_redir_path, check_allow_impersonate def get_login_url(): return force_str(resolve_url(settings.LOGIN_URL)) def allowed_user_required(view_func): def _checkuser(request, *args, **kwargs): if not request.user.is_authenticated: return redirect(u'{0}?{1}={2}'.format( get_login_url(), REDIRECT_FIELD_NAME, quote(request.get_full_path()), )) if getattr(request.user, 'is_impersonate', False): # Do not allow an impersonated session to use the # impersonate views. return redirect(get_redir_path()) if check_allow_impersonate(request): # user is allowed to impersonate return view_func(request, *args, **kwargs) else: # user not allowed impersonate at all return redirect(get_redir_path()) return _checkuser ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1676920044.0 django-impersonate-1.9.2/impersonate/helpers.py0000644000175000017500000001037014374742354020103 0ustar00pjspjs# -*- coding: utf-8 -*- import re from importlib import import_module from django.core.paginator import EmptyPage, Paginator from django.utils.safestring import mark_safe from .settings import User, settings def get_redir_path(request=None): nextval = None redirect_field_name = settings.REDIRECT_FIELD_NAME if request and redirect_field_name: nextval = request.GET.get(redirect_field_name, None) return nextval or settings.REDIRECT_URL def get_redir_arg(request): redirect_field_name = settings.REDIRECT_FIELD_NAME if redirect_field_name: nextval = request.GET.get(redirect_field_name, None) if nextval: return u'?{0}={1}'.format(redirect_field_name, nextval) return u'' def get_redir_field(request): redirect_field_name = settings.REDIRECT_FIELD_NAME if redirect_field_name: nextval = request.GET.get(redirect_field_name, None) if nextval: return mark_safe( u''.format( redirect_field_name, nextval, ) ) return u'' def get_paginator(request, qs): try: page_number = int(request.GET.get('page', 1)) except ValueError: page_number = 1 paginator = Paginator(qs, int(settings.PAGINATE_COUNT),) try: page = paginator.page(page_number) except EmptyPage: page = None return (paginator, page, page_number) def check_allow_staff(): return not settings.REQUIRE_SUPERUSER def users_impersonable(request): ''' Returns a QuerySet of users that this user can impersonate. Uses the CUSTOM_USER_QUERYSET if set, else, it returns all users ''' if settings.CUSTOM_USER_QUERYSET is not None: custom_queryset_func = import_func_from_string( settings.CUSTOM_USER_QUERYSET ) return custom_queryset_func(request) else: qs = User.objects.all() if not qs.query.order_by: qs = qs.order_by('pk') return qs def check_allow_for_user(request, end_user): ''' Return True if some request can impersonate end_user ''' if check_allow_impersonate(request): # start user can impersonate # Can impersonate superusers if ALLOW_SUPERUSER is True # Can impersonate anyone who is in your queryset of 'who i can impersonate'. allow_superusers = settings.ALLOW_SUPERUSER upk = end_user.pk return ( (request.user.is_superuser and allow_superusers) or not end_user.is_superuser ) and users_impersonable(request).filter(pk=upk).exists() # start user not allowed impersonate at all return False def import_func_from_string(string_name): ''' Given a string like 'mod.mod2.funcname' which refers to a function, return that function so it can be called ''' mod_name, func_name = string_name.rsplit('.', 1) mod = import_module(mod_name) return getattr(mod, func_name) def check_allow_impersonate(request): ''' Returns True if this request is allowed to do any impersonation. Uses the CUSTOM_ALLOW function if required, else looks at superuser/staff status and REQUIRE_SUPERUSER ''' if settings.CUSTOM_ALLOW is not None: custom_allow_func = import_func_from_string(settings.CUSTOM_ALLOW) return custom_allow_func(request) else: # default allow checking: if not request.user.is_superuser: if not request.user.is_staff or not check_allow_staff(): return False return True def check_allow_for_uri(uri): uri = uri.lstrip('/') exclusions = settings.URI_EXCLUSIONS if not isinstance(exclusions, (list, tuple)): exclusions = (exclusions,) for exclusion in exclusions: if re.search(exclusion, uri): return False return True def check_read_only(request): ''' Returns True if can only do read only requests. Uses the CUSTOM_READ_ONLY function if required, else looks at the READ_ONLY setting. ''' if settings.CUSTOM_READ_ONLY is not None: custom_read_only_func = import_func_from_string(settings.CUSTOM_READ_ONLY) return custom_read_only_func(request) return settings.READ_ONLY ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1698496703.0 django-impersonate-1.9.2/impersonate/middleware.py0000600000175000017500000000454414517200277020544 0ustar00pjspjs# -*- coding: utf-8 -*- from datetime import datetime, timedelta, timezone from django.http import HttpResponseNotAllowed from django.shortcuts import redirect from django.utils.deprecation import MiddlewareMixin from django.utils.functional import SimpleLazyObject from .compat import reverse from .helpers import User, check_allow_for_uri, check_allow_for_user, check_read_only from .settings import settings class ImpersonateMiddleware(MiddlewareMixin): def process_request(self, request): _usr = request.user # save as local var to prevent infinite recursion def _get_usr(): # This is all to avoid querying for the "User" instance before # it's actually necessary. _usr.is_impersonate = False return _usr request.user = SimpleLazyObject(_get_usr) request.impersonator = None if '_impersonate' in request.session and request.user.is_authenticated: if settings.MAX_DURATION: if request.path == reverse('impersonate-stop'): return if '_impersonate_start' not in request.session: return start_time = datetime.fromtimestamp( request.session['_impersonate_start'], timezone.utc ) delta = timedelta(seconds=settings.MAX_DURATION) if datetime.now(timezone.utc) - start_time > delta: return redirect('impersonate-stop') new_user_id = request.session['_impersonate'] if isinstance(new_user_id, User): # Edge case for issue 15 new_user_id = new_user_id.pk try: new_user = User.objects.get(pk=new_user_id) except User.DoesNotExist: return if check_read_only(request) and request.method not in ['GET', 'HEAD', 'OPTIONS']: return HttpResponseNotAllowed(['GET', 'HEAD', 'OPTIONS']) if check_allow_for_user(request, new_user) and check_allow_for_uri( request.path ): request.impersonator = request.user request.user = new_user request.user.is_impersonate = True request.user.impersonator = request.impersonator request.real_user = request.impersonator or request.user ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1700765883.9852455 django-impersonate-1.9.2/impersonate/migrations/0000755000175000017500000000000014527720274020237 5ustar00pjspjs././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1583548731.0 django-impersonate-1.9.2/impersonate/migrations/0001_initial.py0000664000175000017500000000247113630604473022704 0ustar00pjspjs# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models from django.conf import settings import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] operations = [ migrations.CreateModel( name='ImpersonationLog', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('session_key', models.CharField(help_text='The Django session request key.', max_length=40)), ('session_started_at', models.DateTimeField(help_text='The time impersonation began.', null=True, blank=True)), ('session_ended_at', models.DateTimeField(help_text='The time impersonation ended.', null=True, blank=True)), ('impersonating', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='impersonated_by', to=settings.AUTH_USER_MODEL, help_text='The user being impersonated.')), ('impersonator', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='impersonations', to=settings.AUTH_USER_MODEL, help_text='The user doing the impersonating.')), ], ), ] ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1583548731.0 django-impersonate-1.9.2/impersonate/migrations/__init__.py0000664000175000017500000000000013630604473022334 0ustar00pjspjs././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1601940927.0 django-impersonate-1.9.2/impersonate/models.py0000664000175000017500000000325113736726677017741 0ustar00pjspjs# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models from django.conf import settings from django.utils.duration import duration_string class ImpersonationLog(models.Model): ''' Stores details of each impersonation session. This model is used to persist details of impersonations. It hooks in to the session_begin and session_end signals to capture the details of the user impersonating and the user who is being impersonated. It also stores the Django session key. ''' impersonator = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, help_text='The user doing the impersonating.', related_name='impersonations', ) impersonating = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='impersonated_by', help_text='The user being impersonated.', ) session_key = models.CharField( max_length=40, help_text='The Django session request key.', ) session_started_at = models.DateTimeField( help_text='The time impersonation began.', null=True, blank=True ) session_ended_at = models.DateTimeField( help_text='The time impersonation ended.', null=True, blank=True ) @property def duration(self): return self._duration() def _duration(self): if all((self.session_started_at, self.session_ended_at)): return duration_string( self.session_ended_at - self.session_started_at, ) return '' _duration.short_description = 'Duration' ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1676920044.0 django-impersonate-1.9.2/impersonate/settings.py0000644000175000017500000000211014374742354020272 0ustar00pjspjs# -*- coding: utf-8 -*- from django.conf import settings as django_settings from django.contrib.auth import get_user_model User = get_user_model() username_field = getattr(User, 'USERNAME_FIELD', 'username') _settings = { 'MAX_FILTER_SIZE': 100, 'REDIRECT_FIELD_NAME': None, 'PAGINATE_COUNT': 20, 'REQUIRE_SUPERUSER': False, 'CUSTOM_USER_QUERYSET': None, 'ALLOW_SUPERUSER': False, 'CUSTOM_ALLOW': None, 'URI_EXCLUSIONS': (r'^admin/',), 'DISABLE_LOGGING': False, 'USE_HTTP_REFERER': False, 'LOOKUP_TYPE': 'icontains', 'SEARCH_FIELDS': [username_field, 'first_name', 'last_name', 'email'], 'REDIRECT_URL': getattr(django_settings, 'LOGIN_REDIRECT_URL', u'/'), 'READ_ONLY': False, 'CUSTOM_READ_ONLY': None, 'ADMIN_DELETE_PERMISSION': False, 'ADMIN_ADD_PERMISSION': False, 'ADMIN_READ_ONLY': True, 'MAX_DURATION': None, } class Settings(object): def __getattribute__(self, name): sdict = getattr(django_settings, 'IMPERSONATE', {}) return sdict.get(name, _settings.get(name)) settings = Settings() ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1608174858.0 django-impersonate-1.9.2/impersonate/signals.py0000644000175000017500000000632013766546412020102 0ustar00pjspjs# -*- coding: utf-8 -*- import logging import hashlib from django.dispatch import Signal, receiver from django.utils.timezone import now as tz_now from django.utils.crypto import get_random_string from .settings import settings from .models import ImpersonationLog logger = logging.getLogger(__name__) # signal sent when an impersonation session begins # providing_args=['impersonator', 'impersonating', 'request'] session_begin = Signal() # signal sent when an impersonation session ends # providing_args=['impersonator', 'impersonating', 'request'] session_end = Signal() ID_LENGTH = 12 def gen_unique_id(): return hashlib.sha1( u'{0}:{1}'.format(get_random_string(ID_LENGTH), tz_now()).encode('utf-8') ).hexdigest() @receiver(session_begin, dispatch_uid='impersonate.signals.on_session_begin') def on_session_begin(sender, **kwargs): ''' Create a new ImpersonationLog object. ''' impersonator = kwargs.get('impersonator') impersonating = kwargs.get('impersonating') logger.info(u'{0} has started impersonating {1}.'.format( impersonator, impersonating, )) if settings.DISABLE_LOGGING: return request = kwargs.get('request') session_key = gen_unique_id() ImpersonationLog.objects.create( impersonator=impersonator, impersonating=impersonating, session_key=session_key, session_started_at=tz_now() ) request.session['_impersonate_session_id'] = session_key request.session.modified = True @receiver(session_end, dispatch_uid='impersonate.signals.on_session_end') def on_session_end(sender, **kwargs): ''' Update ImpersonationLog with the end timestamp. This uses the combination of session_key, impersonator and user being impersonated to look up the corresponding impersonation log object. ''' impersonator = kwargs.get('impersonator') impersonating = kwargs.get('impersonating') logger.info(u'{0} has finished impersonating {1}.'.format( impersonator, impersonating, )) if settings.DISABLE_LOGGING: return request = kwargs.get('request') session_key = request.session.get('_impersonate_session_id', None) try: # look for unfinished sessions that match impersonator / subject log = ImpersonationLog.objects.get( impersonator=impersonator, impersonating=impersonating, session_key=session_key, session_ended_at__isnull=True, ) log.session_ended_at = tz_now() log.save() except ImpersonationLog.DoesNotExist: logger.debug( (u'Unfinished ImpersonationLog could not be found for: ' u'{0}, {1}, {2}').format( impersonator, impersonating, session_key, ) ) except ImpersonationLog.MultipleObjectsReturned: logger.debug( (u'Multiple unfinished ImpersonationLog matching: ' u'{0}, {1}, {2}').format( impersonator, impersonating, session_key, ) ) del request.session['_impersonate_session_id'] request.session.modified = True ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1700765883.9819121 django-impersonate-1.9.2/impersonate/templates/0000755000175000017500000000000014527720274020061 5ustar00pjspjs././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1700765883.9852455 django-impersonate-1.9.2/impersonate/templates/impersonate/0000755000175000017500000000000014527720274022407 5ustar00pjspjs././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1583548731.0 django-impersonate-1.9.2/impersonate/templates/impersonate/list_users.html0000664000175000017500000000115313630604473025467 0ustar00pjspjs Django Impersonate User List

User List - Page {{ page_number }}

{% if page.object_list %}
    {% for user in page.object_list %}
  • {{ user }} - Impersonate
  • {% endfor %}
{% endif %} {% if page.has_previous %} Previous Page   {% endif %} {% if page.has_next %} Next Page   {% endif %} ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1583548731.0 django-impersonate-1.9.2/impersonate/templates/impersonate/search_users.html0000664000175000017500000000171313630604473025763 0ustar00pjspjs Django Impersonate - Search Users

Search Users {% if query %}- Page {{ page_number }}{% endif %}

Enter Search Query:

{{redirect_field}}
{% if query and page.object_list %}
    {% for user in page.object_list %}
  • {{ user }} - Impersonate
  • {% endfor %}
{% endif %} {% if query and page.has_previous %} Previous Page   {% endif %} {% if query and page.has_next %} Next Page   {% endif %} ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1698496703.0 django-impersonate-1.9.2/impersonate/tests.py0000600000175000017500000010542514517200277017571 0ustar00pjspjs# -*- coding: utf-8 -*- ''' Tests Factory creates 4 User accounts. user1: id = 1 is_superuser = True is_staff = True user2: id = 2 is_superuser = True is_staff = True user3: id = 3 is_superuser = False is_staff = True user4: id = 4 is_superuser = False is_staff = False ''' from datetime import datetime, timedelta, timezone from distutils.version import LooseVersion from unittest.mock import PropertyMock, patch from urllib.parse import urlencode, urlsplit import django from django.contrib.admin.sites import AdminSite from django.contrib.auth import get_user_model from django.http import HttpResponse from django.test import TestCase from django.test.client import Client, RequestFactory from django.test.utils import override_settings from django.urls import include, path from django.utils.duration import duration_string from .admin import ( ImpersonationLogAdmin, ImpersonatorFilter, SessionStateFilter, ) from .compat import reverse from .helpers import users_impersonable from .models import ImpersonationLog from .signals import session_begin, session_end User = get_user_model() django_version_loose = LooseVersion(django.get_version()) def _get_location(response): # For 2.2 compat. Remove once 2.2 support is EOL if hasattr(response, 'headers'): return response.headers['location'] return response._headers['location'][1] def test_view(request): return HttpResponse('OK {0}'.format(request.user)) urlpatterns = [ path('test-view/', test_view, name='impersonate-test'), path('another-view/', test_view, name='another-test-view'), path('', include('impersonate.urls')), ] def test_allow(request): ''' Used via the IMPERSONATE['CUSTOM_ALLOW'] setting. Simple check for the user to be auth'd and a staff member. ''' return request.user.is_authenticated and request.user.is_staff def test_allow2(request): ''' Used via the IMPERSONATE['CUSTOM_ALLOW'] setting. Always return False ''' return False def test_qs(request): ''' Used via the IMPERSONAT['CUSTOM_USER_QUERYSET'] setting. Simple function to return all users. ''' return User.objects.all().order_by('pk') def test_allow_read_only(request): ''' Used via the IMPERSONATE['CUSTOM_READ_ONLY'] setting. Simple check that the user is not a superuser. ''' return not request.user.is_superuser class UserFactory(object): @staticmethod def create(**kwargs): password = kwargs.pop('password', None) kwargs['email'] = '{0}@test-email.com'.format( kwargs['username'] ).lower() user = User.objects.create(**kwargs) if password: user.set_password(password) user.save() return user class TestMiddleware(TestCase): def setUp(self): from impersonate.middleware import ImpersonateMiddleware self.superuser = UserFactory.create( username='superuser', is_superuser=True, ) self.user = UserFactory.create(username='regular') self.factory = RequestFactory() def dummy_get_response(request): return None self.middleware = ImpersonateMiddleware(dummy_get_response) def _impersonated_request(self, use_id=True, _impersonate_start=None): request = self.factory.get('/') request.user = self.superuser request.session = { '_impersonate': self.user.pk if use_id else self.user, '_impersonate_start': _impersonate_start, } self.middleware.process_request(request) # Check request.user and request.user.real_user self.assertEqual(request.user, self.user) self.assertEqual(request.impersonator, self.superuser) self.assertEqual(request.user.impersonator, self.superuser) self.assertEqual(request.real_user, self.superuser) self.assertTrue(request.user.is_impersonate) def test_impersonated_request(self): self._impersonated_request() def test_impersonated_request_non_id(self): ''' Test to ensure User objects don't kill the app. See Issue #15 ''' self._impersonated_request(use_id=False) @override_settings(IMPERSONATE={'MAX_DURATION': 3600}) def test_impersonated_request_with_max_duration(self): self._impersonated_request( _impersonate_start=datetime.now(timezone.utc).timestamp() ) @override_settings(IMPERSONATE={'MAX_DURATION': 5, 'REDIRECT_URL': '/foo/'}) def test_impersonate_timeout_not_redirect_loop(self): ''' Test to ensure that when MAX_DURATION is reached dont create a redirect loop. See Issue #67 ''' self._impersonated_request( _impersonate_start=datetime.now(timezone.utc).timestamp() ) # new request to see if the redirect to stop request = self.factory.get('/') request.user = self.superuser past_time = datetime.now(timezone.utc) - timedelta(hours=1) request.session = { '_impersonate': self.user, '_impersonate_start': past_time.timestamp(), } request = self.middleware.process_request(request) # Check does the redirect to stop the impersonate self.assertEqual(request.status_code, 302) self.assertEqual(request.url, reverse('impersonate-stop')) # Check impersonate stop redirects to the REDIRECT_URL request = self.client.get(reverse('impersonate-stop')) self.assertEqual(request.status_code, 302) self.assertEqual(request.url, '/foo/') @override_settings(IMPERSONATE={'MAX_DURATION': 3600}) def test_reject_without_start_time(self): ''' Test to ensure that requests without a start time are rejected when MAX_DURATION is set ''' request = self.factory.get('/') request.user = self.superuser request.session = { '_impersonate': self.user.pk, } self.middleware.process_request(request) self.assertEqual(request.user, self.superuser) self.assertFalse(request.user.is_impersonate) @override_settings(IMPERSONATE={'MAX_DURATION': 3600}) def test_reject_expired_impersonation(self): ''' Test to ensure that requests with a start time before (now - MAX_DURATION) are rejected ''' request = self.factory.get('/') request.user = self.superuser request.session = { '_impersonate': self.user.pk, '_impersonate_start': ( datetime.now(timezone.utc) - timedelta(seconds=3601) ).timestamp(), } response = self.middleware.process_request(request) self.assertEqual(response.status_code, 302) self.assertEqual(response.get('Location'), reverse('impersonate-stop')) def test_not_impersonated_request(self, use_id=True): """Check the real_user request attr is set correctly when **not** impersonating.""" request = self.factory.get('/') request.user = self.user request.session = {} self.middleware.process_request(request) # Check request.user and request.user.real_user self.assertEqual(request.user, self.user) self.assertIsNone(request.impersonator, None) self.assertEqual(request.real_user, self.user) self.assertFalse(request.user.is_impersonate) class TestImpersonation(TestCase): def setUp(self): self.client = Client() user_data = ( ('John', 'Smith', True, True), ('John', 'Doe', True, True), ('', '', False, True), ('', '', False, False), ) for cnt, data in enumerate(user_data): UserFactory.create( **{ 'username': 'user{0}'.format(cnt + 1), 'first_name': data[0], 'last_name': data[1], 'is_superuser': data[2], 'is_staff': data[3], 'password': 'foobar', } ) def _impersonate_helper( self, user, passwd, user_id_to_impersonate, qwargs={}, starting_url=None, ): ''' Trigger impersonate mode for a particular user id, using the specified authenticated user. The HTTP_REFERER can be simulated by passing the optional `starting_url` arg. ''' self.client.login(username=user, password=passwd) url = reverse('impersonate-start', args=[user_id_to_impersonate]) if qwargs: url += '?{0}'.format(urlencode(qwargs)) args = [url] kwargs = {} if starting_url: kwargs['HTTP_REFERER'] = starting_url return self.client.get(*args, **kwargs) def _redirect_check(self, response, new_path): ''' Needed because assertRedirect fails because it checks that the new path is able to be fetched. That's going to raise a TemplateDoesNotExist exception (usually). This is just a work around. ''' url = response['Location'] scheme, netloc, path, query, fragment = urlsplit(url) self.assertEqual(path, new_path) def test_user_count(self): self.assertEqual(User.objects.count(), 4) def test_dont_impersonate_superuser(self): self._impersonate_helper('user1', 'foobar', 2) self.assertEqual(self.client.session.get('_impersonate'), None) self.client.logout() # Try again with normal staff user self._impersonate_helper('user3', 'foobar', 2) self.assertEqual(self.client.session.get('_impersonate'), None) self.client.logout() def test_successful_impersonation(self): self._impersonate_helper('user1', 'foobar', 4) self.assertEqual(self.client.session['_impersonate'], 4) self.assertIn('_impersonate_start', self.client.session) self.client.get(reverse('impersonate-stop')) self.assertEqual(self.client.session.get('_impersonate'), None) self.assertNotIn('_impersonate_start', self.client.session) self.client.logout() def test_successful_impersonation_signals(self): # flags used to determine that signals have been sent self.session_begin_fired = False self.session_end_fired = False def on_session_begin(sender, **kwargs): self.session_begin_fired = True self.assertIsNone(sender) self.assertIsNotNone(kwargs.pop('request', None)) self.assertEqual(kwargs.pop('impersonator').username, 'user1') self.assertEqual(kwargs.pop('impersonating').username, 'user4') def on_session_end(sender, **kwargs): self.session_end_fired = True self.assertIsNone(sender) self.assertIsNotNone(kwargs.pop('request', None)) self.assertEqual(kwargs.pop('impersonator').username, 'user1') impersonating = kwargs.pop('impersonating') self.assertEqual(impersonating.username, 'user4') self.assertFalse(self.session_begin_fired) self.assertFalse(self.session_end_fired) session_begin.connect(on_session_begin) session_end.connect(on_session_end) # start the impersonation and check that the _begin signal is sent self._impersonate_helper('user1', 'foobar', 4) self.assertEqual(self.client.session['_impersonate'], 4) self.assertTrue(self.session_begin_fired) self.assertFalse(self.session_end_fired) # now stop the impersonation and check that the _end signal is sent self.client.get(reverse('impersonate-stop')) self.assertEqual(self.client.session.get('_impersonate'), None) self.assertTrue(self.session_end_fired) # Reset for edge case failure. Ref Issue #34 self.session_begin_fired = False self.session_end_fired = False self.assertFalse(self.session_begin_fired) self.assertFalse(self.session_end_fired) # Start impersonation self._impersonate_helper('user1', 'foobar', 4) self.assertTrue(self.session_begin_fired) self.assertFalse(self.session_end_fired) _session = self.client.session _session['_impersonate'] = 1234 # Invalid User ID _session.save() self.client.get(reverse('impersonate-stop')) self.assertFalse(self.session_end_fired) self.client.logout() session_begin.disconnect(on_session_begin) session_end.disconnect(on_session_end) def test_successsful_impersonation_by_staff(self): self._impersonate_helper('user3', 'foobar', 4) self.assertEqual(self.client.session['_impersonate'], 4) self.client.get(reverse('impersonate-stop')) self.assertEqual(self.client.session.get('_impersonate'), None) self.client.logout() @override_settings(IMPERSONATE={'ALLOW_SUPERUSER': True}) def test_successful_impersonation_of_superuser(self): self._impersonate_helper('user1', 'foobar', 2) self.assertEqual(self.client.session.get('_impersonate'), 2) user = User.objects.get(pk=self.client.session.get('_impersonate')) self.assertTrue(user.is_superuser) self.client.get(reverse('impersonate-stop')) self.assertEqual(self.client.session.get('_impersonate'), None) self.client.logout() @override_settings(IMPERSONATE={'REQUIRE_SUPERUSER': True}) def test_unsuccessful_impersonation_by_staff(self): self._impersonate_helper('user3', 'foobar', 4) self.assertEqual(self.client.session.get('_impersonate'), None) self.client.logout() @override_settings(IMPERSONATE={'ALLOW_SUPERUSER': False}) def test_unsuccessful_impersonation_of_superuser(self): self._impersonate_helper('user1', 'foobar', 2) self.assertEqual(self.client.session.get('_impersonate'), None) self.client.logout() def test_unsuccessful_impersonation(self): self._impersonate_helper('user4', 'foobar', 3) self.assertEqual(self.client.session.get('_impersonate'), None) self.client.logout() def test_unsuccessful_impersonation_restricted_uri(self): response = self._impersonate_helper('user1', 'foobar', 4) self.assertEqual(self.client.session['_impersonate'], 4) # Don't allow impersonated users to use impersonate views with self.settings(IMPERSONATE={'REDIRECT_URL': '/test-redirect/'}): response = self.client.get(reverse('impersonate-list')) self._redirect_check(response, '/test-redirect/') # Don't allow impersonated users to use restricted URI's with self.settings(IMPERSONATE={'URI_EXCLUSIONS': r'^test-view/'}): response = self.client.get(reverse('impersonate-test')) self.assertEqual( ('user1' in str(response.content)), True ) # !user4 self.client.logout() def test_unsuccessful_request_unauth_user(self): response = self.client.get(reverse('impersonate-list')) self._redirect_check(response, '/accounts/login/') def test_unsuccessful_request_invalid_user_value(self): response = self._impersonate_helper( 'user1', 'foobar', 'some/bad/value' ) self.assertEqual(response.status_code, 404) @override_settings(IMPERSONATE={'REDIRECT_URL': '/test-redirect/'}) def test_successful_impersonation_redirect_url(self): response = self._impersonate_helper('user1', 'foobar', 4) self.assertEqual(self.client.session['_impersonate'], 4) self._redirect_check(response, '/test-redirect/') self.client.get(reverse('impersonate-stop')) self.assertEqual(self.client.session.get('_impersonate'), None) self.client.logout() @override_settings(IMPERSONATE={'REDIRECT_FIELD_NAME': 'next'}) def test_successful_impersonation_redirect_field_name(self): response = self._impersonate_helper( 'user1', 'foobar', 4, {'next': '/test-next/'}, ) self.assertEqual(self.client.session['_impersonate'], 4) self._redirect_check(response, '/test-next/') self.client.get(reverse('impersonate-stop')) self.assertEqual(self.client.session.get('_impersonate'), None) self.client.logout() @override_settings(IMPERSONATE={'REDIRECT_URL': '/test-redirect-2/'}) def test_successful_impersonation_login_redirect_url(self): response = self._impersonate_helper('user1', 'foobar', 4) self.assertEqual(self.client.session['_impersonate'], 4) self._redirect_check(response, '/test-redirect-2/') self.client.get(reverse('impersonate-stop')) self.assertEqual(self.client.session.get('_impersonate'), None) self.client.logout() @override_settings(IMPERSONATE={'USE_HTTP_REFERER': True}) def test_returned_to_original_path_after_impersonation(self): # show with and without querystrings works for starting_url in [ reverse('another-test-view'), reverse('another-test-view') + '?test=true&foo=bar', ]: response = self._impersonate_helper( user='user1', passwd='foobar', user_id_to_impersonate=4, starting_url=starting_url, ) self.assertEqual(self.client.session['_impersonate'], 4) self._redirect_check(response, '/accounts/profile/') response = self.client.get(reverse('impersonate-stop')) # Can't use self._redirect_check here because it doesn't # compare querystrings self.assertEqual( 'http://testserver{0}'.format(starting_url), _get_location(response), ) self.assertEqual(self.client.session.get('_impersonate'), None) self.client.logout() def test_successful_impersonation_end_redirect_url(self): for url_path, use_refer in ( (reverse('another-test-view'), True), (reverse('another-test-view'), False), ): with self.settings( IMPERSONATE={ 'REDIRECT_URL': '/test-redirect/', 'USE_HTTP_REFERER': use_refer, } ): response = self._impersonate_helper( 'user1', 'foobar', 4, starting_url=url_path, ) self.assertEqual(self.client.session['_impersonate'], 4) self._redirect_check(response, '/test-redirect/') response = self.client.get(reverse('impersonate-stop')) use_url_path = url_path if use_refer else '/test-redirect/' if not use_refer and django_version_loose >= '1.9': self.assertEqual( use_url_path, _get_location(response), ) else: self.assertEqual( 'http://testserver{0}'.format(use_url_path), _get_location(response), ) self.assertEqual(self.client.session.get('_impersonate'), None) self.client.logout() def test_user_listing_and_pagination(self): self.client.login(username='user1', password='foobar') response = self.client.get(reverse('impersonate-list')) self.assertEqual(response.context['users'].count(), 4) with self.settings(IMPERSONATE={'PAGINATE_COUNT': 2}): response = self.client.get(reverse('impersonate-list')) self.assertEqual(response.context['paginator'].num_pages, 2) # Out of range page number response = self.client.get(reverse('impersonate-list'), {'page': 10}) self.assertEqual(response.context['page_number'], 10) self.assertEqual(response.context['page'], None) # Invalid integer response = self.client.get(reverse('impersonate-list'), {'page': 'no'}) self.assertEqual(response.context['page_number'], 1) self.assertEqual(len(response.context['page'].object_list), 4) self.client.logout() def test_user_search_and_pagination(self): self.client.login(username='user1', password='foobar') response = self.client.get( reverse('impersonate-search'), {'q': 'john'}, ) self.assertEqual(response.context['users'].count(), 2) response = self.client.get( reverse('impersonate-search'), {'q': 'doe'}, ) self.assertEqual(response.context['users'].count(), 1) response = self.client.get( reverse('impersonate-search'), {'q': ' john doe'}, ) self.assertEqual(response.context['users'].count(), 1) response = self.client.get( reverse('impersonate-search'), {'q': 'noresultsfound'}, ) self.assertEqual(response.context['users'].count(), 0) with self.settings(IMPERSONATE={'PAGINATE_COUNT': 2}): response = self.client.get( reverse('impersonate-search'), {'q': 'test-email'}, ) self.assertEqual(response.context['paginator'].num_pages, 2) self.assertEqual(response.context['users'].count(), 4) self.client.logout() @override_settings( IMPERSONATE={'SEARCH_FIELDS': ['first_name', 'last_name']} ) def test_user_search_custom_fields(self): self.client.login(username='user1', password='foobar') response = self.client.get( reverse('impersonate-search'), {'q': 'john'}, ) self.assertEqual(response.context['users'].count(), 2) response = self.client.get( reverse('impersonate-search'), {'q': 'doe'}, ) self.assertEqual(response.context['users'].count(), 1) response = self.client.get( reverse('impersonate-search'), {'q': 'user'}, ) self.assertEqual(response.context['users'].count(), 0) self.client.logout() @override_settings(IMPERSONATE={'LOOKUP_TYPE': 'exact'}) def test_user_search_custom_lookup(self): self.client.login(username='user1', password='foobar') response = self.client.get( reverse('impersonate-search'), {'q': 'John'}, ) self.assertEqual(response.context['users'].count(), 2) response = self.client.get( reverse('impersonate-search'), {'q': 'Doe'}, ) self.assertEqual(response.context['users'].count(), 1) response = self.client.get( reverse('impersonate-search'), {'q': 'john'}, ) self.assertEqual(response.context['users'].count(), 0) response = self.client.get( reverse('impersonate-search'), {'q': 'doe'}, ) self.assertEqual(response.context['users'].count(), 0) @override_settings(IMPERSONATE={'REDIRECT_FIELD_NAME': 'next'}) def test_redirect_field_name(self): self.client.login(username='user1', password='foobar') response = self.client.get(reverse('impersonate-list')) self.assertEqual(response.context['redirect'], '') # Add redirect value to query response = self.client.get( reverse('impersonate-list'), {'next': '/test/'}, ) self.assertEqual(response.context['redirect'], '?next=/test/') self.client.logout() @override_settings(IMPERSONATE={'REDIRECT_FIELD_NAME': 'next'}) def test_redirect_field_name_unicode(self): ''' Specific test to account for Issue #21 ''' self.client.login(username='user1', password='foobar') response = self.client.get(reverse('impersonate-list')) self.assertEqual(response.context['redirect'], '') # Add redirect value to query response = self.client.get( reverse('impersonate-list'), {'next': u'/über/'}, ) self.assertEqual(response.context['redirect'], u'?next=/über/') self.client.logout() @override_settings( IMPERSONATE={'CUSTOM_ALLOW': 'impersonate.tests.test_allow'} ) def test_custom_user_allow_function(self): self.client.login(username='user1', password='foobar') response = self.client.get(reverse('impersonate-list')) self.assertEqual(response.context['users'].count(), 4) self.client.logout() def test_custom_user_allow_function_false(self): ''' Edge case test. ''' response = self._impersonate_helper('user1', 'foobar', 4) with self.settings( IMPERSONATE={'CUSTOM_ALLOW': 'impersonate.tests.test_allow2'} ): response = self.client.get(reverse('impersonate-test')) self.assertEqual( ('user1' in str(response.content)), True ) # !user4 def test_custom_user_queryset_ordered(self): qs = users_impersonable(None) self.assertEqual(qs.ordered, True) @override_settings( IMPERSONATE={'CUSTOM_USER_QUERYSET': 'impersonate.tests.test_qs'} ) def test_custom_user_queryset_function(self): self.client.login(username='user1', password='foobar') response = self.client.get(reverse('impersonate-list')) self.assertEqual(response.context['users'].count(), 4) self.client.logout() def test_disable_impersonatelog_logging(self): self.assertFalse(ImpersonationLog.objects.exists()) self._impersonate_helper('user1', 'foobar', 4) self.assertFalse(ImpersonationLog.objects.exists()) @override_settings(IMPERSONATE={'DISABLE_LOGGING': False}) def test_signals_session_begin_impersonatelog(self): self.assertFalse(ImpersonationLog.objects.exists()) self._impersonate_helper('user1', 'foobar', 4) log = ImpersonationLog.objects.get() session_key = self.client.session.get('_impersonate_session_id') self.assertEqual(log.impersonator.id, 1) self.assertEqual(log.impersonating.id, 4) self.assertEqual(log.session_key, session_key) self.assertIsNotNone(log.session_started_at) self.assertIsNone(log.session_ended_at) @override_settings(IMPERSONATE={'DISABLE_LOGGING': False}) def test_signals_session_end_impersonatelog(self): self.assertFalse(ImpersonationLog.objects.exists()) self._impersonate_helper('user1', 'foobar', 4) session_key = self.client.session.get('_impersonate_session_id') self.client.get(reverse('impersonate-stop')) none_session_key = self.client.session.get('_impersonate_session_id') log = ImpersonationLog.objects.get() self.assertEqual(log.impersonator.id, 1) self.assertEqual(log.impersonating.id, 4) self.assertEqual(log.session_key, session_key) self.assertIsNotNone(log.session_started_at) self.assertIsNotNone(log.session_ended_at) self.assertIsNone(none_session_key) self.assertTrue(log.session_ended_at > log.session_started_at) self.assertEqual( log.duration, duration_string(log.session_ended_at - log.session_started_at), ) @override_settings(IMPERSONATE={'DISABLE_LOGGING': False}) def test_impersonatelog_admin_session_state_filter(self): ''' Based on http://stackoverflow.com/questions/16751325/test-a-custom-filter-in-admin-py ''' self.assertFalse(ImpersonationLog.objects.exists()) self._impersonate_helper('user1', 'foobar', 4) self.client.get(reverse('impersonate-stop')) self._impersonate_helper('user2', 'foobar', 4) _filter = SessionStateFilter( None, {}, ImpersonationLog, ImpersonationLogAdmin, ) qs = _filter.queryset(None, ImpersonationLog.objects.all()) self.assertEqual(qs.count(), 2) def _format_params(val): # Django 5.x returns request querystring params as a list # https://github.com/django/django/commit/d03dc63177ad3ba6e685e314eed45d6a8ec5cb0c if django_version_loose >= '5.0': return {'session': [val]} return {'session': val} _filter = SessionStateFilter( None, _format_params('complete'), ImpersonationLog, ImpersonationLogAdmin, ) qs = _filter.queryset(None, ImpersonationLog.objects.all()) self.assertEqual(qs.count(), 1) _filter = SessionStateFilter( None, _format_params('incomplete'), ImpersonationLog, ImpersonationLogAdmin, ) qs = _filter.queryset(None, ImpersonationLog.objects.all()) self.assertEqual(qs.count(), 1) @override_settings(IMPERSONATE={'DISABLE_LOGGING': False}) def test_impersonatelog_admin_impersonator_filter(self): self.assertFalse(ImpersonationLog.objects.exists()) self._impersonate_helper('user1', 'foobar', 4) self.client.get(reverse('impersonate-stop')) self._impersonate_helper('user2', 'foobar', 4) self.client.get(reverse('impersonate-stop')) self._impersonate_helper('user3', 'foobar', 4) self.client.get(reverse('impersonate-stop')) model_admin = ImpersonationLogAdmin(ImpersonationLog, AdminSite()) _filter = ImpersonatorFilter(None, {}, ImpersonationLog, model_admin,) qs = _filter.queryset(None, ImpersonationLog.objects.all()) self.assertEqual(qs.count(), 3) _filter = ImpersonatorFilter( None, {'impersonator': '1'}, ImpersonationLog, model_admin, ) qs = _filter.queryset(None, ImpersonationLog.objects.all()) self.assertEqual(qs.count(), 1) _filter = ImpersonatorFilter( None, {'impersonator': '2'}, ImpersonationLog, model_admin, ) qs = _filter.queryset(None, ImpersonationLog.objects.all()) self.assertEqual(qs.count(), 1) _filter = ImpersonatorFilter( None, {'impersonator': '3'}, ImpersonationLog, model_admin, ) qs = _filter.queryset(None, ImpersonationLog.objects.all()) self.assertEqual(qs.count(), 1) with patch( 'django.contrib.auth.models.AbstractUser.USERNAME_FIELD', new_callable=PropertyMock, return_value='is_active', ): # Check that user1, user2, and user3 are in the lookup options opts = [ (_id, name) for _id, name in _filter.lookups(None, model_admin) ] self.assertTrue(1 in [x[0] for x in opts]) self.assertTrue(2 in [x[0] for x in opts]) self.assertTrue(3 in [x[0] for x in opts]) # Check that `USERNAME_FIELD` field is used # (`username` should not be hard-coded) self.assertTrue(True in [x[1] for x in opts]) @override_settings( IMPERSONATE={'DISABLE_LOGGING': False, 'MAX_FILTER_SIZE': 1} ) def test_impersonatelog_admin_impersonator_filter_max_filter_size(self): self.assertFalse(ImpersonationLog.objects.exists()) self._impersonate_helper('user1', 'foobar', 4) self.client.get(reverse('impersonate-stop')) self._impersonate_helper('user2', 'foobar', 4) self.client.get(reverse('impersonate-stop')) model_admin = ImpersonationLogAdmin(ImpersonationLog, AdminSite()) _filter = ImpersonatorFilter(None, {}, ImpersonationLog, model_admin,) opts = [ (_id, name) for _id, name in _filter.lookups(None, model_admin) ] self.assertEqual(len(opts), 1) def test_impersonatelog_admin_add_delete_permissions(self): model_admin = ImpersonationLogAdmin(ImpersonationLog, AdminSite()) self.assertFalse(model_admin.has_add_permission(None)) self.assertFalse(model_admin.has_delete_permission(None)) # Custom perms with self.settings( IMPERSONATE={ 'ADMIN_DELETE_PERMISSION': True, 'ADMIN_ADD_PERMISSION': True, } ): model_admin = ImpersonationLogAdmin(ImpersonationLog, AdminSite()) self.assertTrue(model_admin.has_add_permission(None)) self.assertTrue(model_admin.has_delete_permission(None)) def test_impersonatelog_admin_change_permissions(self): class FakeRequest: method = 'GET' request = FakeRequest() model_admin = ImpersonationLogAdmin(ImpersonationLog, AdminSite()) self.assertTrue(model_admin.has_change_permission(request)) request.method = 'HEAD' self.assertTrue(model_admin.has_change_permission(request)) request.method = 'OPTIONS' self.assertTrue(model_admin.has_change_permission(request)) request.method = 'POST' self.assertFalse(model_admin.has_change_permission(request)) # Custom perms with self.settings(IMPERSONATE={'ADMIN_READ_ONLY': False}): model_admin = ImpersonationLogAdmin(ImpersonationLog, AdminSite()) request.method = 'GET' self.assertTrue(model_admin.has_change_permission(request)) request.method = 'POST' self.assertTrue(model_admin.has_change_permission(request)) @override_settings(IMPERSONATE={'READ_ONLY': True}) def test_impersonate_read_only(self): self._impersonate_helper('user1', 'foobar', 4) resp = self.client.post(reverse('impersonate-test')) self.assertEqual(resp.status_code, 405) resp = self.client.get(reverse('impersonate-test')) self.assertEqual(resp.status_code, 200) resp = self.client.head(reverse('impersonate-test')) self.assertEqual(resp.status_code, 200) resp = self.client.options(reverse('impersonate-test')) self.assertEqual(resp.status_code, 200) @override_settings(IMPERSONATE={'CUSTOM_READ_ONLY': 'impersonate.tests.test_allow_read_only'}) def test_impersonate_custom_read_only(self): # superuser is able to do all requests self._impersonate_helper('user1', 'foobar', 4) resp = self.client.post(reverse('impersonate-test')) self.assertEqual(resp.status_code, 200) resp = self.client.get(reverse('impersonate-test')) self.assertEqual(resp.status_code, 200) resp = self.client.head(reverse('impersonate-test')) self.assertEqual(resp.status_code, 200) resp = self.client.options(reverse('impersonate-test')) self.assertEqual(resp.status_code, 200) self.client.logout() # staff user is only able to do read only requests self._impersonate_helper('user3', 'foobar', 4) resp = self.client.post(reverse('impersonate-test')) self.assertEqual(resp.status_code, 405) resp = self.client.get(reverse('impersonate-test')) self.assertEqual(resp.status_code, 200) resp = self.client.head(reverse('impersonate-test')) self.assertEqual(resp.status_code, 200) resp = self.client.options(reverse('impersonate-test')) self.assertEqual(resp.status_code, 200) self.client.logout() ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1608745617.0 django-impersonate-1.9.2/impersonate/urls.py0000644000175000017500000000102313770701221017404 0ustar00pjspjs# -*- coding: utf-8 -*- from django.urls import path from . import views urlpatterns = [ path('stop/', views.stop_impersonate, name='impersonate-stop'), path( 'list/', views.list_users, {'template': 'impersonate/list_users.html'}, name='impersonate-list', ), path( 'search/', views.search_users, {'template': 'impersonate/search_users.html'}, name='impersonate-search', ), path('/', views.impersonate, name='impersonate-start'), ] ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1700762756.0 django-impersonate-1.9.2/impersonate/views.py0000600000175000017500000001270414527712204017560 0ustar00pjspjs# -*- coding: utf-8 -*- import logging from datetime import datetime, timezone from django.db.models import Q from django.http import Http404 from django.shortcuts import get_object_or_404, redirect, render from .decorators import allowed_user_required from .helpers import ( check_allow_for_user, get_paginator, get_redir_arg, get_redir_field, get_redir_path, users_impersonable, ) from .settings import User, settings from .signals import session_begin, session_end logger = logging.getLogger(__name__) @allowed_user_required def impersonate(request, uid): ''' Takes in the UID of the user to impersonate. View will fetch the User instance and store it in the request.session under the '_impersonate' key. The middleware will then pick up on it and adjust the request object as needed. Also store the user's 'starting'/'original' URL so we can return them to it. ''' try: new_user = get_object_or_404(User, pk=uid) except ValueError: # Invalid uid value passed logger.error(f'views/impersonate: Invalid value for uid given: {uid}') raise Http404('Invalid value given.') if check_allow_for_user(request, new_user): request.session['_impersonate'] = new_user.pk request.session['_impersonate_start'] = datetime.now( tz=timezone.utc ).timestamp() prev_path = request.META.get('HTTP_REFERER') if prev_path: request.session[ '_impersonate_prev_path' ] = request.build_absolute_uri(prev_path) request.session.modified = True # Let's make sure... # can be used to hook up auditing of the session session_begin.send( sender=None, impersonator=request.user, impersonating=new_user, request=request, ) return redirect(get_redir_path(request)) def stop_impersonate(request): ''' Remove the impersonation object from the session and ideally return the user to the original path they were on. ''' impersonating = request.session.pop('_impersonate', None) if impersonating is not None: try: impersonating = User.objects.get(pk=impersonating) except User.DoesNotExist: # Should never be reached. logger.info( ( u'NOTICE: User being impersonated (PK ' u'{0}) no longer exists.' ).format(impersonating) ) impersonating = None use_refer = settings.USE_HTTP_REFERER request.session.pop('_impersonate_start', None) original_path = request.session.pop('_impersonate_prev_path', None) request.session.modified = True if impersonating is not None: session_end.send( sender=None, impersonator=request.impersonator or request.user, impersonating=impersonating, request=request, ) dest = ( original_path if original_path and use_refer else get_redir_path(request) ) return redirect(dest) @allowed_user_required def list_users(request, template): ''' List all users in the system. Will add 5 items to the context. * users - queryset of all users * paginator - Django Paginator instance * page - Current page of objects (from Paginator) * page_number - Current page number, defaults to 1 * redirect - arg for redirect target, e.g. "?next=/foo/bar" ''' users = users_impersonable(request) paginator, page, page_number = get_paginator(request, users) return render( request, template, { 'users': users, 'paginator': paginator, 'page': page, 'page_number': page_number, 'redirect': get_redir_arg(request), 'redirect_field': get_redir_field(request), }, ) @allowed_user_required def search_users(request, template): ''' Simple search through the users. Will add 7 items to the context. * users - All users that match the query passed. * paginator - Django Paginator instance * page - Current page of objects (from Paginator) * page_number - Current page number, defaults to 1 * query - The search query that was entered * redirect - arg for redirect target, e.g. "?next=/foo/bar" * redirect_field - hidden input field with redirect argument, put this inside search form ''' query = request.GET.get('q', u'') # define search fields and lookup type search_fields = set(settings.SEARCH_FIELDS) lookup_type = settings.LOOKUP_TYPE # prepare kwargs search_q = Q() for term in query.split(): sub_q = Q() for search_field in search_fields: sub_q |= Q(**{'{0}__{1}'.format(search_field, lookup_type): term}) search_q &= sub_q users = users_impersonable(request) users = users.filter(search_q).distinct() paginator, page, page_number = get_paginator(request, users) return render( request, template, { 'users': users, 'paginator': paginator, 'page': page, 'page_number': page_number, 'query': query, 'redirect': get_redir_arg(request), 'redirect_field': get_redir_field(request), }, ) ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1698496703.0 django-impersonate-1.9.2/pyproject.toml0000600000175000017500000000101414517200277016430 0ustar00pjspjs[tool.black] line-length = 79 skip-string-normalization = true target-version = ['py37', 'py38', 'py39', 'py310', 'py311', 'py312'] include = '\.pyi?$' exclude = ''' ( /( \.eggs # exclude a few common directories in the | \.git # root of the project | \.hg | \.mypy_cache | \.tox | \.venv | env | _build | buck-out | build | dist )/ | foo.py # also separately exclude a file named foo.py in # the root of the project ) ''' ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1700765883.9885788 django-impersonate-1.9.2/setup.cfg0000644000175000017500000000004614527720274015356 0ustar00pjspjs[egg_info] tag_build = tag_date = 0 ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1700763219.0 django-impersonate-1.9.2/setup.py0000600000175000017500000000425414527713123015237 0ustar00pjspjsimport os from distutils.core import setup project_name = 'impersonate' long_description = open('README.rst').read() # Idea from django-registration setup.py packages, data_files = [], [] root_dir = os.path.dirname(__file__) if root_dir: os.chdir(root_dir) for dirpath, dirnames, filenames in os.walk(project_name): # Ignore dirnames that start with '.' for i, dirname in enumerate(dirnames): if dirname.startswith('.') or dirname == '__pycache__': del dirnames[i] if '__init__.py' in filenames: pkg = dirpath.replace(os.path.sep, '.') if os.path.altsep: pkg = pkg.replace(os.path.altsep, '.') packages.append(pkg) elif filenames: prefix = dirpath[(len(project_name) + 1) :] for f in filenames: data_files.append(os.path.join(prefix, f)) setup( name='django-impersonate', version=__import__(project_name).get_version(), package_dir={project_name: project_name}, packages=packages, package_data={project_name: data_files}, description='Django app to allow superusers to impersonate other users.', author='Peter Sanchez', author_email='pjs@petersanchez.com', license='BSD License', url='https://code.netlandish.com/~petersanchez/django-impersonate', long_description=long_description, platforms=['any'], classifiers=[ 'Development Status :: 5 - Production/Stable', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Natural Language :: English', 'Operating System :: OS Independent', 'Framework :: Django', 'Framework :: Django :: 3.2', 'Framework :: Django :: 4.0', 'Framework :: Django :: 4.1', 'Framework :: Django :: 4.2', 'Framework :: Django :: 5.0', 'Programming Language :: Python', 'Programming Language :: Python :: 3.7', 'Programming Language :: Python :: 3.8', 'Programming Language :: Python :: 3.9', 'Programming Language :: Python :: 3.10', 'Programming Language :: Python :: 3.11', 'Programming Language :: Python :: 3.12', 'Environment :: Web Environment', ], )