summaryrefslogtreecommitdiff
path: root/docs/authentication.txt
diff options
context:
space:
mode:
authorAdrian Holovaty <adrian@holovaty.com>2006-05-02 01:31:56 +0000
committerAdrian Holovaty <adrian@holovaty.com>2006-05-02 01:31:56 +0000
commitf69cf70ed813a8cd7e1f963a14ae39103e8d5265 (patch)
treed3b32e84cd66573b3833ddf662af020f8ef2f7a8 /docs/authentication.txt
parentd5dbeaa9be359a4c794885c2e9f1b5a7e5e51fb8 (diff)
MERGED MAGIC-REMOVAL BRANCH TO TRUNK. This change is highly backwards-incompatible. Please read http://code.djangoproject.com/wiki/RemovingTheMagic for upgrade instructions.
git-svn-id: http://code.djangoproject.com/svn/django/trunk@2809 bcc190cf-cafb-0310-a4f2-bffc1f526a37
Diffstat (limited to 'docs/authentication.txt')
-rw-r--r--docs/authentication.txt227
1 files changed, 131 insertions, 96 deletions
diff --git a/docs/authentication.txt b/docs/authentication.txt
index 4c45ec6759..8f618f8a20 100644
--- a/docs/authentication.txt
+++ b/docs/authentication.txt
@@ -6,13 +6,8 @@ Django comes with a user authentication system. It handles user accounts,
groups, permissions and cookie-based user sessions. This document explains how
things work.
-The basics
-==========
-
-Django supports authentication out of the box. The ``django-admin.py init``
-command, used to initialize a database with Django's core database tables,
-creates the infrastructure for the auth system. You don't have to do anything
-else to use authentication.
+Overview
+========
The auth system consists of:
@@ -23,13 +18,35 @@ The auth system consists of:
user.
* Messages: A simple way to queue messages for given users.
+Installation
+============
+
+Authentication support is bundled as a Django application in
+``django.contrib.auth``. To install it, do the following:
+
+ 1. Put ``'django.contrib.auth'`` in your ``INSTALLED_APPS`` setting.
+ 2. Run the command ``manage.py syncdb``.
+
+Note that the default ``settings.py`` file created by
+``django-admin.py startproject`` includes ``'django.contrib.auth'`` in
+``INSTALLED_APPS`` for convenience. If your ``INSTALLED_APPS`` already contains
+``'django.contrib.auth'``, feel free to run ``manage.py syncdb`` again; you
+can run that command as many times as you'd like, and each time it'll only
+install what's needed.
+
+The ``syncdb`` command creates the necessary database tables, creates
+permission objects for all installed apps that need 'em, and prompts you to
+create a superuser account.
+
+Once you've taken those steps, that's it.
+
Users
=====
Users are represented by a standard Django model, which lives in
-`django/models/auth.py`_.
+`django/contrib/auth/models.py`_.
-.. _django/models/auth.py: http://code.djangoproject.com/browser/django/trunk/django/models/auth.py
+.. _django/contrib/auth/models.py: http://code.djangoproject.com/browser/django/trunk/django/contrib/auth/models.py
API reference
-------------
@@ -62,16 +79,20 @@ Methods
~~~~~~~
``User`` objects have two many-to-many fields: ``groups`` and
-``user_permissions``. Because of those relationships, ``User`` objects get
-data-access methods like any other `Django model`_:
+``user_permissions``. ``User`` objects can access their related
+objects in the same way as any other `Django model`_::
- * ``get_group_list(**kwargs)``
- * ``set_groups(id_list)``
- * ``get_permission_list(**kwargs)``
- * ``set_user_permissions(id_list)``
+ ``myuser.objects.groups = [group_list]``
+ ``myuser.objects.groups.add(group, group,...)``
+ ``myuser.objects.groups.remove(group, group,...)``
+ ``myuser.objects.groups.clear()``
+ ``myuser.objects.permissions = [permission_list]``
+ ``myuser.objects.permissions.add(permission, permission, ...)``
+ ``myuser.objects.permissions.remove(permission, permission, ...]``
+ ``myuser.objects.permissions.clear()``
In addition to those automatic API methods, ``User`` objects have the following
-methods:
+custom methods:
* ``is_anonymous()`` -- Always returns ``False``. This is a way of
comparing ``User`` objects to anonymous users.
@@ -80,11 +101,12 @@ methods:
with a space in between.
* ``set_password(raw_password)`` -- Sets the user's password to the given
- raw string, taking care of the MD5 hashing. Doesn't save the ``User``
- object.
+ raw string, taking care of the password hashing. Doesn't save the
+ ``User`` object.
* ``check_password(raw_password)`` -- Returns ``True`` if the given raw
- string is the correct password for the user.
+ string is the correct password for the user. (This takes care of the
+ password hashing in making the comparison.)
* ``get_group_permissions()`` -- Returns a list of permission strings that
the user has, through his/her groups.
@@ -110,23 +132,25 @@ methods:
`DEFAULT_FROM_EMAIL`_ setting.
* ``get_profile()`` -- Returns a site-specific profile for this user.
- Raises ``django.models.auth.SiteProfileNotAvailable`` if the current site
+ Raises ``django.contrib.auth.models.SiteProfileNotAvailable`` if the current site
doesn't allow profiles.
.. _Django model: http://www.djangoproject.com/documentation/model_api/
.. _DEFAULT_FROM_EMAIL: http://www.djangoproject.com/documentation/settings/#default-from-email
-Module functions
-~~~~~~~~~~~~~~~~
+Manager functions
+~~~~~~~~~~~~~~~~~
-The ``django.models.auth.users`` module has the following helper functions:
+The ``User`` model has a custom manager that has the following helper functions:
* ``create_user(username, email, password)`` -- Creates, saves and returns
a ``User``. The ``username``, ``email`` and ``password`` are set as
given, and the ``User`` gets ``is_active=True``.
+ See _`Creating users` for example usage.
+
* ``make_random_password(length=10, allowed_chars='abcdefghjkmnpqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789')``
- -- Returns a random password with the given length and given string of
+ Returns a random password with the given length and given string of
allowed characters. (Note that the default value of ``allowed_chars``
doesn't contain ``"I"`` or letters that look like it, to avoid user
confusion.
@@ -140,11 +164,12 @@ Creating users
The most basic way to create users is to use the ``create_user`` helper
function that comes with Django::
- >>> from django.models.auth import users
- >>> user = users.create_user('john', 'lennon@thebeatles.com', 'johnpassword')
+ >>> from django.contrib.auth.models import User
+ >>> user = User.objects.create_user('john', 'lennon@thebeatles.com', 'johnpassword')
- # Now, user is a User object already saved to the database.
- # You can continue to change its attributes if you want to change other fields.
+ # At this point, user is a User object ready to be saved
+ # to the database. You can continue to change its attributes
+ # if you want to change other fields.
>>> user.is_staff = True
>>> user.save()
@@ -153,28 +178,26 @@ Changing passwords
Change a password with ``set_password()``::
- >>> from django.models.auth import users
- >>> u = users.get_object(username__exact='john')
+ >>> from django.contrib.auth.models import User
+ >>> u = User.objects.get(username__exact='john')
>>> u.set_password('new password')
>>> u.save()
-Don't set the password field directly unless you know what you're doing. This
-is explained in the next section.
+Don't set the ``password`` attribute directly unless you know what you're
+doing. This is explained in the next section.
Passwords
---------
-Previous versions, such as Django 0.90, used simple MD5 hashes without password
-salts.
-
-The ``password`` field of a ``User`` object is a string in this format::
+The ``password`` attribute of a ``User`` object is a string in this format::
hashtype$salt$hash
That's hashtype, salt and hash, separated by the dollar-sign character.
-Hashtype is either ``sha1`` (default) or ``md5``. Salt is a random string
-used to salt the raw password to create the hash.
+Hashtype is either ``sha1`` (default) or ``md5`` -- the algorithm used to
+perform a one-way hash of the password. Salt is a random string used to salt
+the raw password to create the hash.
For example::
@@ -183,17 +206,22 @@ For example::
The ``User.set_password()`` and ``User.check_password()`` functions handle
the setting and checking of these values behind the scenes.
+Previous Django versions, such as 0.90, used simple MD5 hashes without password
+salts. For backwards compatibility, those are still supported; they'll be
+converted automatically to the new style the first time ``check_password()``
+works correctly for a given user.
+
Anonymous users
---------------
-``django.parts.auth.anonymoususers.AnonymousUser`` is a class that implements
-the ``django.models.auth.users.User`` interface, with these differences:
+``django.contrib.auth.models.AnonymousUser`` is a class that implements
+the ``django.contirb.auth.models.User`` interface, with these differences:
* ``id`` is always ``None``.
* ``is_anonymous()`` returns ``True`` instead of ``False``.
* ``has_perm()`` always returns ``False``.
- * ``set_password()``, ``check_password()``, ``set_groups()`` and
- ``set_permissions()`` raise ``NotImplementedError``.
+ * ``set_password()``, ``check_password()``, ``save()``, ``delete()``,
+ ``set_groups()`` and ``set_permissions()`` raise ``NotImplementedError``.
In practice, you probably won't need to use ``AnonymousUser`` objects on your
own, but they're used by Web requests, as explained in the next section.
@@ -202,10 +230,15 @@ Authentication in Web requests
==============================
Until now, this document has dealt with the low-level APIs for manipulating
-authentication-related objects. On a higher level, Django hooks this
+authentication-related objects. On a higher level, Django can hook this
authentication framework into its system of `request objects`_.
-In any Django view, ``request.user`` will give you a ``User`` object
+First, install the ``SessionMiddleware`` and ``AuthenticationMiddleware``
+middlewares by adding them to your ``MIDDLEWARE_CLASSES`` setting. See the
+`session documentation`_ for more information.
+
+Once you have those middlewares installed, you'll be able to access
+``request.user`` in views. ``request.user`` will give you a ``User`` object
representing the currently logged-in user. If a user isn't currently logged in,
``request.user`` will be set to an instance of ``AnonymousUser`` (see the
previous section). You can tell them apart with ``is_anonymous()``, like so::
@@ -215,10 +248,6 @@ previous section). You can tell them apart with ``is_anonymous()``, like so::
else:
# Do something for logged-in users.
-If you want to use ``request.user`` in your view code, make sure you have
-``SessionMiddleware`` enabled. See the `session documentation`_ for more
-information.
-
.. _request objects: http://www.djangoproject.com/documentation/request_response/#httprequest-objects
.. _session documentation: http://www.djangoproject.com/documentation/sessions/
@@ -227,8 +256,8 @@ How to log a user in
To log a user in, do the following within a view::
- from django.models.auth import users
- request.session[users.SESSION_KEY] = some_user.id
+ from django.contrib.auth.models import SESSION_KEY
+ request.session[SESSION_KEY] = some_user.id
Because this uses sessions, you'll need to make sure you have
``SessionMiddleware`` enabled. See the `session documentation`_ for more
@@ -246,7 +275,7 @@ The raw way
The simple, raw way to limit access to pages is to check
``request.user.is_anonymous()`` and either redirect to a login page::
- from django.utils.httpwrappers import HttpResponseRedirect
+ from django.http import HttpResponseRedirect
def my_view(request):
if request.user.is_anonymous():
@@ -257,7 +286,7 @@ The simple, raw way to limit access to pages is to check
def my_view(request):
if request.user.is_anonymous():
- return render_to_response('myapp/login_error')
+ return render_to_response('myapp/login_error.html')
# ...
The login_required decorator
@@ -265,15 +294,16 @@ The login_required decorator
As a shortcut, you can use the convenient ``login_required`` decorator::
- from django.views.decorators.auth import login_required
+ from django.contrib.auth.decorators import login_required
def my_view(request):
# ...
my_view = login_required(my_view)
-Here's the same thing, using Python 2.4's decorator syntax::
+Here's an equivalent example, using the more compact decorator syntax
+introduced in Python 2.4::
- from django.views.decorators.auth import login_required
+ from django.contrib.auth.decorators import login_required
@login_required
def my_view(request):
@@ -304,7 +334,7 @@ permission ``polls.can_vote``::
As a shortcut, you can use the convenient ``user_passes_test`` decorator::
- from django.views.decorators.auth import user_passes_test
+ from django.contrib.auth.decorators import user_passes_test
def my_view(request):
# ...
@@ -312,7 +342,7 @@ As a shortcut, you can use the convenient ``user_passes_test`` decorator::
Here's the same thing, using Python 2.4's decorator syntax::
- from django.views.decorators.auth import user_passes_test
+ from django.contrib.auth.decorators import user_passes_test
@user_passes_test(lambda u: u.has_perm('polls.can_vote'))
def my_view(request):
@@ -328,7 +358,7 @@ specify the URL for your login page (``/accounts/login/`` by default).
Example in Python 2.3 syntax::
- from django.views.decorators.auth import user_passes_test
+ from django.contrib.auth.decorators import user_passes_test
def my_view(request):
# ...
@@ -336,7 +366,7 @@ Example in Python 2.3 syntax::
Example in Python 2.4 syntax::
- from django.views.decorators.auth import user_passes_test
+ from django.contrib.auth.decorators import user_passes_test
@user_passes_test(lambda u: u.has_perm('polls.can_vote'), login_url='/login/')
def my_view(request):
@@ -380,49 +410,52 @@ Permissions are set globally per type of object, not per specific object
instance. For example, it's possible to say "Mary may change news stories," but
it's not currently possible to say "Mary may change news stories, but only the
ones she created herself" or "Mary may only change news stories that have a
-certain status or publication date." The latter functionality is something
+certain status, publication date or ID." The latter functionality is something
Django developers are currently discussing.
Default permissions
-------------------
Three basic permissions -- add, create and delete -- are automatically created
-for each Django model that has ``admin`` set. Behind the scenes, these
-permissions are added to the ``auth_permissions`` database table when you run
-``django-admin.py install [app]``. You can view the exact SQL ``INSERT``
-statements by running ``django-admin.py sqlinitialdata [app]``.
+for each Django model that has a ``class Admin`` set. Behind the scenes, these
+permissions are added to the ``auth_permission`` database table when you run
+``manage.py syncdb``.
-Note that if your model doesn't have ``admin`` set when you run
-``django-admin.py install``, the permissions won't be created. If you
-initialize your database and add ``admin`` to models after the fact, you'll
-need to add the permissions to the database manually. Do this by running
-``django-admin.py installperms [app]``, which creates any missing permissions
-for the given app.
+Note that if your model doesn't have ``class Admin`` set when you run
+``syncdb``, the permissions won't be created. If you initialize your database
+and add ``class Admin`` to models after the fact, you'll need to run
+``django-admin.py syncdb`` again. It will create any missing permissions for
+all of your installed apps.
Custom permissions
------------------
To create custom permissions for a given model object, use the ``permissions``
-`model META attribute`_.
+`model Meta attribute`_.
This example model creates three custom permissions::
- class USCitizen(meta.Model):
+ class USCitizen(models.Model):
# ...
- class META:
+ class Meta:
permissions = (
("can_drive", "Can drive"),
("can_vote", "Can vote in elections"),
("can_drink", "Can drink alcohol"),
)
-.. _model META attribute: http://www.djangoproject.com/documentation/model_api/#meta-options
+The only thing this does is create those extra permissions when you run
+``syncdb``.
+
+.. _model Meta attribute: http://www.djangoproject.com/documentation/model_api/#meta-options
API reference
-------------
Just like users, permissions are implemented in a Django model that lives in
-`django/models/auth.py`_.
+`django/contrib/auth/models.py`_.
+
+.. _django/contrib/auth/models.py: http://code.djangoproject.com/browser/django/trunk/django/contrib/auth/models.py
Fields
~~~~~~
@@ -430,8 +463,8 @@ Fields
``Permission`` objects have the following fields:
* ``name`` -- Required. 50 characters or fewer. Example: ``'Can vote'``.
- * ``package`` -- Required. A reference to the ``packages`` database table,
- which contains a record for each installed Django application.
+ * ``content_type`` -- Required. A reference to the ``django_content_type``
+ database table, which contains a record for each installed Django model.
* ``codename`` -- Required. 100 characters or fewer. Example: ``'can_vote'``.
Methods
@@ -444,21 +477,21 @@ Authentication data in templates
================================
The currently logged-in user and his/her permissions are made available in the
-`template context`_ when you use ``DjangoContext``.
+`template context`_ when you use ``RequestContext``.
.. admonition:: Technicality
Technically, these variables are only made available in the template context
- if you use ``DjangoContext`` *and* your ``TEMPLATE_CONTEXT_PROCESSORS``
+ if you use ``RequestContext`` *and* your ``TEMPLATE_CONTEXT_PROCESSORS``
setting contains ``"django.core.context_processors.auth"``, which is default.
- For more, see the `DjangoContext docs`_.
+ For more, see the `RequestContext docs`_.
- .. _DjangoContext docs: http://www.djangoproject.com/documentation/templates_python/#subclassing-context-djangocontext
+ .. _RequestContext docs: http://www.djangoproject.com/documentation/templates_python/#subclassing-context-djangocontext
Users
-----
-The currently logged-in user, either a ``User`` object or an``AnonymousUser``
+The currently logged-in user, either a ``User`` instance or an``AnonymousUser``
instance, is stored in the template variable ``{{ user }}``::
{% if user.is_anonymous %}
@@ -504,25 +537,25 @@ Thus, you can check permissions in template ``{% if %}`` statements::
Groups
======
-Groups are a generic way of categorizing users to apply permissions, or some
-other label, to those users. A user can belong to any number of groups.
+Groups are a generic way of categorizing users so you can apply permissions, or
+some other label, to those users. A user can belong to any number of groups.
A user in a group automatically has the permissions granted to that group. For
example, if the group ``Site editors`` has the permission
``can_edit_home_page``, any user in that group will have that permission.
-Beyond permissions, groups are a convenient way to categorize users to apply
-some label, or extended functionality, to them. For example, you could create
-a group ``'Special users'``, and you could write code that would do special
-things to those users -- such as giving them access to a members-only portion
-of your site, or sending them members-only e-mail messages.
+Beyond permissions, groups are a convenient way to categorize users to give
+them some label, or extended functionality. For example, you could create a
+group ``'Special users'``, and you could write code that could, say, give them
+access to a members-only portion of your site, or send them members-only e-mail
+messages.
Messages
========
The message system is a lightweight way to queue messages for given users.
-A message is associated with a User. There's no concept of expiration or
+A message is associated with a ``User``. There's no concept of expiration or
timestamps.
Messages are used by the Django admin after successful actions. For example,
@@ -530,8 +563,9 @@ Messages are used by the Django admin after successful actions. For example,
The API is simple::
- * To add messages, use ``user.add_message(message_text)``.
- * To retrieve/delete messages, use ``user.get_and_delete_messages()``,
+ * To create a new message, use
+ ``user_obj.message_set.create(message='message_text')``.
+ * To retrieve/delete messages, use ``user_obj.get_and_delete_messages()``,
which returns a list of ``Message`` objects in the user's queue (if any)
and deletes the messages from the queue.
@@ -541,10 +575,11 @@ a playlist::
def create_playlist(request, songs):
# Create the playlist with the given songs.
# ...
- request.user.add_message("Your playlist was added successfully.")
- return render_to_response("playlists/create", context_instance=DjangoContext(request))
+ request.user.message_set.create(message="Your playlist was added successfully.")
+ return render_to_response("playlists/create.html",
+ context_instance=RequestContext(request))
-When you use ``DjangoContext``, the currently logged-in user and his/her
+When you use ``RequestContext``, the currently logged-in user and his/her
messages are made available in the `template context`_ as the template variable
``{{ messages }}``. Here's an example of template code that displays messages::
@@ -556,7 +591,7 @@ messages are made available in the `template context`_ as the template variable
</ul>
{% endif %}
-Note that ``DjangoContext`` calls ``get_and_delete_messages`` behind the
+Note that ``RequestContext`` calls ``get_and_delete_messages`` behind the
scenes, so any messages will be deleted even if you don't display them.
Finally, note that this messages framework only works with users in the user