django-impersonate-1.4.1/0000775000175000017500000000000013464407070014724 5ustar pjspjs00000000000000django-impersonate-1.4.1/BSD-LICENSE0000644000175000017500000000301211724703437016334 0ustar pjspjs00000000000000Copyright (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. django-impersonate-1.4.1/CHANGELOG0000664000175000017500000000626613416542574016156 0ustar pjspjs00000000000000Changes ------- 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 ;) django-impersonate-1.4.1/PKG-INFO0000664000175000017500000004744213464407070016034 0ustar pjspjs00000000000000Metadata-Version: 1.1 Name: django-impersonate Version: 1.4.1 Summary: Django app to allow superusers to impersonate other users. Home-page: http://bitbucket.org/petersanchez/django-impersonate/ Author: Peter Sanchez Author-email: petersanchez@gmail.com License: BSD License Description: .. |nlshield| image:: https://img.shields.io/badge/100%25-Netlandish-blue.svg?style=square-flat :target: http://www.netlandish.com ============================== django-impersonate |nlshield| ============================== :Info: Simple application to allow superusers to "impersonate" other non-superuser accounts. :Version: 1.4.1 :Author: Peter Sanchez (http://www.petersanchez.com) Python / Django Support ======================= * Python 3.6+ for Django versions 1.11 - 2.2 **Note:** As of version 1.4 we are only officially supporting Python 3.6+ and Django 1.11+. However, older versions of Python and Django should continue to work. We just will not guarantee it. Dependencies ============ * Depends on your project using the django.contrib.session framework. **NOTE:** * **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_CLASSES #. 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. 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 ``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``. NB 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, } **Note:** This is a new format. The old format is now deprecated and support for the old format will be removed in a future release. 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. 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 (True/False), 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 (True/False) 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 (True/False), 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 emply 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 impesonation. 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 view switch user To return always to the current page after impersonating a user, use request.path: ``switch user`` 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 bool 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 is removed (just shows all). This is used by the "Filter by impersonator" filter. It is optional, and defaults to 100. SETTINGS PRIOR TO VERSION 1.3 ============================= Prior to version 1.3, settings were not stored in a dictionary. They were each an individual setting. For the time being, you can still use individual settings for each option. If present, they will supersede any setting within the ``IMPERSONATE`` dictionary and will also issue a warning that the settings format has changed and you should convert your projects settings to use the new dictionary format. All dictionary options can be used as individual settings by simply prepending ``IMPERSONATE_`` to the name. For example, the following is the dictionary sample from above and it's old style settings equivalent. New format:: IMPERSONATE = { 'REDIRECT_URL': '/some-path/', 'PAGINATE_COUNT': 10, } Deprecated (old) format:: IMPERSONATE_REDIRECT_URL = '/some-path' IMPERSONATE_PAGE_COUNT = 10 Admin ===== As of version 1.3 django-impersonate now includes a helper admin mixin, located at ``imepersonate.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 ======= You need factory_boy installed for tests to run. To install, use:: $ pip install factory_boy **Note:** This is currently not required for Python 3.3+. For more info on factory_boy, see: https://github.com/dnerdy/factory_boy 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:: py3.7-django2.2: commands succeeded py3.7-django2.1: commands succeeded py3.6-django2.2: commands succeeded py3.6-django2.1: commands succeeded py3.7-django2.0: commands succeeded py3.6-django2.0: commands succeeded py3.7-django1.11: commands succeeded py3.6-django1.11: commands succeeded congratulations :) 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. Platform: any Classifier: Development Status :: 4 - Beta Classifier: Intended Audience :: Developers Classifier: License :: OSI Approved :: BSD License Classifier: Natural Language :: English Classifier: Operating System :: OS Independent Classifier: Programming Language :: Python Classifier: Programming Language :: Python :: 2.7 Classifier: Programming Language :: Python :: 3.3 Classifier: Programming Language :: Python :: 3.4 Classifier: Programming Language :: Python :: 3.5 Classifier: Programming Language :: Python :: 3.6 Classifier: Environment :: Web Environment django-impersonate-1.4.1/README.rst0000664000175000017500000003711213464406443016422 0ustar pjspjs00000000000000.. |nlshield| image:: https://img.shields.io/badge/100%25-Netlandish-blue.svg?style=square-flat :target: http://www.netlandish.com ============================== django-impersonate |nlshield| ============================== :Info: Simple application to allow superusers to "impersonate" other non-superuser accounts. :Version: 1.4.1 :Author: Peter Sanchez (http://www.petersanchez.com) Python / Django Support ======================= * Python 3.6+ for Django versions 1.11 - 2.2 **Note:** As of version 1.4 we are only officially supporting Python 3.6+ and Django 1.11+. However, older versions of Python and Django should continue to work. We just will not guarantee it. Dependencies ============ * Depends on your project using the django.contrib.session framework. **NOTE:** * **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_CLASSES #. 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. 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 ``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``. NB 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, } **Note:** This is a new format. The old format is now deprecated and support for the old format will be removed in a future release. 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. 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 (True/False), 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 (True/False) 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 (True/False), 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 emply 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 impesonation. 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 view switch user To return always to the current page after impersonating a user, use request.path: ``switch user`` 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 bool 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 is removed (just shows all). This is used by the "Filter by impersonator" filter. It is optional, and defaults to 100. SETTINGS PRIOR TO VERSION 1.3 ============================= Prior to version 1.3, settings were not stored in a dictionary. They were each an individual setting. For the time being, you can still use individual settings for each option. If present, they will supersede any setting within the ``IMPERSONATE`` dictionary and will also issue a warning that the settings format has changed and you should convert your projects settings to use the new dictionary format. All dictionary options can be used as individual settings by simply prepending ``IMPERSONATE_`` to the name. For example, the following is the dictionary sample from above and it's old style settings equivalent. New format:: IMPERSONATE = { 'REDIRECT_URL': '/some-path/', 'PAGINATE_COUNT': 10, } Deprecated (old) format:: IMPERSONATE_REDIRECT_URL = '/some-path' IMPERSONATE_PAGE_COUNT = 10 Admin ===== As of version 1.3 django-impersonate now includes a helper admin mixin, located at ``imepersonate.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 ======= You need factory_boy installed for tests to run. To install, use:: $ pip install factory_boy **Note:** This is currently not required for Python 3.3+. For more info on factory_boy, see: https://github.com/dnerdy/factory_boy 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:: py3.7-django2.2: commands succeeded py3.7-django2.1: commands succeeded py3.6-django2.2: commands succeeded py3.6-django2.1: commands succeeded py3.7-django2.0: commands succeeded py3.6-django2.0: commands succeeded py3.7-django1.11: commands succeeded py3.6-django1.11: commands succeeded congratulations :) 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. django-impersonate-1.4.1/impersonate/0000775000175000017500000000000013464407070017252 5ustar pjspjs00000000000000django-impersonate-1.4.1/impersonate/__init__.py0000664000175000017500000000130513464406662021370 0ustar pjspjs00000000000000# -*- coding: utf-8 -*- VERSION = (1, 4, 1, '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) django-impersonate-1.4.1/impersonate/admin.py0000664000175000017500000001204413416537255020723 0ustar pjspjs00000000000000# -*- coding: utf-8 -*- import logging from django.contrib import admin from django.utils.html import format_html from django.db.utils import NotSupportedError from .settings import settings from .models import ImpersonationLog from .helpers import User, check_allow_impersonate try: from django.urls import reverse except ImportError: from django.core.urlresolvers import reverse 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 filter is removed (shows only 'All'). ''' 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') ) except (NotSupportedError, NotImplementedError): # Unit tests use sqlite db backend which doesn't support distinct. qs = model_admin.get_queryset(request).only('impersonator_id') ids = set([x.impersonator_id for x in qs]) if len(ids) > MAX_FILTER_SIZE: logger.debug( ('Hiding admin list filter as number of impersonators [{0}] ' 'exceeds MAX_FILTER_SIZE [{1}]').format( len(ids), MAX_FILTER_SIZE, ) ) return 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_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) admin.site.register(ImpersonationLog, ImpersonationLogAdmin) django-impersonate-1.4.1/impersonate/apps.py0000644000175000017500000000025212621020427020553 0ustar pjspjs00000000000000# -*- coding: utf-8 -*- from django.apps import AppConfig class AccountsConfig(AppConfig): name = 'impersonate' def ready(self): from . import signals django-impersonate-1.4.1/impersonate/decorators.py0000644000175000017500000000227613206142417021771 0ustar pjspjs00000000000000# -*- coding: utf-8 -*- import django from django.conf import settings from django.utils.http import urlquote 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, is_authenticated 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 is_authenticated(request.user): return redirect(u'{0}?{1}={2}'.format( get_login_url(), REDIRECT_FIELD_NAME, urlquote(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 django-impersonate-1.4.1/impersonate/helpers.py0000644000175000017500000001213413212262601021253 0ustar pjspjs00000000000000# -*- coding: utf-8 -*- import re from importlib import import_module from django.utils.safestring import mark_safe from django.core.paginator import Paginator, EmptyPage 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 User._meta.ordering: 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 is_authenticated(user): ''' Helper to check if a user is authenticated or not. Added because in Django 2.0, the method compatibility is being removed. https://docs.djangoproject.com/en/1.11/ref/contrib/auth/#django.contrib.auth.models.User.is_authenticated ''' if not hasattr(user, 'is_authenticated'): return False if callable(user.is_authenticated): return user.is_authenticated() else: return user.is_authenticated try: from django.utils.duration import duration_string except ImportError: # Django < 1.8 def duration_string(duration): ''' Taken straight from Django 1.8 - django/utils/duration.py ''' days = duration.days seconds = duration.seconds microseconds = duration.microseconds minutes = seconds // 60 seconds = seconds % 60 hours = minutes // 60 minutes = minutes % 60 string = '{:02d}:{:02d}:{:02d}'.format(hours, minutes, seconds) if days: string = '{} '.format(days) + string if microseconds: string += '.{:06d}'.format(microseconds) return string django-impersonate-1.4.1/impersonate/middleware.py0000644000175000017500000000222713206137666021747 0ustar pjspjs00000000000000# -*- coding: utf-8 -*- from .helpers import ( User, check_allow_for_user, check_allow_for_uri, is_authenticated, ) try: from django.utils.deprecation import MiddlewareMixin except ImportError: MiddlewareMixin = object # fallback for Django < 1.10 class ImpersonateMiddleware(MiddlewareMixin): def process_request(self, request): request.user.is_impersonate = False request.impersonator = None if is_authenticated(request.user) and \ '_impersonate' in request.session: 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_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.real_user = request.impersonator or request.user django-impersonate-1.4.1/impersonate/migrations/0000775000175000017500000000000013464407070021426 5ustar pjspjs00000000000000django-impersonate-1.4.1/impersonate/migrations/0001_initial.py0000644000175000017500000000247113065053360024067 0ustar pjspjs00000000000000# -*- 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.')), ], ), ] django-impersonate-1.4.1/impersonate/migrations/__init__.py0000644000175000017500000000000012621020427023512 0ustar pjspjs00000000000000django-impersonate-1.4.1/impersonate/models.py0000644000175000017500000000324413065053360021104 0ustar pjspjs00000000000000# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models from django.conf import settings 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): from .helpers import duration_string 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' django-impersonate-1.4.1/impersonate/settings.py0000644000175000017500000000305713212345421021457 0ustar pjspjs00000000000000# -*- coding: utf-8 -*- from __future__ import unicode_literals import warnings from django.contrib.auth import get_user_model from django.conf import settings as django_settings 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'/'), } def deprecate_settings(name): # Silly reset of specific fields, needed for tests _settings['REDIRECT_URL'] = \ getattr(django_settings, 'LOGIN_REDIRECT_URL', u'/') old_settings_name = 'IMPERSONATE_{0}'.format(name) if hasattr(django_settings, old_settings_name): warnings.warn( ('The IMPERSONATE_* settings are now deprecated and will be ' 'removed in an upcoming release. Please use the IMPERSONATE ' 'dictionary setting.') ) return getattr(django_settings, old_settings_name) return _settings.get(name) class Settings(object): def __getattribute__(self, name): sdict = getattr(django_settings, 'IMPERSONATE', {}) return sdict.get(name, deprecate_settings(name)) settings = Settings() django-impersonate-1.4.1/impersonate/signals.py0000644000175000017500000000630213212024473021254 0ustar pjspjs00000000000000# -*- 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 session_begin = Signal( providing_args=['impersonator', 'impersonating', 'request'] ) # signal sent when an impersonation session ends session_end = Signal( providing_args=['impersonator', 'impersonating', 'request'] ) def gen_unique_id(): return hashlib.sha1( u'{0}:{1}'.format(get_random_string(), 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.warning( (u'Unfinished ImpersonationLog could not be found for: ' u'{0}, {1}, {2}').format( impersonator, impersonating, session_key, ) ) except ImpersonationLog.MultipleObjectsReturned: logger.warning( (u'Multiple unfinished ImpersonationLog matching: ' u'{0}, {1}, {2}').format( impersonator, impersonating, session_key, ) ) del request.session['_impersonate_session_id'] request.session.modified = True django-impersonate-1.4.1/impersonate/templates/0000775000175000017500000000000013464407070021250 5ustar pjspjs00000000000000django-impersonate-1.4.1/impersonate/templates/impersonate/0000775000175000017500000000000013464407070023576 5ustar pjspjs00000000000000django-impersonate-1.4.1/impersonate/templates/impersonate/list_users.html0000644000175000017500000000115312660134562026656 0ustar pjspjs00000000000000 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 %} django-impersonate-1.4.1/impersonate/templates/impersonate/search_users.html0000644000175000017500000000171312660134562027152 0ustar pjspjs00000000000000 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 %} django-impersonate-1.4.1/impersonate/tests.py0000664000175000017500000007145613416542460021003 0ustar pjspjs00000000000000# -*- 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 ''' import datetime from collections import namedtuple from distutils.version import LooseVersion from unittest.mock import patch, PropertyMock import django from django.test import TestCase from django.http import HttpResponse from django.utils import six, timezone from django.conf.urls import url, include from django.contrib.auth import get_user_model from django.test.utils import override_settings from django.contrib.admin.sites import AdminSite from django.test.client import Client, RequestFactory from .models import ImpersonationLog from .signals import session_begin, session_end from .helpers import duration_string, users_impersonable, is_authenticated from .admin import ( SessionStateFilter, ImpersonatorFilter, ImpersonationLogAdmin, ) try: from django.urls import reverse except ImportError: from django.core.urlresolvers import reverse try: # Python 3 from urllib.parse import urlencode, urlsplit except ImportError: import factory from urllib import urlencode from urlparse import urlsplit User = get_user_model() django_version_loose = LooseVersion(django.get_version()) def test_view(request): return HttpResponse('OK {0}'.format(request.user)) urlpatterns = [ url(r'^test-view/$', test_view, name='impersonate-test'), url(r'^another-view/$', test_view, name='another-test-view'), url('^', 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 is_authenticated(request.user) 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() if six.PY3: # Temporary until factory_boy gets Py3k support 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 else: class UserFactory(factory.Factory): FACTORY_FOR = User email = factory.LazyAttribute( lambda a: '{0}@test-email.com'.format(a.username).lower() ) @classmethod def _prepare(cls, create, **kwargs): password = kwargs.pop('password', None) user = super(UserFactory, cls)._prepare(create, **kwargs) if password: user.set_password(password) if create: 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() self.middleware = ImpersonateMiddleware() def _impersonated_request(self, use_id=True): request = self.factory.get('/') request.user = self.superuser request.session = { '_impersonate': self.user.pk if use_id else self.user, } 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.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) 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): response = self._impersonate_helper('user1', 'foobar', 2) self.assertEqual(self.client.session.get('_impersonate'), None) self.client.logout() # Try again with normal staff user response = self._impersonate_helper('user3', 'foobar', 2) self.assertEqual(self.client.session.get('_impersonate'), None) self.client.logout() def test_successful_impersonation(self): response = self._impersonate_helper('user1', '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() 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 response = 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 response = 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): response = 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): response = 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): response = 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): response = self._impersonate_helper('user1', 'foobar', 2) self.assertEqual(self.client.session.get('_impersonate'), None) self.client.logout() def test_unsuccessful_impersonation(self): response = 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(LOGIN_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/') @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(LOGIN_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), response._headers['location'][1] ) 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, response._headers['location'][1] ) else: self.assertEqual( 'http://testserver{0}'.format(use_url_path), response._headers['location'][1] ) 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()) response = 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()) response = 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()) response = 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) _filter = SessionStateFilter( None, {'session': 'complete'}, ImpersonationLog, ImpersonationLogAdmin, ) qs = _filter.queryset(None, ImpersonationLog.objects.all()) self.assertEqual(qs.count(), 1) _filter = SessionStateFilter( None, {'session': '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), 0) django-impersonate-1.4.1/impersonate/urls.py0000644000175000017500000000104312771071166020610 0ustar pjspjs00000000000000# -*- coding: utf-8 -*- from django.conf.urls import url from . import views urlpatterns = [ url(r'^stop/$', views.stop_impersonate, name='impersonate-stop'), url(r'^list/$', views.list_users, {'template': 'impersonate/list_users.html'}, name='impersonate-list'), url(r'^search/$', views.search_users, {'template': 'impersonate/search_users.html'}, name='impersonate-search'), url(r'^(?P.+)/$', views.impersonate, name='impersonate-start'), ] django-impersonate-1.4.1/impersonate/views.py0000644000175000017500000001147613212262566020770 0ustar pjspjs00000000000000# -*- coding: utf-8 -*- import logging from django.db.models import Q from django.shortcuts import get_object_or_404, redirect, render from .settings import User, settings from .decorators import allowed_user_required from .signals import session_begin, session_end from .helpers import ( get_redir_path, get_redir_arg, get_paginator, get_redir_field, check_allow_for_user, users_impersonable ) 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. ''' new_user = get_object_or_404(User, pk=uid) if check_allow_for_user(request, new_user): request.session['_impersonate'] = new_user.pk 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 original_path = request.session.pop('_impersonate_prev_path', None) use_refer = settings.USE_HTTP_REFERER if impersonating is not None: request.session.modified = True session_end.send( sender=None, impersonator=request.impersonator, 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), }) django-impersonate-1.4.1/setup.py0000644000175000017500000000361013212356744016436 0ustar pjspjs00000000000000import 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='petersanchez@gmail.com', license='BSD License', url='http://bitbucket.org/petersanchez/django-impersonate/', long_description=long_description, platforms=['any'], classifiers=[ 'Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Natural Language :: English', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', 'Environment :: Web Environment', ], )