~ubuntu-branches/ubuntu/quantal/python-django/quantal-security

« back to all changes in this revision

Viewing changes to docs/topics/auth.txt

  • Committer: Bazaar Package Importer
  • Author(s): Chris Lamb
  • Date: 2010-05-21 07:52:55 UTC
  • mfrom: (1.3.6 upstream)
  • mto: This revision was merged to the branch mainline in revision 28.
  • Revision ID: james.westby@ubuntu.com-20100521075255-ii78v1dyfmyu3uzx
Tags: upstream-1.2
ImportĀ upstreamĀ versionĀ 1.2

Show diffs side-by-side

added added

removed removed

Lines of Context:
23
23
      user.
24
24
    * Messages: A simple way to queue messages for given users.
25
25
 
 
26
.. deprecated:: 1.2
 
27
   The Messages component of the auth system will be removed in Django 1.4.
 
28
 
26
29
Installation
27
30
============
28
31
 
31
34
 
32
35
    1. Put ``'django.contrib.auth'`` and ``'django.contrib.contenttypes'`` in
33
36
       your :setting:`INSTALLED_APPS` setting.
34
 
       (The :class:`~django.contrib.auth.models.Permisson` model in
 
37
       (The :class:`~django.contrib.auth.models.Permission` model in
35
38
       :mod:`django.contrib.auth` depends on :mod:`django.contrib.contenttypes`.)
36
39
    2. Run the command ``manage.py syncdb``.
37
40
 
69
72
        Required. 30 characters or fewer. Alphanumeric characters only
70
73
        (letters, digits and underscores).
71
74
 
 
75
        .. versionchanged:: 1.2
 
76
           Usernames may now contain ``@``, ``+``, ``.`` and ``-`` characters.
 
77
 
72
78
    .. attribute:: models.User.first_name
73
79
 
74
80
        Optional. 30 characters or fewer.
94
100
    .. attribute:: models.User.is_active
95
101
 
96
102
        Boolean. Designates whether this user account should be considered
97
 
        active. Set this flag to ``False`` instead of deleting accounts.
 
103
        active. We recommend that you set this flag to ``False`` instead of
 
104
        deleting accounts; that way, if your applications have any foreign keys
 
105
        to users, the foreign keys won't break.
98
106
 
99
 
        This doesn't control whether or not the user can log in. Nothing in the
100
 
        authentication path checks the ``is_active`` flag, so if you want to
101
 
        reject a login based on ``is_active`` being ``False``, it is up to you
102
 
        to check that in your own login view. However, permission checking
103
 
        using the methods like :meth:`~models.User.has_perm` does check this
104
 
        flag and will always return ``False`` for inactive users.
 
107
        This doesn't necessarily control whether or not the user can log in.
 
108
        Authentication backends aren't required to check for the ``is_active``
 
109
        flag, so if you want to reject a login based on ``is_active`` being
 
110
        ``False``, it's up to you to check that in your own login view.
 
111
        However, the :class:`~django.contrib.auth.forms.AuthenticationForm`
 
112
        used by the :func:`~django.contrib.auth.views.login` view *does*
 
113
        perform this check, as do the permission-checking methods such as
 
114
        :meth:`~models.User.has_perm` and the authentication in the Django
 
115
        admin. All of those functions/methods will return ``False`` for
 
116
        inactive users.
105
117
 
106
118
    .. attribute:: models.User.is_superuser
107
119
 
199
211
        :meth:`~django.contrib.auth.models.User.set_unusable_password()` has
200
212
        been called for this user.
201
213
 
202
 
    .. method:: models.User.get_group_permissions()
 
214
    .. method:: models.User.get_group_permissions(obj=None)
203
215
 
204
216
        Returns a list of permission strings that the user has, through his/her
205
217
        groups.
206
218
 
207
 
    .. method:: models.User.get_all_permissions()
 
219
        .. versionadded:: 1.2
 
220
 
 
221
        If ``obj`` is passed in, only returns the group permissions for
 
222
        this specific object.
 
223
 
 
224
    .. method:: models.User.get_all_permissions(obj=None)
208
225
 
209
226
        Returns a list of permission strings that the user has, both through
210
227
        group and user permissions.
211
228
 
212
 
    .. method:: models.User.has_perm(perm)
 
229
        .. versionadded:: 1.2
 
230
 
 
231
        If ``obj`` is passed in, only returns the permissions for this
 
232
        specific object.
 
233
 
 
234
    .. method:: models.User.has_perm(perm, obj=None)
213
235
 
214
236
        Returns ``True`` if the user has the specified permission, where perm is
215
 
        in the format ``"<app label>.<permission codename>"``.
216
 
        If the user is inactive, this method will always return ``False``.
217
 
 
218
 
    .. method:: models.User.has_perms(perm_list)
 
237
        in the format ``"<app label>.<permission codename>"``. (see
 
238
        `permissions`_ section below). If the user is inactive, this method will
 
239
        always return ``False``.
 
240
 
 
241
        .. versionadded:: 1.2
 
242
 
 
243
        If ``obj`` is passed in, this method won't check for a permission for
 
244
        the model, but for this specific object.
 
245
 
 
246
    .. method:: models.User.has_perms(perm_list, obj=None)
219
247
 
220
248
        Returns ``True`` if the user has each of the specified permissions,
221
 
        where each perm is in the format 
 
249
        where each perm is in the format
222
250
        ``"<app label>.<permission codename>"``. If the user is inactive,
223
251
        this method will always return ``False``.
224
252
 
 
253
        .. versionadded:: 1.2
 
254
 
 
255
        If ``obj`` is passed in, this method won't check for permissions for
 
256
        the model, but for the specific object.
 
257
 
225
258
    .. method:: models.User.has_module_perms(package_name)
226
259
 
227
260
        Returns ``True`` if the user has any permissions in the given package
260
293
    .. method:: models.UserManager.create_user(username, email, password=None)
261
294
 
262
295
        Creates, saves and returns a :class:`~django.contrib.auth.models.User`.
263
 
        The :attr:`~django.contrib.auth.models.User.username`,
264
 
        :attr:`~django.contrib.auth.models.User.email` and
265
 
        :attr:`~django.contrib.auth.models.User.password` are set as given, and
266
 
        the :class:`~django.contrib.auth.models.User` gets ``is_active=True``.
 
296
 
 
297
        The :attr:`~django.contrib.auth.models.User.username` and
 
298
        :attr:`~django.contrib.auth.models.User.password` are set as given. The
 
299
        domain portion of :attr:`~django.contrib.auth.models.User.email` is
 
300
        automatically convered to lowercase, and the returned
 
301
        :class:`~django.contrib.auth.models.User` object will have
 
302
        :attr:`~models.User.is_active` set to ``True``.
267
303
 
268
304
        If no password is provided,
269
305
        :meth:`~django.contrib.auth.models.User.set_unusable_password()` will
321
357
Changing passwords
322
358
~~~~~~~~~~~~~~~~~~
323
359
 
324
 
Change a password with :meth:`~django.contrib.auth.models.User.set_password()`:
 
360
.. versionadded:: 1.2
 
361
   The ``manage.py changepassword`` command was added.
 
362
 
 
363
:djadmin:`manage.py changepassword <username>` offers a method of
 
364
changing a User's password from the command line. It prompts you to
 
365
change the password of a given user which you must enter twice. If
 
366
they both match, the new password will be changed immediately. If you
 
367
do not supply a user, the command will attempt to change the password
 
368
whose username matches the current user.
 
369
 
 
370
You can also change a password programmatically, using
 
371
:meth:`~django.contrib.auth.models.User.set_password()`:
325
372
 
326
373
.. code-block:: python
327
374
 
439
486
provides a method to specify a site-specific related model -- termed a "user
440
487
profile" -- for this purpose.
441
488
 
442
 
To make use of this feature, define a model with fields for the additional
443
 
information you'd like to store, or additional methods you'd like to have
444
 
available, and also add a :class:`~django.db.models.Field.ForeignKey` from your
445
 
model to the :class:`~django.contrib.auth.models.User` model, specified with
446
 
``unique=True`` to ensure only one instance of your model can be created for
447
 
each :class:`~django.contrib.auth.models.User`.
 
489
To make use of this feature, define a model with fields for the
 
490
additional information you'd like to store, or additional methods
 
491
you'd like to have available, and also add a
 
492
:class:`~django.db.models.Field.OneToOneField` from your model to the
 
493
:class:`~django.contrib.auth.models.User` model. This will ensure only
 
494
one instance of your model can be created for each
 
495
:class:`~django.contrib.auth.models.User`.
448
496
 
449
497
To indicate that this model is the user profile model for a given site, fill in
450
498
the setting :setting:`AUTH_PROFILE_MODULE` with a string consisting of the
655
703
 
656
704
        from django.contrib.auth.decorators import login_required
657
705
 
658
 
        def my_view(request):
659
 
            # ...
660
 
        my_view = login_required(my_view)
661
 
 
662
 
    Here's an equivalent example, using the more compact decorator syntax
663
 
    introduced in Python 2.4::
664
 
 
665
 
        from django.contrib.auth.decorators import login_required
666
 
 
667
706
        @login_required
668
707
        def my_view(request):
669
 
            # ...
 
708
            ...
670
709
 
671
710
    :func:`~django.contrib.auth.decorators.login_required` also takes an
672
711
    optional ``redirect_field_name`` parameter. Example::
673
712
 
674
 
        from django.contrib.auth.decorators import login_required
675
 
 
676
 
        def my_view(request):
677
 
            # ...
678
 
        my_view = login_required(redirect_field_name='redirect_to')(my_view)
679
 
 
680
 
    Again, an equivalent example of the more compact decorator syntax
681
 
    introduced in Python 2.4::
682
713
 
683
714
        from django.contrib.auth.decorators import login_required
684
715
 
685
716
        @login_required(redirect_field_name='redirect_to')
686
717
        def my_view(request):
687
 
            # ...
 
718
            ...
688
719
 
689
720
    :func:`~django.contrib.auth.decorators.login_required` does the following:
690
721
 
705
736
 
706
737
    (r'^accounts/login/$', 'django.contrib.auth.views.login'),
707
738
 
708
 
.. function:: views.login(request, [template_name, redirect_field_name])
 
739
.. function:: views.login(request, [template_name, redirect_field_name, authentication_form])
709
740
 
710
741
    Here's what ``django.contrib.auth.views.login`` does:
711
742
 
757
788
    starting point. It assumes you have a :file:`base.html` template that
758
789
    defines a ``content`` block:
759
790
 
760
 
    .. code-block:: html
 
791
    .. code-block:: html+django
761
792
 
762
793
        {% extends "base.html" %}
763
794
 
767
798
        <p>Your username and password didn't match. Please try again.</p>
768
799
        {% endif %}
769
800
 
770
 
        <form method="post" action="{% url django.contrib.auth.views.login %}">
 
801
        <form method="post" action="{% url django.contrib.auth.views.login %}">{% csrf_token %}
771
802
        <table>
772
803
        <tr>
773
804
            <td>{{ form.username.label_tag }}</td>
785
816
 
786
817
        {% endblock %}
787
818
 
 
819
    .. versionadded:: 1.2
 
820
 
 
821
    If you are using alternate authentication (see
 
822
    :ref:`authentication-backends`) you can pass a custom authentication form
 
823
    to the login view via the ``authentication_form`` parameter. This form must
 
824
    accept a ``request`` keyword argument in its ``__init__`` method, and
 
825
    provide a ``get_user`` method which returns the authenticated user object
 
826
    (this method is only ever called after successful form validation).
 
827
 
788
828
    .. _forms documentation: ../forms/
789
829
    .. _site framework docs: ../sites/
790
830
 
824
864
        * ``login_url``: The URL of the login page to redirect to. This will
825
865
          default to :setting:`settings.LOGIN_URL <LOGIN_URL>` if not supplied.
826
866
 
827
 
.. function:: views.password_change(request[, template_name, post_change_redirect])
 
867
.. function:: views.password_change(request[, template_name, post_change_redirect, password_change_form])
828
868
 
829
869
    Allows a user to change their password.
830
870
 
837
877
        * ``post_change_redirect``: The URL to redirect to after a successful
838
878
          password change.
839
879
 
 
880
        * .. versionadded:: 1.2
 
881
 
 
882
          ``password_change_form``: A custom "change password" form which must
 
883
          accept a ``user`` keyword argument. The form is responsible for
 
884
          actually changing the user's password.
 
885
 
 
886
 
840
887
    **Template context:**
841
888
 
842
889
        * ``form``: The password change form.
867
914
          :file:`registration/password_reset_email.html` if not supplied.
868
915
 
869
916
        * ``password_reset_form``: Form that will be used to set the password.
870
 
          Defaults to ``SetPasswordForm``.
 
917
          Defaults to :class:`~django.contrib.auth.forms.PasswordResetForm`.
871
918
 
872
919
        * ``token_generator``: Instance of the class to check the password. This
873
920
          will default to ``default_token_generator``, it's an instance of
991
1038
``polls.can_vote``::
992
1039
 
993
1040
    def my_view(request):
994
 
        if not (request.user.is_authenticated() and request.user.has_perm('polls.can_vote')):
 
1041
        if not request.user.has_perm('polls.can_vote'):
995
1042
            return HttpResponse("You can't vote in this poll.")
996
1043
        # ...
997
1044
 
1001
1048
 
1002
1049
        from django.contrib.auth.decorators import user_passes_test
1003
1050
 
 
1051
        @user_passes_test(lambda u: u.has_perm('polls.can_vote'))
1004
1052
        def my_view(request):
1005
 
            # ...
1006
 
        my_view = user_passes_test(lambda u: u.has_perm('polls.can_vote'))(my_view)
 
1053
            ...
1007
1054
 
1008
1055
    We're using this particular test as a relatively simple example. However,
1009
1056
    if you just want to test whether a permission is available to a user, you
1010
1057
    can use the :func:`~django.contrib.auth.decorators.permission_required()`
1011
1058
    decorator, described later in this document.
1012
1059
 
1013
 
    Here's the same thing, using Python 2.4's decorator syntax::
1014
 
 
1015
 
        from django.contrib.auth.decorators import user_passes_test
1016
 
 
1017
 
        @user_passes_test(lambda u: u.has_perm('polls.can_vote'))
1018
 
        def my_view(request):
1019
 
            # ...
1020
 
 
1021
1060
    :func:`~django.contrib.auth.decorators.user_passes_test` takes a required
1022
1061
    argument: a callable that takes a
1023
1062
    :class:`~django.contrib.auth.models.User` object and returns ``True`` if
1030
1069
    optional ``login_url`` argument, which lets you specify the URL for your
1031
1070
    login page (:setting:`settings.LOGIN_URL <LOGIN_URL>` by default).
1032
1071
 
1033
 
    Example in Python 2.3 syntax::
1034
 
 
1035
 
        from django.contrib.auth.decorators import user_passes_test
1036
 
 
1037
 
        def my_view(request):
1038
 
            # ...
1039
 
        my_view = user_passes_test(lambda u: u.has_perm('polls.can_vote'), login_url='/login/')(my_view)
1040
 
 
1041
 
    Example in Python 2.4 syntax::
 
1072
    For example::
1042
1073
 
1043
1074
        from django.contrib.auth.decorators import user_passes_test
1044
1075
 
1045
1076
        @user_passes_test(lambda u: u.has_perm('polls.can_vote'), login_url='/login/')
1046
1077
        def my_view(request):
1047
 
            # ...
 
1078
            ...
1048
1079
 
1049
1080
The permission_required decorator
1050
1081
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1058
1089
 
1059
1090
        from django.contrib.auth.decorators import permission_required
1060
1091
 
 
1092
        @permission_required('polls.can_vote')
1061
1093
        def my_view(request):
1062
 
            # ...
1063
 
        my_view = permission_required('polls.can_vote')(my_view)
 
1094
            ...
1064
1095
 
1065
1096
    As for the :meth:`User.has_perm` method, permission names take the form
1066
1097
    ``"<app label>.<permission codename>"`` (i.e. ``polls.can_vote`` for a
1071
1102
 
1072
1103
        from django.contrib.auth.decorators import permission_required
1073
1104
 
 
1105
        @permission_required('polls.can_vote', login_url='/loginpage/')
1074
1106
        def my_view(request):
1075
 
            # ...
1076
 
        my_view = permission_required('polls.can_vote', login_url='/loginpage/')(my_view)
 
1107
            ...
1077
1108
 
1078
1109
    As in the :func:`~decorators.login_required` decorator, ``login_url``
1079
1110
    defaults to :setting:`settings.LOGIN_URL <LOGIN_URL>`.
1091
1122
    def limited_object_detail(*args, **kwargs):
1092
1123
        return object_detail(*args, **kwargs)
1093
1124
 
 
1125
.. _permissions:
 
1126
 
1094
1127
Permissions
1095
1128
===========
1096
1129
 
1133
1166
permissions for new models each time you run :djadmin:`manage.py syncdb
1134
1167
<syncdb>`.
1135
1168
 
 
1169
Assuming you have an application with an
 
1170
:attr:`~django.db.models.Options.app_label` ``foo`` and a model named ``Bar``,
 
1171
to test for basic permissions you should use:
 
1172
 
 
1173
    * add: ``user.has_perm('foo.add_bar')``
 
1174
    * change: ``user.has_perm('foo.change_bar')``
 
1175
    * delete: ``user.has_perm('foo.delete_bar')``
 
1176
 
1136
1177
.. _custom-permissions:
1137
1178
 
1138
1179
Custom permissions
1202
1243
   Technically, these variables are only made available in the template context
1203
1244
   if you use :class:`~django.template.context.RequestContext` *and* your
1204
1245
   :setting:`TEMPLATE_CONTEXT_PROCESSORS` setting contains
1205
 
   ``"django.core.context_processors.auth"``, which is default. For more, see
1206
 
   the :ref:`RequestContext docs <subclassing-context-requestcontext>`.
 
1246
   ``"django.contrib.auth.context_processors.auth"``, which is default. For
 
1247
   more, see the :ref:`RequestContext docs <subclassing-context-requestcontext>`.
1207
1248
 
1208
1249
Users
1209
1250
-----
1213
1254
instance or an :class:`~django.contrib.auth.models.AnonymousUser` instance, is
1214
1255
stored in the template variable ``{{ user }}``:
1215
1256
 
1216
 
.. code-block:: html
 
1257
.. code-block:: html+django
1217
1258
 
1218
1259
    {% if user.is_authenticated %}
1219
1260
        <p>Welcome, {{ user.username }}. Thanks for logging in.</p>
1248
1289
 
1249
1290
Thus, you can check permissions in template ``{% if %}`` statements:
1250
1291
 
1251
 
.. code-block:: html
 
1292
.. code-block:: html+django
1252
1293
 
1253
1294
    {% if perms.foo %}
1254
1295
        <p>You have permission to do something in the foo app.</p>
1281
1322
Messages
1282
1323
========
1283
1324
 
 
1325
.. deprecated:: 1.2
 
1326
   This functionality will be removed in Django 1.4.  You should use the
 
1327
   :ref:`messages framework <ref-contrib-messages>` for all new projects and
 
1328
   begin to update your existing code immediately.
 
1329
 
1284
1330
The message system is a lightweight way to queue messages for given users.
1285
1331
 
1286
1332
A message is associated with a :class:`~django.contrib.auth.models.User`.
1316
1362
:ref:`template context <ref-templates-api>` as the template variable
1317
1363
``{{ messages }}``. Here's an example of template code that displays messages:
1318
1364
 
1319
 
.. code-block:: html
 
1365
.. code-block:: html+django
1320
1366
 
1321
1367
    {% if messages %}
1322
1368
    <ul>
1326
1372
    </ul>
1327
1373
    {% endif %}
1328
1374
 
1329
 
Note that :class:`~django.template.context.RequestContext` calls
1330
 
:meth:`~django.contrib.auth.models.User.get_and_delete_messages` behind the
1331
 
scenes, so any messages will be deleted even if you don't display them.
 
1375
.. versionchanged:: 1.2
 
1376
   The ``messages`` template variable uses a backwards compatible method in the
 
1377
   :ref:`messages framework <ref-contrib-messages>` to retrieve messages from
 
1378
   both the user ``Message`` model and from the new framework.  Unlike in
 
1379
   previous revisions, the messages will not be erased unless they are actually
 
1380
   displayed.
1332
1381
 
1333
1382
Finally, note that this messages framework only works with users in the user
1334
1383
database. To send messages to anonymous users, use the
1335
 
:ref:`session framework <topics-http-sessions>`.
 
1384
:ref:`messages framework <ref-contrib-messages>`.
1336
1385
 
1337
1386
.. _authentication-backends:
1338
1387
 
1502
1551
the ``auth_permission`` table most of the time.
1503
1552
 
1504
1553
.. _django/contrib/auth/backends.py: http://code.djangoproject.com/browser/django/trunk/django/contrib/auth/backends.py
 
1554
 
 
1555
Authorization for anonymous users
 
1556
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
 
1557
 
 
1558
.. versionchanged:: 1.2
 
1559
 
 
1560
An anonymous user is one that is not authenticated i.e. they have provided no
 
1561
valid authentication details. However, that does not necessarily mean they are
 
1562
not authorized to do anything. At the most basic level, most Web sites
 
1563
authorize anonymous users to browse most of the site, and many allow anonymous
 
1564
posting of comments etc.
 
1565
 
 
1566
Django's permission framework does not have a place to store permissions for
 
1567
anonymous users. However, it has a foundation that allows custom authentication
 
1568
backends to specify authorization for anonymous users. This is especially useful
 
1569
for the authors of re-usable apps, who can delegate all questions of authorization
 
1570
to the auth backend, rather than needing settings, for example, to control
 
1571
anonymous access.
 
1572
 
 
1573
To enable this in your own backend, you must set the class attribute
 
1574
``supports_anonymous_user`` to ``True``. (This precaution is to maintain
 
1575
compatibility with backends that assume that all user objects are actual
 
1576
instances of the :class:`django.contrib.auth.models.User` class). With this
 
1577
in place, :class:`django.contrib.auth.models.AnonymousUser` will delegate all
 
1578
the relevant permission methods to the authentication backends.
 
1579
 
 
1580
A nonexistent ``supports_anonymous_user`` attribute will raise a hidden
 
1581
``PendingDeprecationWarning`` if used in Django 1.2. In Django 1.3, this
 
1582
warning will be upgraded to a ``DeprecationWarning``, which will be displayed
 
1583
loudly. Additionally ``supports_anonymous_user`` will be set to ``False``.
 
1584
Django 1.4 will assume that every backend supports anonymous users being
 
1585
passed to the authorization methods.
 
1586
 
 
1587
Handling object permissions
 
1588
---------------------------
 
1589
 
 
1590
Django's permission framework has a foundation for object permissions, though
 
1591
there is no implementation for it in the core. That means that checking for
 
1592
object permissions will always return ``False`` or an empty list (depending on
 
1593
the check performed).
 
1594
 
 
1595
To enable object permissions in your own
 
1596
:ref:`authentication backend <ref-authentication-backends>` you'll just have
 
1597
to allow passing an ``obj`` parameter to the permission methods and set the
 
1598
``supports_object_permissions`` class attribute to ``True``.
 
1599
 
 
1600
A nonexistent ``supports_object_permissions`` will raise a hidden
 
1601
``PendingDeprecationWarning`` if used in Django 1.2. In Django 1.3, this
 
1602
warning will be upgraded to a ``DeprecationWarning``, which will be displayed
 
1603
loudly. Additionally ``supports_object_permissions`` will be set to ``False``.
 
1604
Django 1.4 will assume that every backend supports object permissions and
 
1605
won't check for the existence of ``supports_object_permissions``, which
 
1606
means not supporting ``obj`` as a parameter will raise a ``TypeError``.