Debian Codegraph @

PKG-INFO

raw
1 Metadata-Version: 2.1
2 Name: django-impersonate
3 Version: 1.9.2
4 Summary: Django app to allow superusers to impersonate other users.
5 Home-page: https://code.netlandish.com/~petersanchez/django-impersonate
6 Author: Peter Sanchez
7 Author-email: [email protected]
8 License: BSD License
9 Platform: any
10 Classifier: Development Status :: 5 - Production/Stable
11 Classifier: Intended Audience :: Developers
12 Classifier: License :: OSI Approved :: BSD License
13 Classifier: Natural Language :: English
14 Classifier: Operating System :: OS Independent
15 Classifier: Framework :: Django
16 Classifier: Framework :: Django :: 3.2
17 Classifier: Framework :: Django :: 4.0
18 Classifier: Framework :: Django :: 4.1
19 Classifier: Framework :: Django :: 4.2
20 Classifier: Framework :: Django :: 5.0
21 Classifier: Programming Language :: Python
22 Classifier: Programming Language :: Python :: 3.7
23 Classifier: Programming Language :: Python :: 3.8
24 Classifier: Programming Language :: Python :: 3.9
25 Classifier: Programming Language :: Python :: 3.10
26 Classifier: Programming Language :: Python :: 3.11
27 Classifier: Programming Language :: Python :: 3.12
28 Classifier: Environment :: Web Environment
29 License-File: LICENSE
30 License-File: AUTHORS
31
32 django-impersonate |nlshield|
33 -----------------------------
34
35 Simple application to allow superusers to "impersonate" other
36 non-superuser accounts.
37
38 **Version:** 1.9.2
39
40 **Project Links:**
41 `Issues <https://todo.code.netlandish.com/~petersanchez/django-impersonate>`__
42 - `Mailing
43 List <https://lists.code.netlandish.com/~petersanchez/public-inbox>`__ -
44 `Contributing <#contributing>`__
45
46 **Author:** Peter Sanchez (https://petersanchez.com)
47
48 Python / Django Support
49 =======================
50
51 - Python 3.7+ for Django versions 3.2+
52
53 **Note:** As of version 1.4 we are only officially supporting Python and
54 Django versions that are supported by the official projects. So if a
55 Python or Django version is End-of-Life'd, then we will no longer
56 support that version either.
57
58 Dependencies
59 ============
60
61 - Depends on your project using the django.contrib.session framework.
62
63 **NOTE:**
64
65 - **Version 1.6** has officially removed support for the old settings
66 format. Please see the `settings <#settings>`__ section for how
67 settings should be configured.
68 - **Version 1.5 is now only officially supporting Django's 1.11, 2.2,
69 and 3.0**
70 - **Version 1.4 is now officially supporting Python 3.6+ and Django
71 1.11+**
72 - **Version 1.3 adds a settings format change.** Please see the
73 Settings section for details.
74 - **Version 1.0 adds new functionality by default.** Please see the
75 ``DISABLE_LOGGING`` settings option.
76 - If you need to use this with Django older than 1.8, please use
77 version django-impersonate == 1.0.1
78 - If you need to use this with Django older than 1.7, please use
79 version django-impersonate == 0.9.2
80 - **Version 0.9.2 partially reverts work completed in version 0.9.1.**
81 This is because work done to address a request in `Issue
82 #17 <https://bitbucket.org/petersanchez/django-impersonate/issues/17/remember-where-to-return-to-after>`__
83 broke default behavior for all previous versions. `Issue
84 #24 <https://bitbucket.org/petersanchez/django-impersonate/issues/24/impersonate_redirect_url-no-longer-works>`__
85 was opened and the fix was released in 0.9.2 to address it. Please
86 see the new ``USE_HTTP_REFERER`` settings option.
87 - If you need to use this with Django older than 1.4, please use
88 version django-impersonate == 0.5.3
89
90 Installation
91 ============
92
93 PIP:
94
95 ::
96
97 pip install django-impersonate
98
99 Basic Manual Install:
100
101 ::
102
103 $ python setup.py build
104 $ sudo python setup.py install
105
106 Alternative Install (Manually):
107
108 Place impersonate directory in your Python path. Either in your Python
109 installs site-packages directory or set your $PYTHONPATH environment
110 variable to include a directory where the impersonate directory lives.
111
112 Use
113 ===
114
115 #. Add ``impersonate`` to your INSTALLED_APPS
116
117 #. Add ``impersonate.middleware.ImpersonateMiddleware`` to your
118 ``MIDDLEWARE`` setting.
119
120 #. Add ``impersonate.urls`` somewhere in your url structure. Example:
121
122 ::
123
124 urlpatterns = patterns('',
125 url(r'^admin/', include(admin.site.urls)),
126 url(r'^impersonate/', include('impersonate.urls')),
127 ... (all your other urls here) ...
128 )
129
130 **Note:** The ``ImpersonationMiddleware`` class should be placed AFTER
131 the ``django.contrib.auth.*`` middleware classes
132
133 Functionality
134 =============
135
136 **You can now impersonate another user by hitting the following path:**
137
138 ::
139
140 /impersonate/<user-id>/
141
142 Replace <user-id> with the user id of the user you want to impersonate.
143
144 While in impersonation "mode" the ``request.user`` object will have an
145 ``is_impersonate`` attribute set to ``True`` as well as ``impersonator``
146 (and also ``request.impersonator``) set to the original user. So if you
147 wanted to check in your templates or view, you just do something
148 like...:
149
150 ::
151
152 {% if user.is_impersonate %} .... {% endif %}
153
154 The original user is available as ``user.impersonator`` or
155 ``request.impersonator``:
156
157 ::
158
159 {{ request.user }} ({{ request.impersonator }})
160
161 The real user is available as ``request.real_user`` - this is equivalent
162 to calling ``getattr(request, 'impersonator', request.user)``:
163
164 ::
165
166 assert request.real_user == getattr(request, 'impersonator', request.user)
167
168 You can reference this URL with ``reverse`` or the ``{% url %}``
169 template tag as ``impersonate-start`` and expects the argument of the
170 user ID. Example:
171
172 ::
173
174 reverse('impersonate-start', args=[user.id])
175 reverse('impersonate-start', uid=user.id)
176
177 **To remove the impersonation, hit the following path:**
178
179 ::
180
181 /impersonate/stop/
182
183 You can reference this URL with ``reverse`` or the ``{% url %}``
184 template tag as ``impersonate-stop``. When you call this URL, you will
185 be redirected to the page that you used to start impersonating a user
186 (eg, some search results or the user list).
187
188 **To list all users you can go to:**
189
190 ::
191
192 /impersonate/list/
193
194 This will render the template ``impersonate/list_users.html`` and will
195 pass the following in the context:
196
197 - ``users`` - queryset of all users
198 - ``paginator`` - Django Paginator instance
199 - ``page`` - Current page of objects (from Paginator)
200 - ``page_number`` - Current page number, defaults to 1
201
202 You can reference this URL with ``reverse`` or the ``{% url %}``
203 template tag as ``impersonate-list``.
204
205 **To search all users you can go to:**
206
207 ::
208
209 /impersonate/search/
210
211 This will render the template 'impersonate/search_users.html' and will
212 pass the following in the context:
213
214 - ``users`` - queryset of all users
215 - ``paginator`` - Django Paginator instance
216 - ``page`` - Current page of objects (from Paginator)
217 - ``page_number`` - Current page number, defaults to 1
218 - ``query`` - The search query that was entered
219
220 The view will expect a GET request and look for the ``q`` variable being
221 passed. If present, it will search the user entries with the value of
222 ``q``. The default fields searched are:
223
224 ``User.username``, ``User.first_name``, ``User.last_name``,
225 ``User.email``
226
227 You can reference this URL with ``reverse`` or the ``{% url %}``
228 template tag as ``impersonate-search``.
229
230 **To allow some users to impersonate other users**
231
232 You can optionally allow only some non-superuser and non-staff users to
233 impersonate by adding a ``CUSTOM_ALLOW`` setting option. Create a
234 function that takes a request object, and based on your rules, returns
235 ``True`` if the user is allowed to impersonate or not.
236
237 **To limit what users a user can impersonate**
238
239 By, optionally, setting the ``CUSTOM_USER_QUERYSET`` option you can
240 control what users can be impersonated. It takes a request object of the
241 user, and returns a QuerySet of users. This is used when searching for
242 users to impersonate, when listing what users to impersonate, and when
243 trying to start impersonation.
244
245 Signals
246 =======
247
248 If you wish to hook into the impersonation session (for instance, in
249 order to audit access), there are two signals that are fired by
250 django-impersonate, at the beginning and end of a session:
251
252 - ``session_begin`` - sent when calling the ``impersonate`` view
253 - ``session_end`` - sent when calling the ``stop_impersonate`` view
254
255 Both of these signals send the same arguments:
256
257 - ``sender`` - this is a Django signal requirement, and is always set
258 to None
259 - ``impersonator`` - a reference to the User object of the person doing
260 the impersonation
261 - ``impersonating`` - a reference to the User object of the person
262 being impersonated
263 - ``request`` - the Django HttpRequest object from which the
264 impersonation was invoked
265
266 The request object is included as it contains pertinent information that
267 you may wish to audit - such as client IP address, user-agent string,
268 etc.
269
270 For an example of how to hook up the signals, see the relevant test -
271 ``test_successful_impersonation_signals``.
272
273 The ``session_end`` signal will only be fired if the impersonator
274 explicitly ends the session.
275
276 Settings
277 ========
278
279 The following settings are available for django-impersonate. All
280 settings should be set as variables in a dictionary assigned to the
281 attribute named ``IMPERSONATE``.
282
283 For example:
284
285 ::
286
287 IMPERSONATE = {
288 'REDIRECT_URL': '/some-path/',
289 'PAGINATE_COUNT': 10,
290 }
291
292 Here are the options available...
293
294 ::
295
296 REDIRECT_URL
297
298 This is the URL you want to be redirected to *after* you have chosen to
299 impersonate another user. If this is not present it will check for the
300 ``LOGIN_REDIRECT_URL`` setting and fall back to '/' if neither is
301 present. Value should be a string containing the redirect path.
302
303 ::
304
305 READ_ONLY
306
307 A boolean that if set to ``True`` any requests that are not either
308 ``GET`` or ``HEAD`` or ``OPTIONS`` will result in a "Bad Request"
309 response (status code 405). Use this if you want to limit your
310 impersonating users to read only impersonation sessions.
311
312 Value should be a boolean, defaults to ``False``
313
314 If the ``CUSTOM_READ_ONLY`` is set, then that custom function is used,
315 and this setting is ignored.
316
317 ::
318
319 CUSTOM_READ_ONLY
320
321 A string that represents a function (e.g.
322 ``module.submodule.mod.function_name``) that allows more fine grained
323 control over who has read only access. It takes one argument, the
324 request object, and should return True to restrict the user to only
325 allow ``GET``, ``HEAD`` and ``OPTIONS`` requests.
326
327 It is optional, and if it is not present, ``READ_ONLY`` setting value
328 applies.
329
330 ::
331
332 USE_HTTP_REFERER
333
334 If this is set to ``True``, then the app will attempt to be redirect you
335 to the URL you were at when the impersonation began once you have
336 *stopped* the impersonation. For example, if you were at the url
337 '/foo/bar/' when you began impersonating a user, once you end the
338 impersonation, you will be redirected back to '/foo/bar/' instead of the
339 value in ``REDIRECT_URL``.
340
341 Value should be a boolean, defaults to ``False``
342
343 ::
344
345 PAGINATE_COUNT
346
347 This is the number of users to paginate by when using the list or search
348 views. This defaults to 20. Value should be an integer.
349
350 ::
351
352 REQUIRE_SUPERUSER
353
354 If this is set to ``True``, then only users who have ``is_superuser``
355 set to ``True`` will be allowed to impersonate other users. Default is
356 ``False``. If ``False``, then any ``is_staff`` user will be able to
357 impersonate other users.
358
359 **Note:** Regardless of this setting, a ``is_staff`` user will **not**
360 be allowed to impersonate a ``is_superuser`` user.
361
362 Value should be a boolean
363
364 If the ``CUSTOM_ALLOW`` is set, then that custom function is used, and
365 this setting is ignored.
366
367 ::
368
369 ALLOW_SUPERUSER
370
371 By default, superusers cannot be impersonated; this setting allows for
372 that.
373
374 **Note:** Even when this is true, only superusers can impersonate other
375 superusers, regardless of the value of REQUIRE_SUPERUSER.
376
377 Value should be a boolean and the default is ``False``.
378
379 ::
380
381 URI_EXCLUSIONS
382
383 Set to a list/tuple of url patterns that, if matched, user impersonation
384 is not completed. It defaults to:
385
386 ::
387
388 (r'^admin/',)
389
390 If you do not want to use even the default exclusions then set the
391 setting to an empty list/tuple.
392
393 ::
394
395 CUSTOM_USER_QUERYSET
396
397 A string that represents a function (e.g.
398 ``module.submodule.mod.function_name``) that allows more fine grained
399 control over what users a user can impersonate. It takes one argument,
400 the request object, and should return a QuerySet. Only the users in this
401 queryset can be impersonated.
402
403 This function will not be called when the request has an unauthorised
404 users, and will only be called when the user is allowed to impersonate
405 (cf. ``REQUIRE_SUPERUSER`` and ``CUSTOM_ALLOW``).
406
407 Regardless of what this function returns, a user cannot impersonate a
408 superuser, even if there are superusers in the returned QuerySet.
409
410 It is optional, and if it is not present, the user can impersonate any
411 user (i.e. the default is ``User.objects.all()``).
412
413 ::
414
415 CUSTOM_ALLOW
416
417 A string that represents a function (e.g.
418 ``module.submodule.mod.function_name``) that allows more fine grained
419 control over who can use the impersonation. It takes one argument, the
420 request object, and should return True to allow impersonation.
421 Regardless of this setting, the user must be logged in to impersonate.
422 If this setting is used, ``REQUIRE_SUPERUSER`` is ignored.
423
424 It is optional, and if it is not present, the previous rules about
425 superuser and ``REQUIRE_SUPERUSER`` apply.
426
427 ::
428
429 REDIRECT_FIELD_NAME
430
431 A string that represents the name of a request (GET) parameter which
432 contains the URL to redirect to after impersonating a user. This can be
433 used to redirect to a custom page after impersonating a user. Example:
434
435 ::
436
437 # in settings.py
438 IMPERSONATE = {'REDIRECT_FIELD_NAME': 'next'}
439
440 # in your template
441 <a href="{% url 'impersonate-list' %}?next=/some/url/">switch user</a>
442
443 To return always to the current page after impersonating a user, use
444 request.path:
445
446 ::
447
448 `<a href="{% url 'impersonate-list' %}?next={{request.path}}">switch user</a>`
449
450 Each use case is different so obviously set the next value to whatever
451 your case requires.
452
453 ::
454
455 SEARCH_FIELDS
456
457 Array of user model fields used for building searching query. Default
458 value is [``User.USERNAME_FIELD``, ``first_name``, ``last_name``,
459 ``email``]. If the User model doesn't have the ``USERNAME_FIELD``
460 attribute, it falls back to 'username' (< Django 1.5).
461
462 ::
463
464 LOOKUP_TYPE
465
466 A string that represents SQL lookup type for searching users by query on
467 fields above. It is ``icontains`` by default.
468
469 ::
470
471 DISABLE_LOGGING
472
473 A boolean that can be used to disable the logging of impersonation
474 sessions. By default each impersonation ``session_begin`` signal will
475 create a new ``ImpersonationLog`` object, which is closed out (duration
476 calculated) at the corresponding ``session_end`` signal.
477
478 It is optional, and defaults to False (i.e. logging is enabled).
479
480 ::
481
482 MAX_FILTER_SIZE
483
484 The max number of items acceptable in the admin list filters. If the
485 number of items exceeds this, then the filter list is the size of the
486 settings value. This is used by the "Filter by impersonator" filter.
487
488 It is optional, and defaults to 100.
489
490 ::
491
492 ADMIN_DELETE_PERMISSION
493
494 A boolean to enable/disable deletion of impersonation logs in the Django
495 admin.
496
497 Default is ``False``
498
499 ::
500
501 ADMIN_ADD_PERMISSION
502
503 A boolean to enable/disable ability to add impersonation logs in the
504 Django admin.
505
506 Default is ``False``
507
508 ::
509
510 ADMIN_READ_ONLY
511
512 A boolean to enable/disable "read only" mode of impersonation logs in
513 the Django admin. Generally you want to leave this enabled otherwise
514 admin users can alter logs within the Django admin area.
515
516 Default is ``True``
517
518 ::
519
520 MAX_DURATION
521
522 A number specifying the maximum allowed duration of impersonation
523 sessions in **seconds**.
524
525 Default is ``None``
526
527 Admin
528 =====
529
530 As of version 1.3 django-impersonate now includes a helper admin mixin,
531 located at ``impersonate.admin.UserAdminImpersonateMixin``, to include
532 in your User model's ModelAdmin. This provides a direct link to
533 impersonate users from your user model's Django admin list view. Using
534 it is very simple, however if you're using the default
535 ``django.contrib.auth.models.User`` model you will need to unregister
536 the old ModelAdmin before registering your own.
537
538 The ``UserAdminImpersonateMixin`` has a attribute named
539 ``open_new_window`` that **defaults to ``False``**. If this is set to
540 True a new window will be opened to start the new impersonation session
541 when clicking the impersonate link directly in the admin.
542
543 Here's an example:
544
545 ::
546
547 # yourapp/admin.py
548 from django.contrib import admin
549 from django.contrib.auth.models import User
550 from django.contrib.auth.admin import UserAdmin
551 from impersonate.admin import UserAdminImpersonateMixin
552
553
554 class NewUserAdmin(UserAdminImpersonateMixin, UserAdmin):
555 open_new_window = True
556 pass
557
558 admin.site.unregister(User)
559 admin.site.register(User, NewUserAdmin)
560
561 Testing
562 =======
563
564 From the repo checkout, ensure you have Django in your ``PYTHONPATH``
565 and run:
566
567 ::
568
569 $ python runtests.py
570
571 To get test coverage, use:
572
573 ::
574
575 $ coverage run --branch runtests.py
576 $ coverage html <- Pretty HTML files for you
577 $ coverage report -m <- Ascii report
578
579 If you're bored and want to test all the supported environments, you'll
580 need tox.:
581
582 ::
583
584 $ pip install tox
585 $ tox
586
587 And you should see:
588
589 ::
590
591 py37-django2.2: commands succeeded
592 py37-django3.2: commands succeeded
593 py38-django2.2: commands succeeded
594 py38-django3.2: commands succeeded
595 py39-django2.2: commands succeeded
596 py39-django3.2: commands succeeded
597 py38-django4.0: commands succeeded
598 py39-django4.0: commands succeeded
599 py310-django3.2: commands succeeded
600 py310-django4.0: commands succeeded
601 congratulations :)
602
603 Contributing
604 ============
605
606 We accept patches submitted via ``hg email`` which is the ``patchbomb``
607 extension included with Mercurial.
608
609 The mailing list where you submit your patches is
610 ``~petersanchez/[email protected]``. You can also
611 view the archives on the web here:
612
613 https://lists.code.netlandish.com/~petersanchez/public-inbox
614
615 To quickly setup your clone of ``django-impersonate`` to submit to the
616 mailing list just edit your ``.hg/hgrc`` file and add the following:
617
618 ::
619
620 [email]
621 to = ~petersanchez/[email protected]
622
623 [patchbomb]
624 flagtemplate = {separate(' ', 'django-impersonate', flags)}
625
626 [diff]
627 git = 1
628
629 We have more information on the topic here:
630
631 - `Contributing <https://man.code.netlandish.com/contributing.md>`__
632 - `Using email with
633 Mercurial <https://man.code.netlandish.com/hg/email.md>`__
634 - `Mailing list
635 etiquette <https://man.code.netlandish.com/lists/etiquette.md>`__
636
637 Copyright & Warranty
638 ====================
639
640 All documentation, libraries, and sample code are Copyright 2011 Peter
641 Sanchez <[email protected]>. The library and sample code are made
642 available to you under the terms of the BSD license which is contained
643 in the included file, BSD-LICENSE.
644
645 Commercial Support
646 ------------------
647
648 This software, and lots of other software like it, has been built in
649 support of many of Netlandish's own projects, and the projects of our
650 clients. We would love to help you on your next project so get in touch
651 by dropping us a note at [email protected].
652
653 .. |nlshield| image:: https://img.shields.io/badge/100%25-Netlandish-blue.svg?style=square-flat
654 :target: http://www.netlandish.com