Django

Code

root/django/branches/boulder-oracle-sprint/docs/authentication.txt

Revision 5491, 36.9 kB (checked in by bouldersprinters, 1 year ago)

boulder-oracle-sprint: Merged to [5490]

Line 
1 =============================
2 User authentication in Django
3 =============================
4
5 Django comes with a user authentication system. It handles user accounts,
6 groups, permissions and cookie-based user sessions. This document explains how
7 things work.
8
9 Overview
10 ========
11
12 The auth system consists of:
13
14     * Users
15     * Permissions: Binary (yes/no) flags designating whether a user may perform
16       a certain task.
17     * Groups: A generic way of applying labels and permissions to more than one
18       user.
19     * Messages: A simple way to queue messages for given users.
20
21 Installation
22 ============
23
24 Authentication support is bundled as a Django application in
25 ``django.contrib.auth``. To install it, do the following:
26
27     1. Put ``'django.contrib.auth'`` in your ``INSTALLED_APPS`` setting.
28     2. Run the command ``manage.py syncdb``.
29
30 Note that the default ``settings.py`` file created by
31 ``django-admin.py startproject`` includes ``'django.contrib.auth'`` in
32 ``INSTALLED_APPS`` for convenience. If your ``INSTALLED_APPS`` already contains
33 ``'django.contrib.auth'``, feel free to run ``manage.py syncdb`` again; you
34 can run that command as many times as you'd like, and each time it'll only
35 install what's needed.
36
37 The ``syncdb`` command creates the necessary database tables, creates
38 permission objects for all installed apps that need 'em, and prompts you to
39 create a superuser account the first time you run it.
40
41 Once you've taken those steps, that's it.
42
43 Users
44 =====
45
46 Users are represented by a standard Django model, which lives in
47 `django/contrib/auth/models.py`_.
48
49 .. _django/contrib/auth/models.py: http://code.djangoproject.com/browser/django/trunk/django/contrib/auth/models.py
50
51 API reference
52 -------------
53
54 Fields
55 ~~~~~~
56
57 ``User`` objects have the following fields:
58
59     * ``username`` -- Required. 30 characters or fewer. Alphanumeric characters
60       only (letters, digits and underscores).
61     * ``first_name`` -- Optional. 30 characters or fewer.
62     * ``last_name`` -- Optional. 30 characters or fewer.
63     * ``email`` -- Optional. E-mail address.
64     * ``password`` -- Required. A hash of, and metadata about, the password.
65       (Django doesn't store the raw password.) Raw passwords can be arbitrarily
66       long and can contain any character. See the "Passwords" section below.
67     * ``is_staff`` -- Boolean. Designates whether this user can access the
68       admin site.
69     * ``is_active`` -- Boolean. Designates whether this account can be used
70       to log in. Set this flag to ``False`` instead of deleting accounts.
71     * ``is_superuser`` -- Boolean. Designates that this user has all permissions
72       without explicitly assigning them.
73     * ``last_login`` -- A datetime of the user's last login. Is set to the
74       current date/time by default.
75     * ``date_joined`` -- A datetime designating when the account was created.
76       Is set to the current date/time by default when the account is created.
77
78 Methods
79 ~~~~~~~
80
81 ``User`` objects have two many-to-many fields: ``groups`` and
82 ``user_permissions``. ``User`` objects can access their related
83 objects in the same way as any other `Django model`_::
84
85     myuser.groups = [group_list]
86     myuser.groups.add(group, group,...)
87     myuser.groups.remove(group, group,...)
88     myuser.groups.clear()
89     myuser.user_permissions = [permission_list]
90     myuser.user_permissions.add(permission, permission, ...)
91     myuser.user_permissions.remove(permission, permission, ...]
92     myuser.user_permissions.clear()
93
94 In addition to those automatic API methods, ``User`` objects have the following
95 custom methods:
96
97     * ``is_anonymous()`` -- Always returns ``False``. This is a way of
98       differentiating ``User`` and ``AnonymousUser`` objects. Generally, you
99       should prefer using ``is_authenticated()`` to this method.
100
101     * ``is_authenticated()`` -- Always returns ``True``. This is a way to
102       tell if the user has been authenticated. This does not imply any
103       permissions, and doesn't check if the user is active - it only indicates
104       that the user has provided a valid username and password.
105
106     * ``get_full_name()`` -- Returns the ``first_name`` plus the ``last_name``,
107       with a space in between.
108
109     * ``set_password(raw_password)`` -- Sets the user's password to the given
110       raw string, taking care of the password hashing. Doesn't save the
111       ``User`` object.
112
113     * ``check_password(raw_password)`` -- Returns ``True`` if the given raw
114       string is the correct password for the user. (This takes care of the
115       password hashing in making the comparison.)
116
117     * ``get_group_permissions()`` -- Returns a list of permission strings that
118       the user has, through his/her groups.
119
120     * ``get_all_permissions()`` -- Returns a list of permission strings that
121       the user has, both through group and user permissions.
122
123     * ``has_perm(perm)`` -- Returns ``True`` if the user has the specified
124       permission, where perm is in the format ``"package.codename"``.
125       If the user is inactive, this method will always return ``False``.
126
127     * ``has_perms(perm_list)`` -- Returns ``True`` if the user has each of the
128       specified permissions, where each perm is in the format
129       ``"package.codename"``. If the user is inactive, this method will
130       always return ``False``.
131
132     * ``has_module_perms(package_name)`` -- Returns ``True`` if the user has
133       any permissions in the given package (the Django app label).
134       If the user is inactive, this method will always return ``False``.
135
136     * ``get_and_delete_messages()`` -- Returns a list of ``Message`` objects in
137       the user's queue and deletes the messages from the queue.
138
139     * ``email_user(subject, message, from_email=None)`` -- Sends an e-mail to
140       the user. If ``from_email`` is ``None``, Django uses the
141       `DEFAULT_FROM_EMAIL`_ setting.
142
143     * ``get_profile()`` -- Returns a site-specific profile for this user.
144       Raises ``django.contrib.auth.models.SiteProfileNotAvailable`` if the current site
145       doesn't allow profiles.
146
147 .. _Django model: ../model-api/
148 .. _DEFAULT_FROM_EMAIL: ../settings/#default-from-email
149
150 Manager functions
151 ~~~~~~~~~~~~~~~~~
152
153 The ``User`` model has a custom manager that has the following helper functions:
154
155     * ``create_user(username, email, password)`` -- Creates, saves and returns
156       a ``User``. The ``username``, ``email`` and ``password`` are set as
157       given, and the ``User`` gets ``is_active=True``.
158
159       See _`Creating users` for example usage.
160
161     * ``make_random_password(length=10, allowed_chars='abcdefghjkmnpqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789')``
162       Returns a random password with the given length and given string of
163       allowed characters. (Note that the default value of ``allowed_chars``
164       doesn't contain letters that can cause user confusion, including
165       ``1``, ``I`` and ``0``).
166
167 Basic usage
168 -----------
169
170 Creating users
171 ~~~~~~~~~~~~~~
172
173 The most basic way to create users is to use the ``create_user`` helper
174 function that comes with Django::
175
176     >>> from django.contrib.auth.models import User
177     >>> user = User.objects.create_user('john', 'lennon@thebeatles.com', 'johnpassword')
178
179     # At this point, user is a User object ready to be saved
180     # to the database. You can continue to change its attributes
181     # if you want to change other fields.
182     >>> user.is_staff = True
183     >>> user.save()
184
185 Changing passwords
186 ~~~~~~~~~~~~~~~~~~
187
188 Change a password with ``set_password()``::
189
190     >>> from django.contrib.auth.models import User
191     >>> u = User.objects.get(username__exact='john')
192     >>> u.set_password('new password')
193     >>> u.save()
194
195 Don't set the ``password`` attribute directly unless you know what you're
196 doing. This is explained in the next section.
197
198 Passwords
199 ---------
200
201 The ``password`` attribute of a ``User`` object is a string in this format::
202
203     hashtype$salt$hash
204
205 That's hashtype, salt and hash, separated by the dollar-sign character.
206
207 Hashtype is either ``sha1`` (default), ``md5`` or ``crypt`` -- the algorithm
208 used to perform a one-way hash of the password. Salt is a random string used
209 to salt the raw password to create the hash. Note that the ``crypt`` method is
210 only supported on platforms that have the standard Python ``crypt`` module
211 available, and ``crypt`` support is only available in the Django development
212 version.
213
214 For example::
215
216     sha1$a1976$a36cc8cbf81742a8fb52e221aaeab48ed7f58ab4
217
218 The ``User.set_password()`` and ``User.check_password()`` functions handle
219 the setting and checking of these values behind the scenes.
220
221 Previous Django versions, such as 0.90, used simple MD5 hashes without password
222 salts. For backwards compatibility, those are still supported; they'll be
223 converted automatically to the new style the first time ``check_password()``
224 works correctly for a given user.
225
226 Anonymous users
227 ---------------
228
229 ``django.contrib.auth.models.AnonymousUser`` is a class that implements
230 the ``django.contrib.auth.models.User`` interface, with these differences:
231
232     * ``id`` is always ``None``.
233     * ``is_anonymous()`` returns ``True`` instead of ``False``.
234     * ``is_authenticated()`` returns ``False`` instead of ``True``.
235     * ``has_perm()`` always returns ``False``.
236     * ``set_password()``, ``check_password()``, ``save()``, ``delete()``,
237       ``set_groups()`` and ``set_permissions()`` raise ``NotImplementedError``.
238
239 In practice, you probably won't need to use ``AnonymousUser`` objects on your
240 own, but they're used by Web requests, as explained in the next section.
241
242 Creating superusers
243 -------------------
244
245 ``manage.py syncdb`` prompts you to create a superuser the first time you run
246 it after adding ``'django.contrib.auth'`` to your ``INSTALLED_APPS``. But if
247 you need to create a superuser after that via the command line, you can use the
248 ``create_superuser.py`` utility. Just run this command::
249
250     python /path/to/django/contrib/auth/create_superuser.py
251
252 Make sure to substitute ``/path/to/`` with the path to the Django codebase on
253 your filesystem.
254
255 Authentication in Web requests
256 ==============================
257
258 Until now, this document has dealt with the low-level APIs for manipulating
259 authentication-related objects. On a higher level, Django can hook this
260 authentication framework into its system of `request objects`_.
261
262 First, install the ``SessionMiddleware`` and ``AuthenticationMiddleware``
263 middlewares by adding them to your ``MIDDLEWARE_CLASSES`` setting. See the
264 `session documentation`_ for more information.
265
266 Once you have those middlewares installed, you'll be able to access
267 ``request.user`` in views. ``request.user`` will give you a ``User`` object
268 representing the currently logged-in user. If a user isn't currently logged in,
269 ``request.user`` will be set to an instance of ``AnonymousUser`` (see the
270 previous section). You can tell them apart with ``is_authenticated()``, like so::
271
272     if request.user.is_authenticated():
273         # Do something for authenticated users.
274     else:
275         # Do something for anonymous users.
276
277 .. _request objects: ../request_response/#httprequest-objects
278 .. _session documentation: ../sessions/
279
280 How to log a user in
281 --------------------
282
283 Django provides two functions in ``django.contrib.auth``: ``authenticate()``
284 and ``login()``.
285
286 To authenticate a given username and password, use ``authenticate()``. It
287 takes two keyword arguments, ``username`` and ``password``, and it returns
288 a ``User`` object if the password is valid for the given username. If the
289 password is invalid, ``authenticate()`` returns ``None``. Example::
290
291     from django.contrib.auth import authenticate
292     user = authenticate(username='john', password='secret')
293     if user is not None:
294         if user.is_active:
295             print "You provided a correct username and password!"
296         else:
297             print "Your account has been disabled!"
298     else:
299         print "Your username and password were incorrect."
300
301 To log a user in, in a view, use ``login()``. It takes an ``HttpRequest``
302 object and a ``User`` object. ``login()`` saves the user's ID in the session,
303 using Django's session framework, so, as mentioned above, you'll need to make
304 sure to have the session middleware installed.
305
306 This example shows how you might use both ``authenticate()`` and ``login()``::
307
308     from django.contrib.auth import authenticate, login
309
310     def my_view(request):
311         username = request.POST['username']
312         password = request.POST['password']
313         user = authenticate(username=username, password=password)
314         if user is not None:
315             if user.is_active:
316                 login(request, user)
317                 # Redirect to a success page.
318             else:
319                 # Return a 'disabled account' error message
320         else:
321             # Return an 'invalid login' error message.
322
323 Manually checking a user's password
324 -----------------------------------
325
326 If you'd like to manually authenticate a user by comparing a
327 plain-text password to the hashed password in the database, use the
328 convenience function `django.contrib.auth.models.check_password`. It
329 takes two arguments: the plain-text password to check, and the full
330 value of a user's ``password`` field in the database to check against,
331 and returns ``True`` if they match, ``False`` otherwise.
332
333 How to log a user out
334 ---------------------
335
336 To log out a user who has been logged in via ``django.contrib.auth.login()``,
337 use ``django.contrib.auth.logout()`` within your view. It takes an
338 ``HttpRequest`` object and has no return value. Example::
339
340     from django.contrib.auth import logout
341
342     def logout_view(request):
343         logout(request)
344         # Redirect to a success page.
345
346 Note that ``logout()`` doesn't throw any errors if the user wasn't logged in.
347
348 Limiting access to logged-in users
349 ----------------------------------
350
351 The raw way
352 ~~~~~~~~~~~
353
354 The simple, raw way to limit access to pages is to check
355 ``request.user.is_authenticated()`` and either redirect to a login page::
356
357     from django.http import HttpResponseRedirect
358
359     def my_view(request):
360         if not request.user.is_authenticated():
361             return HttpResponseRedirect('/login/?next=%s' % request.path)
362         # ...
363
364 ...or display an error message::
365
366     def my_view(request):
367         if not request.user.is_authenticated():
368             return render_to_response('myapp/login_error.html')
369         # ...
370
371 The login_required decorator
372 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
373
374 As a shortcut, you can use the convenient ``login_required`` decorator::
375
376     from django.contrib.auth.decorators import login_required
377
378     def my_view(request):
379         # ...
380     my_view = login_required(my_view)
381
382 Here's an equivalent example, using the more compact decorator syntax
383 introduced in Python 2.4::
384
385     from django.contrib.auth.decorators import login_required
386
387     @login_required
388     def my_view(request):
389         # ...
390
391 ``login_required`` does the following:
392
393     * If the user isn't logged in, redirect to ``settings.LOGIN_URL``
394       (``/accounts/login/`` by default), passing the current absolute URL
395       in the query string as ``next``. For example:
396       ``/accounts/login/?next=/polls/3/``.
397     * If the user is logged in, execute the view normally. The view code is
398       free to assume the user is logged in.
399
400 Note that you'll need to map the appropriate Django view to ``settings.LOGIN_URL``.
401 For example, using the defaults, add the following line to your URLconf::
402
403     (r'^accounts/login/$', 'django.contrib.auth.views.login'),
404
405 Here's what ``django.contrib.auth.views.login`` does:
406
407     * If called via ``GET``, it displays a login form that POSTs to the same
408       URL. More on this in a bit.
409
410     * If called via ``POST``, it tries to log the user in. If login is
411       successful, the view redirects to the URL specified in ``next``. If
412       ``next`` isn't provided, it redirects to ``settings.LOGIN_REDIRECT_URL``
413       (which defaults to ``/accounts/profile/``). If login isn't successful,
414       it redisplays the login form.
415
416 It's your responsibility to provide the login form in a template called
417 ``registration/login.html`` by default. This template gets passed three
418 template context variables:
419
420     * ``form``: A ``FormWrapper`` object representing the login form. See the
421       `forms documentation`_ for more on ``FormWrapper`` objects.
422     * ``next``: The URL to redirect to after successful login. This may contain
423       a query string, too.
424     * ``site_name``: The name of the current ``Site``, according to the
425       ``SITE_ID`` setting. See the `site framework docs`_.
426
427 If you'd prefer not to call the template ``registration/login.html``, you can
428 pass the ``template_name`` parameter via the extra arguments to the view in
429 your URLconf. For example, this URLconf line would use ``myapp/login.html``
430 instead::
431
432     (r'^accounts/login/$', 'django.contrib.auth.views.login', {'template_name': 'myapp/login.html'}),
433
434 Here's a sample ``registration/login.html`` template you can use as a starting
435 point. It assumes you have a ``base.html`` template that defines a ``content``
436 block::
437
438     {% extends "base.html" %}
439
440     {% block content %}
441
442     {% if form.has_errors %}
443     <p>Your username and password didn't match. Please try again.</p>
444     {% endif %}
445
446     <form method="post" action=".">
447     <table>
448     <tr><td><label for="id_username">Username:</label></td><td>{{ form.username }}</td></tr>
449     <tr><td><label for="id_password">Password:</label></td><td>{{ form.password }}</td></tr>
450     </table>
451
452     <input type="submit" value="login" />
453     <input type="hidden" name="next" value="{{ next }}" />
454     </form>
455
456     {% endblock %}
457
458 .. _forms documentation: ../forms/
459 .. _site framework docs: ../sites/
460
461 Other built-in views
462 --------------------
463
464 In addition to the `login` view, the authentication system includes a
465 few other useful built-in views:
466
467 ``django.contrib.auth.views.logout``
468 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
469
470 **Description:**
471
472 Logs a user out.
473
474 **Optional arguments:**
475
476     * ``template_name``: The full name of a template to display after
477       logging the user out. This will default to
478       ``registration/logged_out.html`` if no argument is supplied.
479
480 **Template context:**
481
482     * ``title``: The string "Logged out", localized.
483
484 ``django.contrib.auth.views.logout_then_login``
485 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
486
487 **Description:**
488
489 Logs a user out, then redirects to the login page.
490
491 **Optional arguments:**
492
493     * ``login_url``: The URL of the login page to redirect to. This
494       will default to ``settings.LOGIN_URL`` if not supplied.
495
496 ``django.contrib.auth.views.password_change``
497 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
498
499 **Description:**
500
501 Allows a user to change their password.
502
503 **Optional arguments:**
504
505     * ``template_name``: The full name of a template to use for
506       displaying the password change form. This will default to
507       ``registration/password_change_form.html`` if not supplied.
508
509 **Template context:**
510
511     * ``form``: The password change form.
512
513 ``django.contrib.auth.views.password_change_done``
514 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
515
516 **Description:**
517
518 The page shown after a user has changed their password.
519
520 **Optional arguments:**
521
522     * ``template_name``: The full name of a template to use. This will
523       default to ``registration/password_change_done.html`` if not
524       supplied.
525
526 ``django.contrib.auth.views.password_reset``
527 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
528
529 **Description:**
530
531 Allows a user to reset their password, and sends them the new password
532 in an email.
533
534 **Optional arguments:**
535
536     * ``template_name``: The full name of a template to use for
537       displaying the password reset form. This will default to
538       ``registration/password_reset_form.html`` if not supplied.
539
540     * ``email_template_name``: The full name of a template to use for
541       generating the email with the new password. This will default to
542       ``registration/password_reset_email.html`` if not supplied.
543
544 **Template context:**
545
546     * ``form``: The form for resetting the user's password.
547
548 ``django.contrib.auth.views.password_reset_done``
549 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
550
551 **Description:**
552
553 The page shown after a user has reset their password.
554
555 **Optional arguments:**
556
557     * ``template_name``: The full name of a template to use. This will
558       default to ``registration/password_reset_done.html`` if not
559       supplied.
560
561 ``django.contrib.auth.views.redirect_to_login``
562 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
563
564 **Description:**
565
566 Redirects to the login page, and then back to another URL after a
567 successful login.
568
569 **Required arguments:**
570
571     * ``next``: The URL to redirect to after a successful login.
572
573 **Optional arguments:**
574
575     * ``login_url``: The URL of the login page to redirect to. This
576       will default to ``settings.LOGIN_URL`` if not supplied.
577
578 Built-in manipulators
579 ---------------------
580
581 If you don't want to use the built-in views, but want the convenience
582 of not having to write manipulators for this functionality, the
583 authentication system provides several built-in manipulators:
584
585     * ``django.contrib.auth.forms.AdminPasswordChangeForm``: A
586       manipulator used in the admin interface to change a user's
587       password.
588
589     * ``django.contrib.auth.forms.AuthenticationForm``: A manipulator
590       for logging a user in.
591
592     * ``django.contrib.auth.forms.PasswordChangeForm``: A manipulator
593       for allowing a user to change their password.
594
595     * ``django.contrib.auth.forms.PasswordResetForm``: A manipulator
596       for resetting a user's password and emailing the new password to
597       them.
598
599     * ``django.contrib.auth.forms.UserCreationForm``: A manipulator
600       for creating a new user.
601
602 Limiting access to logged-in users that pass a test
603 ---------------------------------------------------
604
605 To limit access based on certain permissions or some other test, you'd do
606 essentially the same thing as described in the previous section.
607
608 The simple way is to run your test on ``request.user`` in the view directly.
609 For example, this view checks to make sure the user is logged in and has the
610 permission ``polls.can_vote``::
611
612     def my_view(request):
613         if not (request.user.is_authenticated() and request.user.has_perm('polls.can_vote')):
614             return HttpResponse("You can't vote in this poll.")
615         # ...
616
617 As a shortcut, you can use the convenient ``user_passes_test`` decorator::
618
619     from django.contrib.auth.decorators import user_passes_test
620
621     def my_view(request):
622         # ...
623     my_view = user_passes_test(lambda u: u.has_perm('polls.can_vote'))(my_view)
624
625 We're using this particular test as a relatively simple example. However, if
626 you just want to test whether a permission is available to a user, you can use
627 the ``permission_required()`` decorator, described later in this document.
628
629 Here's the same thing, using Python 2.4's decorator syntax::
630
631     from django.contrib.auth.decorators import user_passes_test
632
633     @user_passes_test(lambda u: u.has_perm('polls.can_vote'))
634     def my_view(request):
635         # ...
636
637 ``user_passes_test`` takes a required argument: a callable that takes a
638 ``User`` object and returns ``True`` if the user is allowed to view the page.
639 Note that ``user_passes_test`` does not automatically check that the ``User``
640 is not anonymous.
641
642 ``user_passes_test()`` takes an optional ``login_url`` argument, which lets you
643 specify the URL for your login page (``settings.LOGIN_URL`` by default).
644
645 Example in Python 2.3 syntax::
646
647     from django.contrib.auth.decorators import user_passes_test
648
649     def my_view(request):
650         # ...
651     my_view = user_passes_test(lambda u: u.has_perm('polls.can_vote'), login_url='/login/')(my_view)
652
653 Example in Python 2.4 syntax::
654
655     from django.contrib.auth.decorators import user_passes_test
656
657     @user_passes_test(lambda u: u.has_perm('polls.can_vote'), login_url='/login/')
658     def my_view(request):
659         # ...
660
661 The permission_required decorator
662 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
663
664 **New in Django development version**
665
666 It's a relatively common task to check whether a user has a particular
667 permission. For that reason, Django provides a shortcut for that case: the
668 ``permission_required()`` decorator. Using this decorator, the earlier example
669 can be written as::
670
671     from django.contrib.auth.decorators import permission_required
672
673     def my_view(request):
674         # ...
675     my_view = permission_required('polls.can_vote')(my_view)
676
677 Note that ``permission_required()`` also takes an optional ``login_url``
678 parameter. Example::
679
680     from django.contrib.auth.decorators import permission_required
681
682     def my_view(request):
683         # ...
684     my_view = permission_required('polls.can_vote', login_url='/loginpage/')(my_view)
685
686 As in the ``login_required`` decorator, ``login_url`` defaults to
687 ``settings.LOGIN_URL``.
688
689 Limiting access to generic views
690 --------------------------------
691
692 To limit access to a `generic view`_, write a thin wrapper around the view,
693 and point your URLconf to your wrapper instead of the generic view itself.
694 For example::
695
696     from django.views.generic.date_based import object_detail
697
698     @login_required
699     def limited_object_detail(*args, **kwargs):
700         return object_detail(*args, **kwargs)
701
702 .. _generic view: ../generic_views/
703
704 Permissions
705 ===========
706
707 Django comes with a simple permissions system. It provides a way to assign
708 permissions to specific users and groups of users.
709
710 It's used by the Django admin site, but you're welcome to use it in your own
711 code.
712
713 The Django admin site uses permissions as follows:
714
715     * Access to view the "add" form and add an object is limited to users with
716       the "add" permission for that type of object.
717     * Access to view the change list, view the "change" form and change an
718       object is limited to users with the "change" permission for that type of
719       object.
720     * Access to delete an object is limited to users with the "delete"
721       permission for that type of object.
722
723 Permissions are set globally per type of object, not per specific object
724 instance. For example, it's possible to say "Mary may change news stories," but
725 it's not currently possible to say "Mary may change news stories, but only the
726 ones she created herself" or "Mary may only change news stories that have a
727 certain status, publication date or ID." The latter functionality is something
728 Django developers are currently discussing.
729
730 Default permissions
731 -------------------
732
733 Three basic permissions -- add, change and delete -- are automatically created
734 for each Django model that has a ``class Admin`` set. Behind the scenes, these
735 permissions are added to the ``auth_permission`` database table when you run
736 ``manage.py syncdb``.
737
738 Note that if your model doesn't have ``class Admin`` set when you run
739 ``syncdb``, the permissions won't be created. If you initialize your database
740 and add ``class Admin`` to models after the fact, you'll need to run
741 ``manage.py syncdb`` again. It will create any missing permissions for
742 all of your installed apps.
743
744 Custom permissions
745 ------------------
746
747 To create custom permissions for a given model object, use the ``permissions``
748 `model Meta attribute`_.
749
750 This example model creates three custom permissions::
751
752     class USCitizen(models.Model):
753         # ...
754         class Meta:
755             permissions = (
756                 ("can_drive", "Can drive"),
757                 ("can_vote", "Can vote in elections"),
758                 ("can_drink", "Can drink alcohol"),
759             )
760
761 The only thing this does is create those extra permissions when you run
762 ``syncdb``.
763
764 .. _model Meta attribute: ../model-api/#meta-options
765
766 API reference
767 -------------
768
769 Just like users, permissions are implemented in a Django model that lives in
770 `django/contrib/auth/models.py`_.
771
772 .. _django/contrib/auth/models.py: http://code.djangoproject.com/browser/django/trunk/django/contrib/auth/models.py
773
774 Fields
775 ~~~~~~
776
777 ``Permission`` objects have the following fields:
778
779     * ``name`` -- Required. 50 characters or fewer. Example: ``'Can vote'``.
780     * ``content_type`` -- Required. A reference to the ``django_content_type``
781       database table, which contains a record for each installed Django model.
782     * ``codename`` -- Required. 100 characters or fewer. Example: ``'can_vote'``.
783
784 Methods
785 ~~~~~~~
786
787 ``Permission`` objects have the standard data-access methods like any other
788 `Django model`_.
789
790 Authentication data in templates
791 ================================
792
793 The currently logged-in user and his/her permissions are made available in the
794 `template context`_ when you use ``RequestContext``.
795
796 .. admonition:: Technicality
797
798    Technically, these variables are only made available in the template context
799    if you use ``RequestContext`` *and* your ``TEMPLATE_CONTEXT_PROCESSORS``
800    setting contains ``"django.core.context_processors.auth"``, which is default.
801    For more, see the `RequestContext docs`_.
802
803    .. _RequestContext docs: ../templates_python/#subclassing-context-requestcontext
804
805 Users
806 -----
807
808 The currently logged-in user, either a ``User`` instance or an``AnonymousUser``
809 instance, is stored in the template variable ``{{ user }}``::
810
811     {% if user.is_authenticated %}
812         <p>Welcome, {{ user.username }}. Thanks for logging in.</p>
813     {% else %}
814         <p>Welcome, new user. Please log in.</p>
815     {% endif %}
816
817 Permissions
818 -----------
819
820 The currently logged-in user's permissions are stored in the template variable
821 ``{{ perms }}``. This is an instance of ``django.core.context_processors.PermWrapper``,
822 which is a template-friendly proxy of permissions.
823
824 In the ``{{ perms }}`` object, single-attribute lookup is a proxy to
825 ``User.has_module_perms``. This example would display ``True`` if the logged-in
826 user had any permissions in the ``foo`` app::
827
828     {{ perms.foo }}
829
830 Two-level-attribute lookup is a proxy to ``User.has_perm``. This example would
831 display ``True`` if the logged-in user had the permission ``foo.can_vote``::
832
833     {{ perms.foo.can_vote }}
834
835 Thus, you can check permissions in template ``{% if %}`` statements::
836
837     {% if perms.foo %}
838         <p>You have permission to do something in the foo app.</p>
839         {% if perms.foo.can_vote %}
840             <p>You can vote!</p>
841         {% endif %}
842         {% if perms.foo.can_drive %}
843             <p>You can drive!</p>
844         {% endif %}
845     {% else %}
846         <p>You don't have permission to do anything in the foo app.</p>
847     {% endif %}
848
849 .. _template context: ../templates_python/
850
851 Groups
852 ======
853
854 Groups are a generic way of categorizing users so you can apply permissions, or
855 some other label, to those users. A user can belong to any number of groups.
856
857 A user in a group automatically has the permissions granted to that group. For
858 example, if the group ``Site editors`` has the permission
859 ``can_edit_home_page``, any user in that group will have that permission.
860
861 Beyond permissions, groups are a convenient way to categorize users to give
862 them some label, or extended functionality. For example, you could create a
863 group ``'Special users'``, and you could write code that could, say, give them
864 access to a members-only portion of your site, or send them members-only e-mail
865 messages.
866
867 Messages
868 ========
869
870 The message system is a lightweight way to queue messages for given users.
871
872 A message is associated with a ``User``. There's no concept of expiration or
873 timestamps.
874
875 Messages are used by the Django admin after successful actions. For example,
876 ``"The poll Foo was created successfully."`` is a message.
877
878 The API is simple:
879
880     * To create a new message, use
881       ``user_obj.message_set.create(message='message_text')``.
882     * To retrieve/delete messages, use ``user_obj.get_and_delete_messages()``,
883       which returns a list of ``Message`` objects in the user's queue (if any)
884       and deletes the messages from the queue.
885
886 In this example view, the system saves a message for the user after creating
887 a playlist::
888
889     def create_playlist(request, songs):
890         # Create the playlist with the given songs.
891         # ...
892         request.user.message_set.create(message="Your playlist was added successfully.")
893         return render_to_response("playlists/create.html",
894             context_instance=RequestContext(request))
895
896 When you use ``RequestContext``, the currently logged-in user and his/her
897 messages are made available in the `template context`_ as the template variable
898 ``{{ messages }}``. Here's an example of template code that displays messages::
899
900     {% if messages %}
901     <ul>
902         {% for message in messages %}
903         <li>{{ message }}</li>
904         {% endfor %}
905     </ul>
906     {% endif %}
907
908 Note that ``RequestContext`` calls ``get_and_delete_messages`` behind the
909 scenes, so any messages will be deleted even if you don't display them.
910
911 Finally, note that this messages framework only works with users in the user
912 database. To send messages to anonymous users, use the `session framework`_.
913
914 .. _session framework: ../sessions/
915
916 Other authentication sources
917 ============================
918
919 The authentication that comes with Django is good enough for most common cases,
920 but you may have the need to hook into another authentication source -- that
921 is, another source of usernames and passwords or authentication methods.
922
923 For example, your company may already have an LDAP setup that stores a username
924 and password for every employee. It'd be a hassle for both the network
925 administrator and the users themselves if users had separate accounts in LDAP
926 and the Django-based applications.
927
928 So, to handle situations like this, the Django authentication system lets you
929 plug in another authentication sources. You can override Django's default
930 database-based scheme, or you can use the default system in tandem with other
931 systems.
932
933 Specifying authentication backends
934 ----------------------------------
935
936 Behind the scenes, Django maintains a list of "authentication backends" that it
937 checks for authentication. When somebody calls
938 ``django.contrib.auth.authenticate()`` -- as described in "How to log a user in"
939 above -- Django tries authenticating across all of its authentication backends.
940 If the first authentication method fails, Django tries the second one, and so
941 on, until all backends have been attempted.
942
943 The list of authentication backends to use is specified in the
944 ``AUTHENTICATION_BACKENDS`` setting. This should be a tuple of Python path
945 names that point to Python classes that know how to authenticate. These classes
946 can be anywhere on your Python path.
947
948 By default, ``AUTHENTICATION_BACKENDS`` is set to::
949
950     ('django.contrib.auth.backends.ModelBackend',)
951
952 That's the basic authentication scheme that checks the Django users database.
953
954 The order of ``AUTHENTICATION_BACKENDS`` matters, so if the same username and
955 password is valid in multiple backends, Django will stop processing at the
956 first positive match.
957
958 Writing an authentication backend
959 ---------------------------------
960
961 An authentication backend is a class that implements two methods:
962 ``get_user(id)`` and ``authenticate(**credentials)``.
963
964 The ``get_user`` method takes an ``id`` -- which could be a username, database
965 ID or whatever -- and returns a ``User`` object.
966
967 The  ``authenticate`` method takes credentials as keyword arguments. Most of
968 the time, it'll just look like this::
969
970     class MyBackend:
971         def authenticate(self, username=None, password=None):
972             # Check the username/password and return a User.
973
974 But it could also authenticate a token, like so::
975
976     class MyBackend:
977         def authenticate(self, token=None):
978             # Check the token and return a User.
979
980 Either way, ``authenticate`` should check the credentials it gets, and it
981 should return a ``User`` object that matches those credentials, if the
982 credentials are valid. If they're not valid, it should return ``None``.
983
984 The Django admin system is tightly coupled to the Django ``User`` object
985 described at the beginning of this document. For now, the best way to deal with
986 this is to create a Django ``User`` object for each user that exists for your
987 backend (e.g., in your LDAP directory, your external SQL database, etc.) You
988 can either write a script to do this in advance, or your ``authenticate``
989 method can do it the first time a user logs in.
990
991 Here's an example backend that authenticates against a username and password
992 variable defined in your ``settings.py`` file and creates a Django ``User``
993 object the first time a user authenticates::
994
995     from django.conf import settings
996     from django.contrib.auth.models import User, check_password
997
998     class SettingsBackend:
999         """
1000         Authenticate against the settings ADMIN_LOGIN and ADMIN_PASSWORD.
1001
1002         Use the login name, and a hash of the password. For example:
1003
1004         ADMIN_LOGIN = 'admin'
1005         ADMIN_PASSWORD = 'sha1$4e987$afbcf42e21bd417fb71db8c66b321e9fc33051de'
1006         """
1007         def authenticate(self, username=None, password=None):
1008             login_valid = (settings.ADMIN_LOGIN == username)
1009             pwd_valid = check_password(password, settings.ADMIN_PASSWORD)
1010             if login_valid and pwd_valid:
1011                 try:
1012                     user = User.objects.get(username=username)
1013                 except User.DoesNotExist:
1014                     # Create a new user. Note that we can set password
1015                     # to anything, because it won't be checked; the password
1016                     # from settings.py will.
1017                     user = User(username=username, password='get from settings.py')
1018                     user.is_staff = True
1019                     user.is_superuser = True
1020                     user.save()
1021                 return user
1022             return None
1023
1024         def get_user(self, user_id):
1025             try:
1026                 return User.objects.get(pk=user_id)
1027             except User.DoesNotExist:
1028                 return None
Note: See TracBrowser for help on using the browser.