Django

Code

root/django/branches/gis/docs/authentication.txt

Revision 8215, 42.6 kB (checked in by jbronn, 4 months ago)

gis: Merged revisions 7981-8001,8003-8011,8013-8033,8035-8036,8038-8039,8041-8063,8065-8076,8078-8139,8141-8154,8156-8214 via svnmerge from trunk.

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