Debian Codegraph @

README.rst

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