Fixed #5868 -- Provided an example of how to extend simplejson to serialize
[django.git] / docs / authentication.txt
blobaee9c5224aefd4253cd2a684ff0a438f15a5f79c
1 =============================
2 User authentication in Django
3 =============================
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.
9 Overview
10 ========
12 The auth system consists of:
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.
21 Installation
22 ============
24 Authentication support is bundled as a Django application in
25 ``django.contrib.auth``. To install it, do the following:
27     1. Put ``'django.contrib.auth'`` in your ``INSTALLED_APPS`` setting.
28     2. Run the command ``manage.py syncdb``.
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.
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.
41 Once you've taken those steps, that's it.
43 Users
44 =====
46 Users are represented by a standard Django model, which lives in
47 `django/contrib/auth/models.py`_.
49 .. _django/contrib/auth/models.py: http://code.djangoproject.com/browser/django/trunk/django/contrib/auth/models.py
51 API reference
52 -------------
54 Fields
55 ~~~~~~
57 ``User`` objects have the following fields:
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.
78 Methods
79 ~~~~~~~
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`_::
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()
94 In addition to those automatic API methods, ``User`` objects have the following
95 custom methods:
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.
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.
106     * ``get_full_name()`` -- Returns the ``first_name`` plus the ``last_name``,
107       with a space in between.
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.
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.)
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.
122       You may need this if authentication for your application takes place
123       against an existing external source such as an LDAP directory.
125     * ``has_usable_password()`` -- **New in Django development version.**
126       Returns ``False`` if ``set_unusable_password()`` has been called for this
127       user.
129     * ``get_group_permissions()`` -- Returns a list of permission strings that
130       the user has, through his/her groups.
132     * ``get_all_permissions()`` -- Returns a list of permission strings that
133       the user has, both through group and user permissions.
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``.
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``.
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``.
148     * ``get_and_delete_messages()`` -- Returns a list of ``Message`` objects in
149       the user's queue and deletes the messages from the queue.
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.
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.
159 .. _Django model: ../model-api/
160 .. _DEFAULT_FROM_EMAIL: ../settings/#default-from-email
162 Manager functions
163 ~~~~~~~~~~~~~~~~~
165 The ``User`` model has a custom manager that has the following helper functions:
167     * ``create_user(username, email, password=None)`` -- Creates, saves and
168       returns a ``User``. The ``username``, ``email`` and ``password`` are set
169       as given, and the ``User`` gets ``is_active=True``.
171       If no password is provided, ``set_unusable_password()`` will be called.
173       See _`Creating users` for example usage.
175     * ``make_random_password(length=10, allowed_chars='abcdefghjkmnpqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789')``
176       Returns a random password with the given length and given string of
177       allowed characters. (Note that the default value of ``allowed_chars``
178       doesn't contain letters that can cause user confusion, including
179       ``1``, ``I`` and ``0``).
181 Basic usage
182 -----------
184 Creating users
185 ~~~~~~~~~~~~~~
187 The most basic way to create users is to use the ``create_user`` helper
188 function that comes with Django::
190     >>> from django.contrib.auth.models import User
191     >>> user = User.objects.create_user('john', 'lennon@thebeatles.com', 'johnpassword')
193     # At this point, user is a User object that has already been saved
194     # to the database. You can continue to change its attributes
195     # if you want to change other fields.
196     >>> user.is_staff = True
197     >>> user.save()
199 Changing passwords
200 ~~~~~~~~~~~~~~~~~~
202 Change a password with ``set_password()``::
204     >>> from django.contrib.auth.models import User
205     >>> u = User.objects.get(username__exact='john')
206     >>> u.set_password('new password')
207     >>> u.save()
209 Don't set the ``password`` attribute directly unless you know what you're
210 doing. This is explained in the next section.
212 Passwords
213 ---------
215 The ``password`` attribute of a ``User`` object is a string in this format::
217     hashtype$salt$hash
219 That's hashtype, salt and hash, separated by the dollar-sign character.
221 Hashtype is either ``sha1`` (default), ``md5`` or ``crypt`` -- the algorithm
222 used to perform a one-way hash of the password. Salt is a random string used
223 to salt the raw password to create the hash. Note that the ``crypt`` method is
224 only supported on platforms that have the standard Python ``crypt`` module
225 available, and ``crypt`` support is only available in the Django development
226 version.
228 For example::
230     sha1$a1976$a36cc8cbf81742a8fb52e221aaeab48ed7f58ab4
232 The ``User.set_password()`` and ``User.check_password()`` functions handle
233 the setting and checking of these values behind the scenes.
235 Previous Django versions, such as 0.90, used simple MD5 hashes without password
236 salts. For backwards compatibility, those are still supported; they'll be
237 converted automatically to the new style the first time ``User.check_password()``
238 works correctly for a given user.
240 Anonymous users
241 ---------------
243 ``django.contrib.auth.models.AnonymousUser`` is a class that implements
244 the ``django.contrib.auth.models.User`` interface, with these differences:
246     * ``id`` is always ``None``.
247     * ``is_staff`` and ``is_superuser`` are always False.
248     * ``is_active`` is always True.
249     * ``groups`` and ``user_permissions`` are always empty.
250     * ``is_anonymous()`` returns ``True`` instead of ``False``.
251     * ``is_authenticated()`` returns ``False`` instead of ``True``.
252     * ``has_perm()`` always returns ``False``.
253     * ``set_password()``, ``check_password()``, ``save()``, ``delete()``,
254       ``set_groups()`` and ``set_permissions()`` raise ``NotImplementedError``.
256 In practice, you probably won't need to use ``AnonymousUser`` objects on your
257 own, but they're used by Web requests, as explained in the next section.
259 Creating superusers
260 -------------------
262 ``manage.py syncdb`` prompts you to create a superuser the first time you run
263 it after adding ``'django.contrib.auth'`` to your ``INSTALLED_APPS``. But if
264 you need to create a superuser after that via the command line, you can use the
265 ``create_superuser.py`` utility. Just run this command::
267     python /path/to/django/contrib/auth/create_superuser.py
269 Make sure to substitute ``/path/to/`` with the path to the Django codebase on
270 your filesystem.
272 Authentication in Web requests
273 ==============================
275 Until now, this document has dealt with the low-level APIs for manipulating
276 authentication-related objects. On a higher level, Django can hook this
277 authentication framework into its system of `request objects`_.
279 First, install the ``SessionMiddleware`` and ``AuthenticationMiddleware``
280 middlewares by adding them to your ``MIDDLEWARE_CLASSES`` setting. See the
281 `session documentation`_ for more information.
283 Once you have those middlewares installed, you'll be able to access
284 ``request.user`` in views. ``request.user`` will give you a ``User`` object
285 representing the currently logged-in user. If a user isn't currently logged in,
286 ``request.user`` will be set to an instance of ``AnonymousUser`` (see the
287 previous section). You can tell them apart with ``is_authenticated()``, like so::
289     if request.user.is_authenticated():
290         # Do something for authenticated users.
291     else:
292         # Do something for anonymous users.
294 .. _request objects: ../request_response/#httprequest-objects
295 .. _session documentation: ../sessions/
297 How to log a user in
298 --------------------
300 Django provides two functions in ``django.contrib.auth``: ``authenticate()``
301 and ``login()``.
303 To authenticate a given username and password, use ``authenticate()``. It
304 takes two keyword arguments, ``username`` and ``password``, and it returns
305 a ``User`` object if the password is valid for the given username. If the
306 password is invalid, ``authenticate()`` returns ``None``. Example::
308     from django.contrib.auth import authenticate
309     user = authenticate(username='john', password='secret')
310     if user is not None:
311         if user.is_active:
312             print "You provided a correct username and password!"
313         else:
314             print "Your account has been disabled!"
315     else:
316         print "Your username and password were incorrect."
318 To log a user in, in a view, use ``login()``. It takes an ``HttpRequest``
319 object and a ``User`` object. ``login()`` saves the user's ID in the session,
320 using Django's session framework, so, as mentioned above, you'll need to make
321 sure to have the session middleware installed.
323 This example shows how you might use both ``authenticate()`` and ``login()``::
325     from django.contrib.auth import authenticate, login
327     def my_view(request):
328         username = request.POST['username']
329         password = request.POST['password']
330         user = authenticate(username=username, password=password)
331         if user is not None:
332             if user.is_active:
333                 login(request, user)
334                 # Redirect to a success page.
335             else:
336                 # Return a 'disabled account' error message
337         else:
338             # Return an 'invalid login' error message.
340 Manually checking a user's password
341 -----------------------------------
343 If you'd like to manually authenticate a user by comparing a
344 plain-text password to the hashed password in the database, use the
345 convenience function ``django.contrib.auth.models.check_password``. It
346 takes two arguments: the plain-text password to check, and the full
347 value of a user's ``password`` field in the database to check against,
348 and returns ``True`` if they match, ``False`` otherwise.
350 How to log a user out
351 ---------------------
353 To log out a user who has been logged in via ``django.contrib.auth.login()``,
354 use ``django.contrib.auth.logout()`` within your view. It takes an
355 ``HttpRequest`` object and has no return value. Example::
357     from django.contrib.auth import logout
359     def logout_view(request):
360         logout(request)
361         # Redirect to a success page.
363 Note that ``logout()`` doesn't throw any errors if the user wasn't logged in.
365 Limiting access to logged-in users
366 ----------------------------------
368 The raw way
369 ~~~~~~~~~~~
371 The simple, raw way to limit access to pages is to check
372 ``request.user.is_authenticated()`` and either redirect to a login page::
374     from django.http import HttpResponseRedirect
376     def my_view(request):
377         if not request.user.is_authenticated():
378             return HttpResponseRedirect('/login/?next=%s' % request.path)
379         # ...
381 ...or display an error message::
383     def my_view(request):
384         if not request.user.is_authenticated():
385             return render_to_response('myapp/login_error.html')
386         # ...
388 The login_required decorator
389 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
391 As a shortcut, you can use the convenient ``login_required`` decorator::
393     from django.contrib.auth.decorators import login_required
395     def my_view(request):
396         # ...
397     my_view = login_required(my_view)
399 Here's an equivalent example, using the more compact decorator syntax
400 introduced in Python 2.4::
402     from django.contrib.auth.decorators import login_required
404     @login_required
405     def my_view(request):
406         # ...
408 In the Django development version, ``login_required`` also takes an optional
409 ``redirect_field_name`` parameter. Example::
410     
411     from django.contrib.auth.decorators import login_required
413     def my_view(request):
414         # ...
415     my_view = login_required(redirect_field_name='redirect_to')(my_view)
417 Again, an equivalent example of the more compact decorator syntax introduced in Python 2.4::
418     
419     from django.contrib.auth.decorators import login_required
421     @login_required(redirect_field_name='redirect_to')
422     def my_view(request):
423         # ...
425 ``login_required`` does the following:
427     * If the user isn't logged in, redirect to ``settings.LOGIN_URL``
428       (``/accounts/login/`` by default), passing the current absolute URL
429       in the query string as ``next`` or the value of ``redirect_field_name``. 
430       For example:
431       ``/accounts/login/?next=/polls/3/``.
432     * If the user is logged in, execute the view normally. The view code is
433       free to assume the user is logged in.
435 Note that you'll need to map the appropriate Django view to ``settings.LOGIN_URL``.
436 For example, using the defaults, add the following line to your URLconf::
438     (r'^accounts/login/$', 'django.contrib.auth.views.login'),
440 Here's what ``django.contrib.auth.views.login`` does:
442     * If called via ``GET``, it displays a login form that POSTs to the same
443       URL. More on this in a bit.
445     * If called via ``POST``, it tries to log the user in. If login is
446       successful, the view redirects to the URL specified in ``next``. If
447       ``next`` isn't provided, it redirects to ``settings.LOGIN_REDIRECT_URL``
448       (which defaults to ``/accounts/profile/``). If login isn't successful,
449       it redisplays the login form.
451 It's your responsibility to provide the login form in a template called
452 ``registration/login.html`` by default. This template gets passed three
453 template context variables:
455     * ``form``: A ``FormWrapper`` object representing the login form. See the
456       `forms documentation`_ for more on ``FormWrapper`` objects.
457     * ``next``: The URL to redirect to after successful login. This may contain
458       a query string, too.
459     * ``site_name``: The name of the current ``Site``, according to the
460       ``SITE_ID`` setting. If you're using the Django development version and
461       you don't have the site framework installed, this will be set to the
462       value of ``request.META['SERVER_NAME']``. For more on sites, see the
463       `site framework docs`_.
465 If you'd prefer not to call the template ``registration/login.html``, you can
466 pass the ``template_name`` parameter via the extra arguments to the view in
467 your URLconf. For example, this URLconf line would use ``myapp/login.html``
468 instead::
470     (r'^accounts/login/$', 'django.contrib.auth.views.login', {'template_name': 'myapp/login.html'}),
472 Here's a sample ``registration/login.html`` template you can use as a starting
473 point. It assumes you have a ``base.html`` template that defines a ``content``
474 block::
476     {% extends "base.html" %}
478     {% block content %}
480     {% if form.has_errors %}
481     <p>Your username and password didn't match. Please try again.</p>
482     {% endif %}
484     <form method="post" action=".">
485     <table>
486     <tr><td><label for="id_username">Username:</label></td><td>{{ form.username }}</td></tr>
487     <tr><td><label for="id_password">Password:</label></td><td>{{ form.password }}</td></tr>
488     </table>
490     <input type="submit" value="login" />
491     <input type="hidden" name="next" value="{{ next }}" />
492     </form>
494     {% endblock %}
496 .. _forms documentation: ../forms/
497 .. _site framework docs: ../sites/
499 Other built-in views
500 --------------------
502 In addition to the ``login`` view, the authentication system includes a
503 few other useful built-in views:
505 ``django.contrib.auth.views.logout``
506 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
508 **Description:**
510 Logs a user out.
512 **Optional arguments:**
514     * ``template_name``: The full name of a template to display after
515       logging the user out. This will default to
516       ``registration/logged_out.html`` if no argument is supplied.
518 **Template context:**
520     * ``title``: The string "Logged out", localized.
522 ``django.contrib.auth.views.logout_then_login``
523 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
525 **Description:**
527 Logs a user out, then redirects to the login page.
529 **Optional arguments:**
531     * ``login_url``: The URL of the login page to redirect to. This
532       will default to ``settings.LOGIN_URL`` if not supplied.
534 ``django.contrib.auth.views.password_change``
535 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
537 **Description:**
539 Allows a user to change their password.
541 **Optional arguments:**
543     * ``template_name``: The full name of a template to use for
544       displaying the password change form. This will default to
545       ``registration/password_change_form.html`` if not supplied.
547 **Template context:**
549     * ``form``: The password change form.
551 ``django.contrib.auth.views.password_change_done``
552 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
554 **Description:**
556 The page shown after a user has changed their password.
558 **Optional arguments:**
560     * ``template_name``: The full name of a template to use. This will
561       default to ``registration/password_change_done.html`` if not
562       supplied.
564 ``django.contrib.auth.views.password_reset``
565 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
567 **Description:**
569 Allows a user to reset their password, and sends them the new password
570 in an email.
572 **Optional arguments:**
574     * ``template_name``: The full name of a template to use for
575       displaying the password reset form. This will default to
576       ``registration/password_reset_form.html`` if not supplied.
578     * ``email_template_name``: The full name of a template to use for
579       generating the email with the new password. This will default to
580       ``registration/password_reset_email.html`` if not supplied.
582 **Template context:**
584     * ``form``: The form for resetting the user's password.
586 ``django.contrib.auth.views.password_reset_done``
587 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
589 **Description:**
591 The page shown after a user has reset their password.
593 **Optional arguments:**
595     * ``template_name``: The full name of a template to use. This will
596       default to ``registration/password_reset_done.html`` if not
597       supplied.
599 ``django.contrib.auth.views.redirect_to_login``
600 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
602 **Description:**
604 Redirects to the login page, and then back to another URL after a
605 successful login.
607 **Required arguments:**
609     * ``next``: The URL to redirect to after a successful login.
611 **Optional arguments:**
613     * ``login_url``: The URL of the login page to redirect to. This
614       will default to ``settings.LOGIN_URL`` if not supplied.
616 Built-in manipulators
617 ---------------------
619 If you don't want to use the built-in views, but want the convenience
620 of not having to write manipulators for this functionality, the
621 authentication system provides several built-in manipulators:
623     * ``django.contrib.auth.forms.AdminPasswordChangeForm``: A
624       manipulator used in the admin interface to change a user's
625       password.
627     * ``django.contrib.auth.forms.AuthenticationForm``: A manipulator
628       for logging a user in.
630     * ``django.contrib.auth.forms.PasswordChangeForm``: A manipulator
631       for allowing a user to change their password.
633     * ``django.contrib.auth.forms.PasswordResetForm``: A manipulator
634       for resetting a user's password and emailing the new password to
635       them.
637     * ``django.contrib.auth.forms.UserCreationForm``: A manipulator
638       for creating a new user.
640 Limiting access to logged-in users that pass a test
641 ---------------------------------------------------
643 To limit access based on certain permissions or some other test, you'd do
644 essentially the same thing as described in the previous section.
646 The simple way is to run your test on ``request.user`` in the view directly.
647 For example, this view checks to make sure the user is logged in and has the
648 permission ``polls.can_vote``::
650     def my_view(request):
651         if not (request.user.is_authenticated() and request.user.has_perm('polls.can_vote')):
652             return HttpResponse("You can't vote in this poll.")
653         # ...
655 As a shortcut, you can use the convenient ``user_passes_test`` decorator::
657     from django.contrib.auth.decorators import user_passes_test
659     def my_view(request):
660         # ...
661     my_view = user_passes_test(lambda u: u.has_perm('polls.can_vote'))(my_view)
663 We're using this particular test as a relatively simple example. However, if
664 you just want to test whether a permission is available to a user, you can use
665 the ``permission_required()`` decorator, described later in this document.
667 Here's the same thing, using Python 2.4's decorator syntax::
669     from django.contrib.auth.decorators import user_passes_test
671     @user_passes_test(lambda u: u.has_perm('polls.can_vote'))
672     def my_view(request):
673         # ...
675 ``user_passes_test`` takes a required argument: a callable that takes a
676 ``User`` object and returns ``True`` if the user is allowed to view the page.
677 Note that ``user_passes_test`` does not automatically check that the ``User``
678 is not anonymous.
680 ``user_passes_test()`` takes an optional ``login_url`` argument, which lets you
681 specify the URL for your login page (``settings.LOGIN_URL`` by default).
683 Example in Python 2.3 syntax::
685     from django.contrib.auth.decorators import user_passes_test
687     def my_view(request):
688         # ...
689     my_view = user_passes_test(lambda u: u.has_perm('polls.can_vote'), login_url='/login/')(my_view)
691 Example in Python 2.4 syntax::
693     from django.contrib.auth.decorators import user_passes_test
695     @user_passes_test(lambda u: u.has_perm('polls.can_vote'), login_url='/login/')
696     def my_view(request):
697         # ...
699 The permission_required decorator
700 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
702 It's a relatively common task to check whether a user has a particular
703 permission. For that reason, Django provides a shortcut for that case: the
704 ``permission_required()`` decorator. Using this decorator, the earlier example
705 can be written as::
707     from django.contrib.auth.decorators import permission_required
709     def my_view(request):
710         # ...
711     my_view = permission_required('polls.can_vote')(my_view)
713 Note that ``permission_required()`` also takes an optional ``login_url``
714 parameter. Example::
716     from django.contrib.auth.decorators import permission_required
718     def my_view(request):
719         # ...
720     my_view = permission_required('polls.can_vote', login_url='/loginpage/')(my_view)
722 As in the ``login_required`` decorator, ``login_url`` defaults to
723 ``settings.LOGIN_URL``.
725 Limiting access to generic views
726 --------------------------------
728 To limit access to a `generic view`_, write a thin wrapper around the view,
729 and point your URLconf to your wrapper instead of the generic view itself.
730 For example::
732     from django.views.generic.date_based import object_detail
734     @login_required
735     def limited_object_detail(*args, **kwargs):
736         return object_detail(*args, **kwargs)
738 .. _generic view: ../generic_views/
740 Permissions
741 ===========
743 Django comes with a simple permissions system. It provides a way to assign
744 permissions to specific users and groups of users.
746 It's used by the Django admin site, but you're welcome to use it in your own
747 code.
749 The Django admin site uses permissions as follows:
751     * Access to view the "add" form and add an object is limited to users with
752       the "add" permission for that type of object.
753     * Access to view the change list, view the "change" form and change an
754       object is limited to users with the "change" permission for that type of
755       object.
756     * Access to delete an object is limited to users with the "delete"
757       permission for that type of object.
759 Permissions are set globally per type of object, not per specific object
760 instance. For example, it's possible to say "Mary may change news stories," but
761 it's not currently possible to say "Mary may change news stories, but only the
762 ones she created herself" or "Mary may only change news stories that have a
763 certain status, publication date or ID." The latter functionality is something
764 Django developers are currently discussing.
766 Default permissions
767 -------------------
769 Three basic permissions -- add, change and delete -- are automatically created
770 for each Django model that has a ``class Admin`` set. Behind the scenes, these
771 permissions are added to the ``auth_permission`` database table when you run
772 ``manage.py syncdb``.
774 Note that if your model doesn't have ``class Admin`` set when you run
775 ``syncdb``, the permissions won't be created. If you initialize your database
776 and add ``class Admin`` to models after the fact, you'll need to run
777 ``manage.py syncdb`` again. It will create any missing permissions for
778 all of your installed apps.
780 Custom permissions
781 ------------------
783 To create custom permissions for a given model object, use the ``permissions``
784 `model Meta attribute`_.
786 This example model creates three custom permissions::
788     class USCitizen(models.Model):
789         # ...
790         class Meta:
791             permissions = (
792                 ("can_drive", "Can drive"),
793                 ("can_vote", "Can vote in elections"),
794                 ("can_drink", "Can drink alcohol"),
795             )
797 The only thing this does is create those extra permissions when you run
798 ``syncdb``.
800 .. _model Meta attribute: ../model-api/#meta-options
802 API reference
803 -------------
805 Just like users, permissions are implemented in a Django model that lives in
806 `django/contrib/auth/models.py`_.
808 .. _django/contrib/auth/models.py: http://code.djangoproject.com/browser/django/trunk/django/contrib/auth/models.py
810 Fields
811 ~~~~~~
813 ``Permission`` objects have the following fields:
815     * ``name`` -- Required. 50 characters or fewer. Example: ``'Can vote'``.
816     * ``content_type`` -- Required. A reference to the ``django_content_type``
817       database table, which contains a record for each installed Django model.
818     * ``codename`` -- Required. 100 characters or fewer. Example: ``'can_vote'``.
820 Methods
821 ~~~~~~~
823 ``Permission`` objects have the standard data-access methods like any other
824 `Django model`_.
826 Authentication data in templates
827 ================================
829 The currently logged-in user and his/her permissions are made available in the
830 `template context`_ when you use ``RequestContext``.
832 .. admonition:: Technicality
834    Technically, these variables are only made available in the template context
835    if you use ``RequestContext`` *and* your ``TEMPLATE_CONTEXT_PROCESSORS``
836    setting contains ``"django.core.context_processors.auth"``, which is default.
837    For more, see the `RequestContext docs`_.
839    .. _RequestContext docs: ../templates_python/#subclassing-context-requestcontext
841 Users
842 -----
844 The currently logged-in user, either a ``User`` instance or an``AnonymousUser``
845 instance, is stored in the template variable ``{{ user }}``::
847     {% if user.is_authenticated %}
848         <p>Welcome, {{ user.username }}. Thanks for logging in.</p>
849     {% else %}
850         <p>Welcome, new user. Please log in.</p>
851     {% endif %}
853 Permissions
854 -----------
856 The currently logged-in user's permissions are stored in the template variable
857 ``{{ perms }}``. This is an instance of ``django.core.context_processors.PermWrapper``,
858 which is a template-friendly proxy of permissions.
860 In the ``{{ perms }}`` object, single-attribute lookup is a proxy to
861 ``User.has_module_perms``. This example would display ``True`` if the logged-in
862 user had any permissions in the ``foo`` app::
864     {{ perms.foo }}
866 Two-level-attribute lookup is a proxy to ``User.has_perm``. This example would
867 display ``True`` if the logged-in user had the permission ``foo.can_vote``::
869     {{ perms.foo.can_vote }}
871 Thus, you can check permissions in template ``{% if %}`` statements::
873     {% if perms.foo %}
874         <p>You have permission to do something in the foo app.</p>
875         {% if perms.foo.can_vote %}
876             <p>You can vote!</p>
877         {% endif %}
878         {% if perms.foo.can_drive %}
879             <p>You can drive!</p>
880         {% endif %}
881     {% else %}
882         <p>You don't have permission to do anything in the foo app.</p>
883     {% endif %}
885 .. _template context: ../templates_python/
887 Groups
888 ======
890 Groups are a generic way of categorizing users so you can apply permissions, or
891 some other label, to those users. A user can belong to any number of groups.
893 A user in a group automatically has the permissions granted to that group. For
894 example, if the group ``Site editors`` has the permission
895 ``can_edit_home_page``, any user in that group will have that permission.
897 Beyond permissions, groups are a convenient way to categorize users to give
898 them some label, or extended functionality. For example, you could create a
899 group ``'Special users'``, and you could write code that could, say, give them
900 access to a members-only portion of your site, or send them members-only e-mail
901 messages.
903 Messages
904 ========
906 The message system is a lightweight way to queue messages for given users.
908 A message is associated with a ``User``. There's no concept of expiration or
909 timestamps.
911 Messages are used by the Django admin after successful actions. For example,
912 ``"The poll Foo was created successfully."`` is a message.
914 The API is simple:
916     * To create a new message, use
917       ``user_obj.message_set.create(message='message_text')``.
918     * To retrieve/delete messages, use ``user_obj.get_and_delete_messages()``,
919       which returns a list of ``Message`` objects in the user's queue (if any)
920       and deletes the messages from the queue.
922 In this example view, the system saves a message for the user after creating
923 a playlist::
925     def create_playlist(request, songs):
926         # Create the playlist with the given songs.
927         # ...
928         request.user.message_set.create(message="Your playlist was added successfully.")
929         return render_to_response("playlists/create.html",
930             context_instance=RequestContext(request))
932 When you use ``RequestContext``, the currently logged-in user and his/her
933 messages are made available in the `template context`_ as the template variable
934 ``{{ messages }}``. Here's an example of template code that displays messages::
936     {% if messages %}
937     <ul>
938         {% for message in messages %}
939         <li>{{ message }}</li>
940         {% endfor %}
941     </ul>
942     {% endif %}
944 Note that ``RequestContext`` calls ``get_and_delete_messages`` behind the
945 scenes, so any messages will be deleted even if you don't display them.
947 Finally, note that this messages framework only works with users in the user
948 database. To send messages to anonymous users, use the `session framework`_.
950 .. _session framework: ../sessions/
952 Other authentication sources
953 ============================
955 The authentication that comes with Django is good enough for most common cases,
956 but you may have the need to hook into another authentication source -- that
957 is, another source of usernames and passwords or authentication methods.
959 For example, your company may already have an LDAP setup that stores a username
960 and password for every employee. It'd be a hassle for both the network
961 administrator and the users themselves if users had separate accounts in LDAP
962 and the Django-based applications.
964 So, to handle situations like this, the Django authentication system lets you
965 plug in another authentication sources. You can override Django's default
966 database-based scheme, or you can use the default system in tandem with other
967 systems.
969 Specifying authentication backends
970 ----------------------------------
972 Behind the scenes, Django maintains a list of "authentication backends" that it
973 checks for authentication. When somebody calls
974 ``django.contrib.auth.authenticate()`` -- as described in "How to log a user in"
975 above -- Django tries authenticating across all of its authentication backends.
976 If the first authentication method fails, Django tries the second one, and so
977 on, until all backends have been attempted.
979 The list of authentication backends to use is specified in the
980 ``AUTHENTICATION_BACKENDS`` setting. This should be a tuple of Python path
981 names that point to Python classes that know how to authenticate. These classes
982 can be anywhere on your Python path.
984 By default, ``AUTHENTICATION_BACKENDS`` is set to::
986     ('django.contrib.auth.backends.ModelBackend',)
988 That's the basic authentication scheme that checks the Django users database.
990 The order of ``AUTHENTICATION_BACKENDS`` matters, so if the same username and
991 password is valid in multiple backends, Django will stop processing at the
992 first positive match.
994 Writing an authentication backend
995 ---------------------------------
997 An authentication backend is a class that implements two methods:
998 ``get_user(user_id)`` and ``authenticate(**credentials)``.
1000 The ``get_user`` method takes a ``user_id`` -- which could be a username,
1001 database ID or whatever -- and returns a ``User`` object.
1003 The  ``authenticate`` method takes credentials as keyword arguments. Most of
1004 the time, it'll just look like this::
1006     class MyBackend:
1007         def authenticate(self, username=None, password=None):
1008             # Check the username/password and return a User.
1010 But it could also authenticate a token, like so::
1012     class MyBackend:
1013         def authenticate(self, token=None):
1014             # Check the token and return a User.
1016 Either way, ``authenticate`` should check the credentials it gets, and it
1017 should return a ``User`` object that matches those credentials, if the
1018 credentials are valid. If they're not valid, it should return ``None``.
1020 The Django admin system is tightly coupled to the Django ``User`` object
1021 described at the beginning of this document. For now, the best way to deal with
1022 this is to create a Django ``User`` object for each user that exists for your
1023 backend (e.g., in your LDAP directory, your external SQL database, etc.) You
1024 can either write a script to do this in advance, or your ``authenticate``
1025 method can do it the first time a user logs in.
1027 Here's an example backend that authenticates against a username and password
1028 variable defined in your ``settings.py`` file and creates a Django ``User``
1029 object the first time a user authenticates::
1031     from django.conf import settings
1032     from django.contrib.auth.models import User, check_password
1034     class SettingsBackend:
1035         """
1036         Authenticate against the settings ADMIN_LOGIN and ADMIN_PASSWORD.
1038         Use the login name, and a hash of the password. For example:
1040         ADMIN_LOGIN = 'admin'
1041         ADMIN_PASSWORD = 'sha1$4e987$afbcf42e21bd417fb71db8c66b321e9fc33051de'
1042         """
1043         def authenticate(self, username=None, password=None):
1044             login_valid = (settings.ADMIN_LOGIN == username)
1045             pwd_valid = check_password(password, settings.ADMIN_PASSWORD)
1046             if login_valid and pwd_valid:
1047                 try:
1048                     user = User.objects.get(username=username)
1049                 except User.DoesNotExist:
1050                     # Create a new user. Note that we can set password
1051                     # to anything, because it won't be checked; the password
1052                     # from settings.py will.
1053                     user = User(username=username, password='get from settings.py')
1054                     user.is_staff = True
1055                     user.is_superuser = True
1056                     user.save()
1057                 return user
1058             return None
1060         def get_user(self, user_id):
1061             try:
1062                 return User.objects.get(pk=user_id)
1063             except User.DoesNotExist:
1064                 return None
1066 Handling authorization in custom backends
1067 -----------------------------------------
1069 Custom auth backends can provide their own permissions. 
1071 The user model will delegate permission lookup functions
1072 (``get_group_permissions()``, ``get_all_permissions()``, ``has_perm()``, and
1073 ``has_module_perms()``) to any authentication backend that implements these
1074 functions.
1076 The permissions given to the user will be the superset of all permissions
1077 returned by all backends. That is, Django grants a permission to a user that any
1078 one backend grants.
1080 The simple backend above could implement permissions for the magic admin fairly
1081 simply::
1082         
1083     class SettingsBackend:
1084     
1085         # ...
1087         def has_perm(self, user_obj, perm):
1088             if user_obj.username == settings.ADMIN_LOGIN:
1089                 return True
1090             else:
1091                 return False
1092                 
1093 This gives full permissions to the user granted access in the above example. Notice
1094 that the backend auth functions all take the user object as an argument, and
1095 they also accept the same arguments given to the associated ``User`` functions.
1097 A full authorization implementation can be found in
1098 ``django/contrib/auth/backends.py`` _, which is the default backend and queries
1099 the ``auth_permission`` table most of the time.
1101 .. _django/contrib/auth/backends.py: http://code.djangoproject.com/browser/django/trunk/django/contrib/auth/backends.py