|
1 ============================= |
|
2 User authentication in Django |
|
3 ============================= |
|
4 |
|
5 .. module:: django.contrib.auth |
|
6 :synopsis: Django's authentication framework. |
|
7 |
|
8 Django comes with a user authentication system. It handles user accounts, |
|
9 groups, permissions and cookie-based user sessions. This document explains how |
|
10 things work. |
|
11 |
|
12 Overview |
|
13 ======== |
|
14 |
|
15 The auth system consists of: |
|
16 |
|
17 * Users |
|
18 * Permissions: Binary (yes/no) flags designating whether a user may perform |
|
19 a certain task. |
|
20 * Groups: A generic way of applying labels and permissions to more than one |
|
21 user. |
|
22 * Messages: A simple way to queue messages for given users. |
|
23 |
|
24 .. deprecated:: 1.2 |
|
25 The Messages component of the auth system will be removed in Django 1.4. |
|
26 |
|
27 Installation |
|
28 ============ |
|
29 |
|
30 Authentication support is bundled as a Django application in |
|
31 ``django.contrib.auth``. To install it, do the following: |
|
32 |
|
33 1. Put ``'django.contrib.auth'`` and ``'django.contrib.contenttypes'`` in |
|
34 your :setting:`INSTALLED_APPS` setting. |
|
35 (The :class:`~django.contrib.auth.models.Permission` model in |
|
36 :mod:`django.contrib.auth` depends on :mod:`django.contrib.contenttypes`.) |
|
37 2. Run the command ``manage.py syncdb``. |
|
38 |
|
39 Note that the default :file:`settings.py` file created by |
|
40 :djadmin:`django-admin.py startproject <startproject>` includes |
|
41 ``'django.contrib.auth'`` and ``'django.contrib.contenttypes'`` in |
|
42 :setting:`INSTALLED_APPS` for convenience. If your :setting:`INSTALLED_APPS` |
|
43 already contains these apps, feel free to run :djadmin:`manage.py syncdb |
|
44 <syncdb>` again; you can run that command as many times as you'd like, and each |
|
45 time it'll only install what's needed. |
|
46 |
|
47 The :djadmin:`syncdb` command creates the necessary database tables, creates |
|
48 permission objects for all installed apps that need 'em, and prompts you to |
|
49 create a superuser account the first time you run it. |
|
50 |
|
51 Once you've taken those steps, that's it. |
|
52 |
|
53 Users |
|
54 ===== |
|
55 |
|
56 .. class:: models.User |
|
57 |
|
58 API reference |
|
59 ------------- |
|
60 |
|
61 Fields |
|
62 ~~~~~~ |
|
63 |
|
64 .. class:: models.User |
|
65 |
|
66 :class:`~django.contrib.auth.models.User` objects have the following |
|
67 fields: |
|
68 |
|
69 .. attribute:: models.User.username |
|
70 |
|
71 Required. 30 characters or fewer. Alphanumeric characters only |
|
72 (letters, digits and underscores). |
|
73 |
|
74 .. versionchanged:: 1.2 |
|
75 Usernames may now contain ``@``, ``+``, ``.`` and ``-`` characters. |
|
76 |
|
77 .. attribute:: models.User.first_name |
|
78 |
|
79 Optional. 30 characters or fewer. |
|
80 |
|
81 .. attribute:: models.User.last_name |
|
82 |
|
83 Optional. 30 characters or fewer. |
|
84 |
|
85 .. attribute:: models.User.email |
|
86 |
|
87 Optional. E-mail address. |
|
88 |
|
89 .. attribute:: models.User.password |
|
90 |
|
91 Required. A hash of, and metadata about, the password. (Django doesn't |
|
92 store the raw password.) Raw passwords can be arbitrarily long and can |
|
93 contain any character. See the "Passwords" section below. |
|
94 |
|
95 .. attribute:: models.User.is_staff |
|
96 |
|
97 Boolean. Designates whether this user can access the admin site. |
|
98 |
|
99 .. attribute:: models.User.is_active |
|
100 |
|
101 Boolean. Designates whether this user account should be considered |
|
102 active. We recommend that you set this flag to ``False`` instead of |
|
103 deleting accounts; that way, if your applications have any foreign keys |
|
104 to users, the foreign keys won't break. |
|
105 |
|
106 This doesn't necessarily control whether or not the user can log in. |
|
107 Authentication backends aren't required to check for the ``is_active`` |
|
108 flag, so if you want to reject a login based on ``is_active`` being |
|
109 ``False``, it's up to you to check that in your own login view. |
|
110 However, the :class:`~django.contrib.auth.forms.AuthenticationForm` |
|
111 used by the :func:`~django.contrib.auth.views.login` view *does* |
|
112 perform this check, as do the permission-checking methods such as |
|
113 :meth:`~models.User.has_perm` and the authentication in the Django |
|
114 admin. All of those functions/methods will return ``False`` for |
|
115 inactive users. |
|
116 |
|
117 .. attribute:: models.User.is_superuser |
|
118 |
|
119 Boolean. Designates that this user has all permissions without |
|
120 explicitly assigning them. |
|
121 |
|
122 .. attribute:: models.User.last_login |
|
123 |
|
124 A datetime of the user's last login. Is set to the current date/time by |
|
125 default. |
|
126 |
|
127 .. attribute:: models.User.date_joined |
|
128 |
|
129 A datetime designating when the account was created. Is set to the |
|
130 current date/time by default when the account is created. |
|
131 |
|
132 Methods |
|
133 ~~~~~~~ |
|
134 |
|
135 .. class:: models.User |
|
136 |
|
137 :class:`~django.contrib.auth.models.User` objects have two many-to-many |
|
138 fields: models.User. ``groups`` and ``user_permissions``. |
|
139 :class:`~django.contrib.auth.models.User` objects can access their related |
|
140 objects in the same way as any other :doc:`Django model |
|
141 </topics/db/models>`: |
|
142 |
|
143 .. code-block:: python |
|
144 |
|
145 myuser.groups = [group_list] |
|
146 myuser.groups.add(group, group, ...) |
|
147 myuser.groups.remove(group, group, ...) |
|
148 myuser.groups.clear() |
|
149 myuser.user_permissions = [permission_list] |
|
150 myuser.user_permissions.add(permission, permission, ...) |
|
151 myuser.user_permissions.remove(permission, permission, ...) |
|
152 myuser.user_permissions.clear() |
|
153 |
|
154 In addition to those automatic API methods, |
|
155 :class:`~django.contrib.auth.models.User` objects have the following custom |
|
156 methods: |
|
157 |
|
158 .. method:: models.User.is_anonymous() |
|
159 |
|
160 Always returns ``False``. This is a way of differentiating |
|
161 :class:`~django.contrib.auth.models.User` and |
|
162 :class:`~django.contrib.auth.models.AnonymousUser` objects. |
|
163 Generally, you should prefer using |
|
164 :meth:`~django.contrib.auth.models.User.is_authenticated()` to this |
|
165 method. |
|
166 |
|
167 .. method:: models.User.is_authenticated() |
|
168 |
|
169 Always returns ``True``. This is a way to tell if the user has been |
|
170 authenticated. This does not imply any permissions, and doesn't check |
|
171 if the user is active - it only indicates that the user has provided a |
|
172 valid username and password. |
|
173 |
|
174 .. method:: models.User.get_full_name() |
|
175 |
|
176 Returns the :attr:`~django.contrib.auth.models.User.first_name` plus |
|
177 the :attr:`~django.contrib.auth.models.User.last_name`, with a space in |
|
178 between. |
|
179 |
|
180 .. method:: models.User.set_password(raw_password) |
|
181 |
|
182 Sets the user's password to the given raw string, taking care of the |
|
183 password hashing. Doesn't save the |
|
184 :class:`~django.contrib.auth.models.User` object. |
|
185 |
|
186 .. method:: models.User.check_password(raw_password) |
|
187 |
|
188 Returns ``True`` if the given raw string is the correct password for |
|
189 the user. (This takes care of the password hashing in making the |
|
190 comparison.) |
|
191 |
|
192 .. method:: models.User.set_unusable_password() |
|
193 |
|
194 .. versionadded:: 1.0 |
|
195 |
|
196 Marks the user as having no password set. This isn't the same as |
|
197 having a blank string for a password. |
|
198 :meth:`~django.contrib.auth.models.User.check_password()` for this user |
|
199 will never return ``True``. Doesn't save the |
|
200 :class:`~django.contrib.auth.models.User` object. |
|
201 |
|
202 You may need this if authentication for your application takes place |
|
203 against an existing external source such as an LDAP directory. |
|
204 |
|
205 .. method:: models.User.has_usable_password() |
|
206 |
|
207 .. versionadded:: 1.0 |
|
208 |
|
209 Returns ``False`` if |
|
210 :meth:`~django.contrib.auth.models.User.set_unusable_password()` has |
|
211 been called for this user. |
|
212 |
|
213 .. method:: models.User.get_group_permissions(obj=None) |
|
214 |
|
215 Returns a set of permission strings that the user has, through his/her |
|
216 groups. |
|
217 |
|
218 .. versionadded:: 1.2 |
|
219 |
|
220 If ``obj`` is passed in, only returns the group permissions for |
|
221 this specific object. |
|
222 |
|
223 .. method:: models.User.get_all_permissions(obj=None) |
|
224 |
|
225 Returns a set of permission strings that the user has, both through |
|
226 group and user permissions. |
|
227 |
|
228 .. versionadded:: 1.2 |
|
229 |
|
230 If ``obj`` is passed in, only returns the permissions for this |
|
231 specific object. |
|
232 |
|
233 .. method:: models.User.has_perm(perm, obj=None) |
|
234 |
|
235 Returns ``True`` if the user has the specified permission, where perm is |
|
236 in the format ``"<app label>.<permission codename>"``. (see |
|
237 `permissions`_ section below). If the user is inactive, this method will |
|
238 always return ``False``. |
|
239 |
|
240 .. versionadded:: 1.2 |
|
241 |
|
242 If ``obj`` is passed in, this method won't check for a permission for |
|
243 the model, but for this specific object. |
|
244 |
|
245 .. method:: models.User.has_perms(perm_list, obj=None) |
|
246 |
|
247 Returns ``True`` if the user has each of the specified permissions, |
|
248 where each perm is in the format |
|
249 ``"<app label>.<permission codename>"``. If the user is inactive, |
|
250 this method will always return ``False``. |
|
251 |
|
252 .. versionadded:: 1.2 |
|
253 |
|
254 If ``obj`` is passed in, this method won't check for permissions for |
|
255 the model, but for the specific object. |
|
256 |
|
257 .. method:: models.User.has_module_perms(package_name) |
|
258 |
|
259 Returns ``True`` if the user has any permissions in the given package |
|
260 (the Django app label). If the user is inactive, this method will |
|
261 always return ``False``. |
|
262 |
|
263 .. method:: models.User.get_and_delete_messages() |
|
264 |
|
265 Returns a list of :class:`~django.contrib.auth.models.Message` objects |
|
266 in the user's queue and deletes the messages from the queue. |
|
267 |
|
268 .. method:: models.User.email_user(subject, message, from_email=None) |
|
269 |
|
270 Sends an e-mail to the user. If |
|
271 :attr:`~django.contrib.auth.models.User.from_email` is ``None``, Django |
|
272 uses the :setting:`DEFAULT_FROM_EMAIL`. |
|
273 |
|
274 .. method:: models.User.get_profile() |
|
275 |
|
276 Returns a site-specific profile for this user. Raises |
|
277 :exc:`django.contrib.auth.models.SiteProfileNotAvailable` if the |
|
278 current site doesn't allow profiles. For information on how to define a |
|
279 site-specific user profile, see the section on `storing additional user |
|
280 information`_ below. |
|
281 |
|
282 .. _storing additional user information: #storing-additional-information-about-users |
|
283 |
|
284 Manager functions |
|
285 ~~~~~~~~~~~~~~~~~ |
|
286 |
|
287 .. class:: models.UserManager |
|
288 |
|
289 The :class:`~django.contrib.auth.models.User` model has a custom manager |
|
290 that has the following helper functions: |
|
291 |
|
292 .. method:: models.UserManager.create_user(username, email, password=None) |
|
293 |
|
294 Creates, saves and returns a :class:`~django.contrib.auth.models.User`. |
|
295 |
|
296 The :attr:`~django.contrib.auth.models.User.username` and |
|
297 :attr:`~django.contrib.auth.models.User.password` are set as given. The |
|
298 domain portion of :attr:`~django.contrib.auth.models.User.email` is |
|
299 automatically convered to lowercase, and the returned |
|
300 :class:`~django.contrib.auth.models.User` object will have |
|
301 :attr:`~models.User.is_active` set to ``True``. |
|
302 |
|
303 If no password is provided, |
|
304 :meth:`~django.contrib.auth.models.User.set_unusable_password()` will |
|
305 be called. |
|
306 |
|
307 See `Creating users`_ for example usage. |
|
308 |
|
309 .. method:: models.UserManager.make_random_password(length=10, allowed_chars='abcdefghjkmnpqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789') |
|
310 |
|
311 Returns a random password with the given length and given string of |
|
312 allowed characters. (Note that the default value of ``allowed_chars`` |
|
313 doesn't contain letters that can cause user confusion, including: |
|
314 |
|
315 * ``i``, ``l``, ``I``, and ``1`` (lowercase letter i, lowercase |
|
316 letter L, uppercase letter i, and the number one) |
|
317 * ``o``, ``O``, and ``0`` (uppercase letter o, lowercase letter o, |
|
318 and zero) |
|
319 |
|
320 Basic usage |
|
321 ----------- |
|
322 |
|
323 .. _topics-auth-creating-users: |
|
324 |
|
325 Creating users |
|
326 ~~~~~~~~~~~~~~ |
|
327 |
|
328 The most basic way to create users is to use the |
|
329 :meth:`~django.contrib.auth.models.UserManager.create_user` helper function |
|
330 that comes with Django:: |
|
331 |
|
332 >>> from django.contrib.auth.models import User |
|
333 >>> user = User.objects.create_user('john', 'lennon@thebeatles.com', 'johnpassword') |
|
334 |
|
335 # At this point, user is a User object that has already been saved |
|
336 # to the database. You can continue to change its attributes |
|
337 # if you want to change other fields. |
|
338 >>> user.is_staff = True |
|
339 >>> user.save() |
|
340 |
|
341 You can also create users using the Django admin site. Assuming you've enabled |
|
342 the admin site and hooked it to the URL ``/admin/``, the "Add user" page is at |
|
343 ``/admin/auth/user/add/``. You should also see a link to "Users" in the "Auth" |
|
344 section of the main admin index page. The "Add user" admin page is different |
|
345 than standard admin pages in that it requires you to choose a username and |
|
346 password before allowing you to edit the rest of the user's fields. |
|
347 |
|
348 Also note: if you want your own user account to be able to create users using |
|
349 the Django admin site, you'll need to give yourself permission to add users |
|
350 *and* change users (i.e., the "Add user" and "Change user" permissions). If |
|
351 your account has permission to add users but not to change them, you won't be |
|
352 able to add users. Why? Because if you have permission to add users, you have |
|
353 the power to create superusers, which can then, in turn, change other users. So |
|
354 Django requires add *and* change permissions as a slight security measure. |
|
355 |
|
356 Changing passwords |
|
357 ~~~~~~~~~~~~~~~~~~ |
|
358 |
|
359 .. versionadded:: 1.2 |
|
360 The ``manage.py changepassword`` command was added. |
|
361 |
|
362 :djadmin:`manage.py changepassword *username* <changepassword>` offers a method |
|
363 of changing a User's password from the command line. It prompts you to |
|
364 change the password of a given user which you must enter twice. If |
|
365 they both match, the new password will be changed immediately. If you |
|
366 do not supply a user, the command will attempt to change the password |
|
367 whose username matches the current user. |
|
368 |
|
369 You can also change a password programmatically, using |
|
370 :meth:`~django.contrib.auth.models.User.set_password()`: |
|
371 |
|
372 .. code-block:: python |
|
373 |
|
374 >>> from django.contrib.auth.models import User |
|
375 >>> u = User.objects.get(username__exact='john') |
|
376 >>> u.set_password('new password') |
|
377 >>> u.save() |
|
378 |
|
379 Don't set the :attr:`~django.contrib.auth.models.User.password` attribute |
|
380 directly unless you know what you're doing. This is explained in the next |
|
381 section. |
|
382 |
|
383 Passwords |
|
384 --------- |
|
385 |
|
386 The :attr:`~django.contrib.auth.models.User.password` attribute of a |
|
387 :class:`~django.contrib.auth.models.User` object is a string in this format:: |
|
388 |
|
389 hashtype$salt$hash |
|
390 |
|
391 That's hashtype, salt and hash, separated by the dollar-sign character. |
|
392 |
|
393 Hashtype is either ``sha1`` (default), ``md5`` or ``crypt`` -- the algorithm |
|
394 used to perform a one-way hash of the password. Salt is a random string used |
|
395 to salt the raw password to create the hash. Note that the ``crypt`` method is |
|
396 only supported on platforms that have the standard Python ``crypt`` module |
|
397 available. |
|
398 |
|
399 .. versionadded:: 1.0 |
|
400 Support for the ``crypt`` module is new in Django 1.0. |
|
401 |
|
402 For example:: |
|
403 |
|
404 sha1$a1976$a36cc8cbf81742a8fb52e221aaeab48ed7f58ab4 |
|
405 |
|
406 The :meth:`~django.contrib.auth.models.User.set_password` and |
|
407 :meth:`~django.contrib.auth.models.User.check_password` functions handle the |
|
408 setting and checking of these values behind the scenes. |
|
409 |
|
410 Previous Django versions, such as 0.90, used simple MD5 hashes without password |
|
411 salts. For backwards compatibility, those are still supported; they'll be |
|
412 converted automatically to the new style the first time |
|
413 :meth:`~django.contrib.auth.models.User.check_password()` works correctly for |
|
414 a given user. |
|
415 |
|
416 Anonymous users |
|
417 --------------- |
|
418 |
|
419 .. class:: models.AnonymousUser |
|
420 |
|
421 :class:`django.contrib.auth.models.AnonymousUser` is a class that |
|
422 implements the :class:`django.contrib.auth.models.User` interface, with |
|
423 these differences: |
|
424 |
|
425 * :attr:`~django.contrib.auth.models.User.id` is always ``None``. |
|
426 * :attr:`~django.contrib.auth.models.User.is_staff` and |
|
427 :attr:`~django.contrib.auth.models.User.is_superuser` are always |
|
428 ``False``. |
|
429 * :attr:`~django.contrib.auth.models.User.is_active` is always ``False``. |
|
430 * :attr:`~django.contrib.auth.models.User.groups` and |
|
431 :attr:`~django.contrib.auth.models.User.user_permissions` are always |
|
432 empty. |
|
433 * :meth:`~django.contrib.auth.models.User.is_anonymous()` returns ``True`` |
|
434 instead of ``False``. |
|
435 * :meth:`~django.contrib.auth.models.User.is_authenticated()` returns |
|
436 ``False`` instead of ``True``. |
|
437 * :meth:`~django.contrib.auth.models.User.set_password()`, |
|
438 :meth:`~django.contrib.auth.models.User.check_password()`, |
|
439 :meth:`~django.contrib.auth.models.User.save()`, |
|
440 :meth:`~django.contrib.auth.models.User.delete()`, |
|
441 :meth:`~django.contrib.auth.models.User.set_groups()` and |
|
442 :meth:`~django.contrib.auth.models.User.set_permissions()` raise |
|
443 :exc:`NotImplementedError`. |
|
444 |
|
445 In practice, you probably won't need to use |
|
446 :class:`~django.contrib.auth.models.AnonymousUser` objects on your own, but |
|
447 they're used by Web requests, as explained in the next section. |
|
448 |
|
449 .. _topics-auth-creating-superusers: |
|
450 |
|
451 Creating superusers |
|
452 ------------------- |
|
453 |
|
454 .. versionadded:: 1.0 |
|
455 The ``manage.py createsuperuser`` command is new. |
|
456 |
|
457 :djadmin:`manage.py syncdb <syncdb>` prompts you to create a superuser the |
|
458 first time you run it after adding ``'django.contrib.auth'`` to your |
|
459 :setting:`INSTALLED_APPS`. If you need to create a superuser at a later date, |
|
460 you can use a command line utility:: |
|
461 |
|
462 manage.py createsuperuser --username=joe --email=joe@example.com |
|
463 |
|
464 You will be prompted for a password. After you enter one, the user will be |
|
465 created immediately. If you leave off the :djadminopt:`--username` or the |
|
466 :djadminopt:`--email` options, it will prompt you for those values. |
|
467 |
|
468 If you're using an older release of Django, the old way of creating a superuser |
|
469 on the command line still works:: |
|
470 |
|
471 python /path/to/django/contrib/auth/create_superuser.py |
|
472 |
|
473 ...where :file:`/path/to` is the path to the Django codebase on your |
|
474 filesystem. The ``manage.py`` command is preferred because it figures out the |
|
475 correct path and environment for you. |
|
476 |
|
477 .. _auth-profiles: |
|
478 |
|
479 Storing additional information about users |
|
480 ------------------------------------------ |
|
481 |
|
482 If you'd like to store additional information related to your users, Django |
|
483 provides a method to specify a site-specific related model -- termed a "user |
|
484 profile" -- for this purpose. |
|
485 |
|
486 To make use of this feature, define a model with fields for the |
|
487 additional information you'd like to store, or additional methods |
|
488 you'd like to have available, and also add a |
|
489 :class:`~django.db.models.Field.OneToOneField` from your model to the |
|
490 :class:`~django.contrib.auth.models.User` model. This will ensure only |
|
491 one instance of your model can be created for each |
|
492 :class:`~django.contrib.auth.models.User`. |
|
493 |
|
494 To indicate that this model is the user profile model for a given site, fill in |
|
495 the setting :setting:`AUTH_PROFILE_MODULE` with a string consisting of the |
|
496 following items, separated by a dot: |
|
497 |
|
498 1. The name of the application (case sensitive) in which the user |
|
499 profile model is defined (in other words, the |
|
500 name which was passed to :djadmin:`manage.py startapp <startapp>` to create |
|
501 the application). |
|
502 |
|
503 2. The name of the model (not case sensitive) class. |
|
504 |
|
505 For example, if the profile model was a class named ``UserProfile`` and was |
|
506 defined inside an application named ``accounts``, the appropriate setting would |
|
507 be:: |
|
508 |
|
509 AUTH_PROFILE_MODULE = 'accounts.UserProfile' |
|
510 |
|
511 When a user profile model has been defined and specified in this manner, each |
|
512 :class:`~django.contrib.auth.models.User` object will have a method -- |
|
513 :class:`~django.contrib.auth.models.User.get_profile()` -- which returns the |
|
514 instance of the user profile model associated with that |
|
515 :class:`~django.contrib.auth.models.User`. |
|
516 |
|
517 The method :class:`~django.contrib.auth.models.User.get_profile()` |
|
518 does not create the profile, if it does not exist. You need to |
|
519 register a handler for the signal |
|
520 :attr:`django.db.models.signals.post_save` on the User model, and, in |
|
521 the handler, if created=True, create the associated user profile. |
|
522 |
|
523 For more information, see `Chapter 12 of the Django book`_. |
|
524 |
|
525 .. _Chapter 12 of the Django book: http://www.djangobook.com/en/1.0/chapter12/#cn222 |
|
526 |
|
527 Authentication in Web requests |
|
528 ============================== |
|
529 |
|
530 Until now, this document has dealt with the low-level APIs for manipulating |
|
531 authentication-related objects. On a higher level, Django can hook this |
|
532 authentication framework into its system of |
|
533 :class:`request objects <django.http.HttpRequest>`. |
|
534 |
|
535 First, install the |
|
536 :class:`~django.contrib.sessions.middleware.SessionMiddleware` and |
|
537 :class:`~django.contrib.auth.middleware.AuthenticationMiddleware` |
|
538 middlewares by adding them to your :setting:`MIDDLEWARE_CLASSES` setting. See |
|
539 the :doc:`session documentation </topics/http/sessions>` for more information. |
|
540 |
|
541 Once you have those middlewares installed, you'll be able to access |
|
542 :attr:`request.user <django.http.HttpRequest.user>` in views. |
|
543 :attr:`request.user <django.http.HttpRequest.user>` will give you a |
|
544 :class:`~django.contrib.auth.models.User` object representing the currently |
|
545 logged-in user. If a user isn't currently logged in, |
|
546 :attr:`request.user <django.http.HttpRequest.user>` will be set to an instance |
|
547 of :class:`~django.contrib.auth.models.AnonymousUser` (see the previous |
|
548 section). You can tell them apart with |
|
549 :meth:`~django.contrib.auth.models.User.is_authenticated()`, like so:: |
|
550 |
|
551 if request.user.is_authenticated(): |
|
552 # Do something for authenticated users. |
|
553 else: |
|
554 # Do something for anonymous users. |
|
555 |
|
556 .. _how-to-log-a-user-in: |
|
557 |
|
558 How to log a user in |
|
559 -------------------- |
|
560 |
|
561 Django provides two functions in :mod:`django.contrib.auth`: |
|
562 :func:`~django.contrib.auth.authenticate()` and |
|
563 :func:`~django.contrib.auth.login()`. |
|
564 |
|
565 .. function:: authenticate() |
|
566 |
|
567 To authenticate a given username and password, use |
|
568 :func:`~django.contrib.auth.authenticate()`. It takes two keyword |
|
569 arguments, ``username`` and ``password``, and it returns a |
|
570 :class:`~django.contrib.auth.models.User` object if the password is valid |
|
571 for the given username. If the password is invalid, |
|
572 :func:`~django.contrib.auth.authenticate()` returns ``None``. Example:: |
|
573 |
|
574 from django.contrib.auth import authenticate |
|
575 user = authenticate(username='john', password='secret') |
|
576 if user is not None: |
|
577 if user.is_active: |
|
578 print "You provided a correct username and password!" |
|
579 else: |
|
580 print "Your account has been disabled!" |
|
581 else: |
|
582 print "Your username and password were incorrect." |
|
583 |
|
584 .. function:: login() |
|
585 |
|
586 To log a user in, in a view, use :func:`~django.contrib.auth.login()`. It |
|
587 takes an :class:`~django.http.HttpRequest` object and a |
|
588 :class:`~django.contrib.auth.models.User` object. |
|
589 :func:`~django.contrib.auth.login()` saves the user's ID in the session, |
|
590 using Django's session framework, so, as mentioned above, you'll need to |
|
591 make sure to have the session middleware installed. |
|
592 |
|
593 This example shows how you might use both |
|
594 :func:`~django.contrib.auth.authenticate()` and |
|
595 :func:`~django.contrib.auth.login()`:: |
|
596 |
|
597 from django.contrib.auth import authenticate, login |
|
598 |
|
599 def my_view(request): |
|
600 username = request.POST['username'] |
|
601 password = request.POST['password'] |
|
602 user = authenticate(username=username, password=password) |
|
603 if user is not None: |
|
604 if user.is_active: |
|
605 login(request, user) |
|
606 # Redirect to a success page. |
|
607 else: |
|
608 # Return a 'disabled account' error message |
|
609 else: |
|
610 # Return an 'invalid login' error message. |
|
611 |
|
612 .. admonition:: Calling ``authenticate()`` first |
|
613 |
|
614 When you're manually logging a user in, you *must* call |
|
615 :func:`~django.contrib.auth.authenticate()` before you call |
|
616 :func:`~django.contrib.auth.login()`. |
|
617 :func:`~django.contrib.auth.authenticate()` |
|
618 sets an attribute on the :class:`~django.contrib.auth.models.User` noting |
|
619 which authentication backend successfully authenticated that user (see the |
|
620 `backends documentation`_ for details), and this information is needed |
|
621 later during the login process. |
|
622 |
|
623 .. _backends documentation: #other-authentication-sources |
|
624 |
|
625 Manually checking a user's password |
|
626 ----------------------------------- |
|
627 |
|
628 .. function:: check_password() |
|
629 |
|
630 If you'd like to manually authenticate a user by comparing a plain-text |
|
631 password to the hashed password in the database, use the convenience |
|
632 function :func:`django.contrib.auth.models.check_password`. It takes two |
|
633 arguments: the plain-text password to check, and the full value of a user's |
|
634 ``password`` field in the database to check against, and returns ``True`` |
|
635 if they match, ``False`` otherwise. |
|
636 |
|
637 How to log a user out |
|
638 --------------------- |
|
639 |
|
640 .. function:: logout() |
|
641 |
|
642 To log out a user who has been logged in via |
|
643 :func:`django.contrib.auth.login()`, use |
|
644 :func:`django.contrib.auth.logout()` within your view. It takes an |
|
645 :class:`~django.http.HttpRequest` object and has no return value. |
|
646 Example:: |
|
647 |
|
648 from django.contrib.auth import logout |
|
649 |
|
650 def logout_view(request): |
|
651 logout(request) |
|
652 # Redirect to a success page. |
|
653 |
|
654 Note that :func:`~django.contrib.auth.logout()` doesn't throw any errors if |
|
655 the user wasn't logged in. |
|
656 |
|
657 .. versionchanged:: 1.0 |
|
658 Calling ``logout()`` now cleans session data. |
|
659 |
|
660 When you call :func:`~django.contrib.auth.logout()`, the session data for |
|
661 the current request is completely cleaned out. All existing data is |
|
662 removed. This is to prevent another person from using the same Web browser |
|
663 to log in and have access to the previous user's session data. If you want |
|
664 to put anything into the session that will be available to the user |
|
665 immediately after logging out, do that *after* calling |
|
666 :func:`django.contrib.auth.logout()`. |
|
667 |
|
668 Limiting access to logged-in users |
|
669 ---------------------------------- |
|
670 |
|
671 The raw way |
|
672 ~~~~~~~~~~~ |
|
673 |
|
674 The simple, raw way to limit access to pages is to check |
|
675 :meth:`request.user.is_authenticated() |
|
676 <django.contrib.auth.models.User.is_authenticated()>` and either redirect to a |
|
677 login page:: |
|
678 |
|
679 from django.http import HttpResponseRedirect |
|
680 |
|
681 def my_view(request): |
|
682 if not request.user.is_authenticated(): |
|
683 return HttpResponseRedirect('/login/?next=%s' % request.path) |
|
684 # ... |
|
685 |
|
686 ...or display an error message:: |
|
687 |
|
688 def my_view(request): |
|
689 if not request.user.is_authenticated(): |
|
690 return render_to_response('myapp/login_error.html') |
|
691 # ... |
|
692 |
|
693 The login_required decorator |
|
694 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ |
|
695 |
|
696 .. function:: decorators.login_required([redirect_field_name=REDIRECT_FIELD_NAME]) |
|
697 |
|
698 As a shortcut, you can use the convenient |
|
699 :func:`~django.contrib.auth.decorators.login_required` decorator:: |
|
700 |
|
701 from django.contrib.auth.decorators import login_required |
|
702 |
|
703 @login_required |
|
704 def my_view(request): |
|
705 ... |
|
706 |
|
707 :func:`~django.contrib.auth.decorators.login_required` does the following: |
|
708 |
|
709 * If the user isn't logged in, redirect to |
|
710 :setting:`settings.LOGIN_URL <LOGIN_URL>`, passing the current absolute |
|
711 path in the query string. Example: ``/accounts/login/?next=/polls/3/``. |
|
712 |
|
713 * If the user is logged in, execute the view normally. The view code is |
|
714 free to assume the user is logged in. |
|
715 |
|
716 By default, the path that the user should be redirected to upon |
|
717 successful authentication is stored in a query string parameter called |
|
718 ``"next"``. If you would prefer to use a different name for this parameter, |
|
719 :func:`~django.contrib.auth.decorators.login_required` takes an |
|
720 optional ``redirect_field_name`` parameter:: |
|
721 |
|
722 from django.contrib.auth.decorators import login_required |
|
723 |
|
724 @login_required(redirect_field_name='my_redirect_field') |
|
725 def my_view(request): |
|
726 ... |
|
727 |
|
728 If you provide a value to ``redirect_field_name``, you will most |
|
729 likely need to customize your login template as well, since the template |
|
730 context variable which stores the redirect path will use the value of |
|
731 ``redirect_field_name`` as it's key rather than ``"next"`` (the default). |
|
732 |
|
733 Note that you'll need to map the appropriate Django view to |
|
734 :setting:`settings.LOGIN_URL <LOGIN_URL>`. For example, using the defaults, |
|
735 add the following line to your URLconf:: |
|
736 |
|
737 (r'^accounts/login/$', 'django.contrib.auth.views.login'), |
|
738 |
|
739 .. function:: views.login(request, [template_name, redirect_field_name, authentication_form]) |
|
740 |
|
741 Here's what ``django.contrib.auth.views.login`` does: |
|
742 |
|
743 * If called via ``GET``, it displays a login form that POSTs to the |
|
744 same URL. More on this in a bit. |
|
745 |
|
746 * If called via ``POST``, it tries to log the user in. If login is |
|
747 successful, the view redirects to the URL specified in ``next``. If |
|
748 ``next`` isn't provided, it redirects to |
|
749 :setting:`settings.LOGIN_REDIRECT_URL <LOGIN_REDIRECT_URL>` (which |
|
750 defaults to ``/accounts/profile/``). If login isn't successful, it |
|
751 redisplays the login form. |
|
752 |
|
753 It's your responsibility to provide the login form in a template called |
|
754 ``registration/login.html`` by default. This template gets passed four |
|
755 template context variables: |
|
756 |
|
757 * ``form``: A :class:`~django.forms.Form` object representing the login |
|
758 form. See the :doc:`forms documentation </topics/forms/index>` for |
|
759 more on ``Form`` objects. |
|
760 |
|
761 * ``next``: The URL to redirect to after successful login. This may |
|
762 contain a query string, too. |
|
763 |
|
764 * ``site``: The current :class:`~django.contrib.sites.models.Site`, |
|
765 according to the :setting:`SITE_ID` setting. If you don't have the |
|
766 site framework installed, this will be set to an instance of |
|
767 :class:`~django.contrib.sites.models.RequestSite`, which derives the |
|
768 site name and domain from the current |
|
769 :class:`~django.http.HttpRequest`. |
|
770 |
|
771 * ``site_name``: An alias for ``site.name``. If you don't have the site |
|
772 framework installed, this will be set to the value of |
|
773 :attr:`request.META['SERVER_NAME'] <django.http.HttpRequest.META>`. |
|
774 For more on sites, see :doc:`/ref/contrib/sites`. |
|
775 |
|
776 If you'd prefer not to call the template :file:`registration/login.html`, |
|
777 you can pass the ``template_name`` parameter via the extra arguments to |
|
778 the view in your URLconf. For example, this URLconf line would use |
|
779 :file:`myapp/login.html` instead:: |
|
780 |
|
781 (r'^accounts/login/$', 'django.contrib.auth.views.login', {'template_name': 'myapp/login.html'}), |
|
782 |
|
783 You can also specify the name of the ``GET`` field which contains the URL |
|
784 to redirect to after login by passing ``redirect_field_name`` to the view. |
|
785 By default, the field is called ``next``. |
|
786 |
|
787 Here's a sample :file:`registration/login.html` template you can use as a |
|
788 starting point. It assumes you have a :file:`base.html` template that |
|
789 defines a ``content`` block: |
|
790 |
|
791 .. code-block:: html+django |
|
792 |
|
793 {% extends "base.html" %} |
|
794 |
|
795 {% block content %} |
|
796 |
|
797 {% if form.errors %} |
|
798 <p>Your username and password didn't match. Please try again.</p> |
|
799 {% endif %} |
|
800 |
|
801 <form method="post" action="{% url django.contrib.auth.views.login %}"> |
|
802 {% csrf_token %} |
|
803 <table> |
|
804 <tr> |
|
805 <td>{{ form.username.label_tag }}</td> |
|
806 <td>{{ form.username }}</td> |
|
807 </tr> |
|
808 <tr> |
|
809 <td>{{ form.password.label_tag }}</td> |
|
810 <td>{{ form.password }}</td> |
|
811 </tr> |
|
812 </table> |
|
813 |
|
814 <input type="submit" value="login" /> |
|
815 <input type="hidden" name="next" value="{{ next }}" /> |
|
816 </form> |
|
817 |
|
818 {% endblock %} |
|
819 |
|
820 .. versionadded:: 1.2 |
|
821 |
|
822 If you are using alternate authentication (see |
|
823 :ref:`authentication-backends`) you can pass a custom authentication form |
|
824 to the login view via the ``authentication_form`` parameter. This form must |
|
825 accept a ``request`` keyword argument in its ``__init__`` method, and |
|
826 provide a ``get_user`` method which returns the authenticated user object |
|
827 (this method is only ever called after successful form validation). |
|
828 |
|
829 .. _forms documentation: ../forms/ |
|
830 .. _site framework docs: ../sites/ |
|
831 |
|
832 Other built-in views |
|
833 -------------------- |
|
834 |
|
835 In addition to the :func:`~views.login` view, the authentication system |
|
836 includes a few other useful built-in views located in |
|
837 :mod:`django.contrib.auth.views`: |
|
838 |
|
839 .. function:: views.logout(request, [next_page, template_name, redirect_field_name]) |
|
840 |
|
841 Logs a user out. |
|
842 |
|
843 **Optional arguments:** |
|
844 |
|
845 * ``next_page``: The URL to redirect to after logout. |
|
846 |
|
847 * ``template_name``: The full name of a template to display after |
|
848 logging the user out. This will default to |
|
849 :file:`registration/logged_out.html` if no argument is supplied. |
|
850 |
|
851 * ``redirect_field_name``: The name of a ``GET`` field containing the |
|
852 URL to redirect to after log out. Overrides ``next_page`` if the given |
|
853 ``GET`` parameter is passed. |
|
854 |
|
855 **Template context:** |
|
856 |
|
857 * ``title``: The string "Logged out", localized. |
|
858 |
|
859 .. function:: views.logout_then_login(request[, login_url]) |
|
860 |
|
861 Logs a user out, then redirects to the login page. |
|
862 |
|
863 **Optional arguments:** |
|
864 |
|
865 * ``login_url``: The URL of the login page to redirect to. This will |
|
866 default to :setting:`settings.LOGIN_URL <LOGIN_URL>` if not supplied. |
|
867 |
|
868 .. function:: views.password_change(request[, template_name, post_change_redirect, password_change_form]) |
|
869 |
|
870 Allows a user to change their password. |
|
871 |
|
872 **Optional arguments:** |
|
873 |
|
874 * ``template_name``: The full name of a template to use for |
|
875 displaying the password change form. This will default to |
|
876 :file:`registration/password_change_form.html` if not supplied. |
|
877 |
|
878 * ``post_change_redirect``: The URL to redirect to after a successful |
|
879 password change. |
|
880 |
|
881 * .. versionadded:: 1.2 |
|
882 |
|
883 ``password_change_form``: A custom "change password" form which must |
|
884 accept a ``user`` keyword argument. The form is responsible for |
|
885 actually changing the user's password. |
|
886 |
|
887 |
|
888 **Template context:** |
|
889 |
|
890 * ``form``: The password change form. |
|
891 |
|
892 .. function:: views.password_change_done(request[, template_name]) |
|
893 |
|
894 The page shown after a user has changed their password. |
|
895 |
|
896 **Optional arguments:** |
|
897 |
|
898 * ``template_name``: The full name of a template to use. This will |
|
899 default to :file:`registration/password_change_done.html` if not |
|
900 supplied. |
|
901 |
|
902 .. function:: views.password_reset(request[, is_admin_site, template_name, email_template_name, password_reset_form, token_generator, post_reset_redirect]) |
|
903 |
|
904 Allows a user to reset their password by generating a one-time use link |
|
905 that can be used to reset the password, and sending that link to the |
|
906 user's registered e-mail address. |
|
907 |
|
908 **Optional arguments:** |
|
909 |
|
910 * ``template_name``: The full name of a template to use for |
|
911 displaying the password reset form. This will default to |
|
912 :file:`registration/password_reset_form.html` if not supplied. |
|
913 |
|
914 * ``email_template_name``: The full name of a template to use for |
|
915 generating the e-mail with the new password. This will default to |
|
916 :file:`registration/password_reset_email.html` if not supplied. |
|
917 |
|
918 * ``password_reset_form``: Form that will be used to set the password. |
|
919 Defaults to :class:`~django.contrib.auth.forms.PasswordResetForm`. |
|
920 |
|
921 * ``token_generator``: Instance of the class to check the password. This |
|
922 will default to ``default_token_generator``, it's an instance of |
|
923 ``django.contrib.auth.tokens.PasswordResetTokenGenerator``. |
|
924 |
|
925 * ``post_reset_redirect``: The URL to redirect to after a successful |
|
926 password change. |
|
927 |
|
928 **Template context:** |
|
929 |
|
930 * ``form``: The form for resetting the user's password. |
|
931 |
|
932 .. function:: views.password_reset_done(request[, template_name]) |
|
933 |
|
934 The page shown after a user has reset their password. |
|
935 |
|
936 **Optional arguments:** |
|
937 |
|
938 * ``template_name``: The full name of a template to use. This will |
|
939 default to :file:`registration/password_reset_done.html` if not |
|
940 supplied. |
|
941 |
|
942 .. function:: views.redirect_to_login(next[, login_url, redirect_field_name]) |
|
943 |
|
944 Redirects to the login page, and then back to another URL after a |
|
945 successful login. |
|
946 |
|
947 **Required arguments:** |
|
948 |
|
949 * ``next``: The URL to redirect to after a successful login. |
|
950 |
|
951 **Optional arguments:** |
|
952 |
|
953 * ``login_url``: The URL of the login page to redirect to. This will |
|
954 default to :setting:`settings.LOGIN_URL <LOGIN_URL>` if not supplied. |
|
955 |
|
956 * ``redirect_field_name``: The name of a ``GET`` field containing the |
|
957 URL to redirect to after log out. Overrides ``next`` if the given |
|
958 ``GET`` parameter is passed. |
|
959 |
|
960 .. function:: password_reset_confirm(request[, uidb36, token, template_name, token_generator, set_password_form, post_reset_redirect]) |
|
961 |
|
962 Presents a form for entering a new password. |
|
963 |
|
964 **Optional arguments:** |
|
965 |
|
966 * ``uidb36``: The user's id encoded in base 36. This will default to |
|
967 ``None``. |
|
968 * ``token``: Token to check that the password is valid. This will default to ``None``. |
|
969 * ``template_name``: The full name of a template to display the confirm |
|
970 password view. Default value is :file:`registration/password_reset_confirm.html`. |
|
971 * ``token_generator``: Instance of the class to check the password. This |
|
972 will default to ``default_token_generator``, it's an instance of |
|
973 ``django.contrib.auth.tokens.PasswordResetTokenGenerator``. |
|
974 * ``set_password_form``: Form that will be used to set the password. |
|
975 This will default to ``SetPasswordForm``. |
|
976 * ``post_reset_redirect``: URL to redirect after the password reset |
|
977 done. This will default to ``None``. |
|
978 |
|
979 .. function:: password_reset_complete(request[,template_name]) |
|
980 |
|
981 Presents a view which informs the user that the password has been |
|
982 successfully changed. |
|
983 |
|
984 **Optional arguments:** |
|
985 |
|
986 * ``template_name``: The full name of a template to display the view. |
|
987 This will default to :file:`registration/password_reset_complete.html`. |
|
988 |
|
989 Built-in forms |
|
990 -------------- |
|
991 |
|
992 .. module:: django.contrib.auth.forms |
|
993 |
|
994 If you don't want to use the built-in views, but want the convenience of not |
|
995 having to write forms for this functionality, the authentication system |
|
996 provides several built-in forms located in :mod:`django.contrib.auth.forms`: |
|
997 |
|
998 .. class:: AdminPasswordChangeForm |
|
999 |
|
1000 A form used in the admin interface to change a user's password. |
|
1001 |
|
1002 .. class:: AuthenticationForm |
|
1003 |
|
1004 A form for logging a user in. |
|
1005 |
|
1006 .. class:: PasswordChangeForm |
|
1007 |
|
1008 A form for allowing a user to change their password. |
|
1009 |
|
1010 .. class:: PasswordResetForm |
|
1011 |
|
1012 A form for generating and e-mailing a one-time use link to reset a |
|
1013 user's password. |
|
1014 |
|
1015 .. class:: SetPasswordForm |
|
1016 |
|
1017 A form that lets a user change his/her password without entering the old |
|
1018 password. |
|
1019 |
|
1020 .. class:: UserChangeForm |
|
1021 |
|
1022 A form used in the admin interface to change a user's information and |
|
1023 permissions. |
|
1024 |
|
1025 .. class:: UserCreationForm |
|
1026 |
|
1027 A form for creating a new user. |
|
1028 |
|
1029 Limiting access to logged-in users that pass a test |
|
1030 --------------------------------------------------- |
|
1031 |
|
1032 .. currentmodule:: django.contrib.auth |
|
1033 |
|
1034 To limit access based on certain permissions or some other test, you'd do |
|
1035 essentially the same thing as described in the previous section. |
|
1036 |
|
1037 The simple way is to run your test on :attr:`request.user |
|
1038 <django.http.HttpRequest.user>` in the view directly. For example, this view |
|
1039 checks to make sure the user is logged in and has the permission |
|
1040 ``polls.can_vote``:: |
|
1041 |
|
1042 def my_view(request): |
|
1043 if not request.user.has_perm('polls.can_vote'): |
|
1044 return HttpResponse("You can't vote in this poll.") |
|
1045 # ... |
|
1046 |
|
1047 .. function:: decorators.user_passes_test() |
|
1048 |
|
1049 As a shortcut, you can use the convenient ``user_passes_test`` decorator:: |
|
1050 |
|
1051 from django.contrib.auth.decorators import user_passes_test |
|
1052 |
|
1053 @user_passes_test(lambda u: u.has_perm('polls.can_vote')) |
|
1054 def my_view(request): |
|
1055 ... |
|
1056 |
|
1057 We're using this particular test as a relatively simple example. However, |
|
1058 if you just want to test whether a permission is available to a user, you |
|
1059 can use the :func:`~django.contrib.auth.decorators.permission_required()` |
|
1060 decorator, described later in this document. |
|
1061 |
|
1062 :func:`~django.contrib.auth.decorators.user_passes_test` takes a required |
|
1063 argument: a callable that takes a |
|
1064 :class:`~django.contrib.auth.models.User` object and returns ``True`` if |
|
1065 the user is allowed to view the page. Note that |
|
1066 :func:`~django.contrib.auth.decorators.user_passes_test` does not |
|
1067 automatically check that the :class:`~django.contrib.auth.models.User` is |
|
1068 not anonymous. |
|
1069 |
|
1070 :func:`~django.contrib.auth.decorators.user_passes_test()` takes an |
|
1071 optional ``login_url`` argument, which lets you specify the URL for your |
|
1072 login page (:setting:`settings.LOGIN_URL <LOGIN_URL>` by default). |
|
1073 |
|
1074 For example:: |
|
1075 |
|
1076 from django.contrib.auth.decorators import user_passes_test |
|
1077 |
|
1078 @user_passes_test(lambda u: u.has_perm('polls.can_vote'), login_url='/login/') |
|
1079 def my_view(request): |
|
1080 ... |
|
1081 |
|
1082 The permission_required decorator |
|
1083 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ |
|
1084 |
|
1085 .. function:: decorators.permission_required() |
|
1086 |
|
1087 It's a relatively common task to check whether a user has a particular |
|
1088 permission. For that reason, Django provides a shortcut for that case: the |
|
1089 :func:`~django.contrib.auth.decorators.permission_required()` decorator. |
|
1090 Using this decorator, the earlier example can be written as:: |
|
1091 |
|
1092 from django.contrib.auth.decorators import permission_required |
|
1093 |
|
1094 @permission_required('polls.can_vote') |
|
1095 def my_view(request): |
|
1096 ... |
|
1097 |
|
1098 As for the :meth:`User.has_perm` method, permission names take the form |
|
1099 ``"<app label>.<permission codename>"`` (i.e. ``polls.can_vote`` for a |
|
1100 permission on a model in the ``polls`` application). |
|
1101 |
|
1102 Note that :func:`~django.contrib.auth.decorators.permission_required()` |
|
1103 also takes an optional ``login_url`` parameter. Example:: |
|
1104 |
|
1105 from django.contrib.auth.decorators import permission_required |
|
1106 |
|
1107 @permission_required('polls.can_vote', login_url='/loginpage/') |
|
1108 def my_view(request): |
|
1109 ... |
|
1110 |
|
1111 As in the :func:`~decorators.login_required` decorator, ``login_url`` |
|
1112 defaults to :setting:`settings.LOGIN_URL <LOGIN_URL>`. |
|
1113 |
|
1114 Limiting access to generic views |
|
1115 -------------------------------- |
|
1116 |
|
1117 To limit access to a :doc:`generic view </ref/generic-views>`, write a thin |
|
1118 wrapper around the view, and point your URLconf to your wrapper instead of the |
|
1119 generic view itself. For example:: |
|
1120 |
|
1121 from django.views.generic.date_based import object_detail |
|
1122 |
|
1123 @login_required |
|
1124 def limited_object_detail(*args, **kwargs): |
|
1125 return object_detail(*args, **kwargs) |
|
1126 |
|
1127 .. _permissions: |
|
1128 |
|
1129 Permissions |
|
1130 =========== |
|
1131 |
|
1132 Django comes with a simple permissions system. It provides a way to assign |
|
1133 permissions to specific users and groups of users. |
|
1134 |
|
1135 It's used by the Django admin site, but you're welcome to use it in your own |
|
1136 code. |
|
1137 |
|
1138 The Django admin site uses permissions as follows: |
|
1139 |
|
1140 * Access to view the "add" form and add an object is limited to users with |
|
1141 the "add" permission for that type of object. |
|
1142 * Access to view the change list, view the "change" form and change an |
|
1143 object is limited to users with the "change" permission for that type of |
|
1144 object. |
|
1145 * Access to delete an object is limited to users with the "delete" |
|
1146 permission for that type of object. |
|
1147 |
|
1148 Permissions are set globally per type of object, not per specific object |
|
1149 instance. For example, it's possible to say "Mary may change news stories," but |
|
1150 it's not currently possible to say "Mary may change news stories, but only the |
|
1151 ones she created herself" or "Mary may only change news stories that have a |
|
1152 certain status, publication date or ID." The latter functionality is something |
|
1153 Django developers are currently discussing. |
|
1154 |
|
1155 Default permissions |
|
1156 ------------------- |
|
1157 |
|
1158 When ``django.contrib.auth`` is listed in your :setting:`INSTALLED_APPS` |
|
1159 setting, it will ensure that three default permissions -- add, change and |
|
1160 delete -- are created for each Django model defined in one of your installed |
|
1161 applications. |
|
1162 |
|
1163 These permissions will be created when you run :djadmin:`manage.py syncdb |
|
1164 <syncdb>`; the first time you run ``syncdb`` after adding |
|
1165 ``django.contrib.auth`` to :setting:`INSTALLED_APPS`, the default permissions |
|
1166 will be created for all previously-installed models, as well as for any new |
|
1167 models being installed at that time. Afterward, it will create default |
|
1168 permissions for new models each time you run :djadmin:`manage.py syncdb |
|
1169 <syncdb>`. |
|
1170 |
|
1171 Assuming you have an application with an |
|
1172 :attr:`~django.db.models.Options.app_label` ``foo`` and a model named ``Bar``, |
|
1173 to test for basic permissions you should use: |
|
1174 |
|
1175 * add: ``user.has_perm('foo.add_bar')`` |
|
1176 * change: ``user.has_perm('foo.change_bar')`` |
|
1177 * delete: ``user.has_perm('foo.delete_bar')`` |
|
1178 |
|
1179 .. _custom-permissions: |
|
1180 |
|
1181 Custom permissions |
|
1182 ------------------ |
|
1183 |
|
1184 To create custom permissions for a given model object, use the ``permissions`` |
|
1185 :ref:`model Meta attribute <meta-options>`. |
|
1186 |
|
1187 This example Task model creates three custom permissions, i.e., actions users |
|
1188 can or cannot do with Task instances, specific to your appication:: |
|
1189 |
|
1190 class Task(models.Model): |
|
1191 ... |
|
1192 class Meta: |
|
1193 permissions = ( |
|
1194 ("can_view", "Can see available tasks"), |
|
1195 ("can_change_status", "Can change the status of tasks"), |
|
1196 ("can_close", "Can remove a task by setting its status as closed"), |
|
1197 ) |
|
1198 |
|
1199 The only thing this does is create those extra permissions when you run |
|
1200 :djadmin:`manage.py syncdb <syncdb>`. Your code is in charge of checking the |
|
1201 value of these permissions when an user is trying to access the functionality |
|
1202 provided by the application (viewing tasks, changing the status of tasks, |
|
1203 closing tasks.) |
|
1204 |
|
1205 API reference |
|
1206 ------------- |
|
1207 |
|
1208 .. class:: models.Permission |
|
1209 |
|
1210 Just like users, permissions are implemented in a Django model that lives |
|
1211 in `django/contrib/auth/models.py`_. |
|
1212 |
|
1213 .. _django/contrib/auth/models.py: http://code.djangoproject.com/browser/django/trunk/django/contrib/auth/models.py |
|
1214 |
|
1215 Fields |
|
1216 ~~~~~~ |
|
1217 |
|
1218 :class:`~django.contrib.auth.models.Permission` objects have the following |
|
1219 fields: |
|
1220 |
|
1221 .. attribute:: models.Permission.name |
|
1222 |
|
1223 Required. 50 characters or fewer. Example: ``'Can vote'``. |
|
1224 |
|
1225 .. attribute:: models.Permission.content_type |
|
1226 |
|
1227 Required. A reference to the ``django_content_type`` database table, which |
|
1228 contains a record for each installed Django model. |
|
1229 |
|
1230 .. attribute:: models.Permission.codename |
|
1231 |
|
1232 Required. 100 characters or fewer. Example: ``'can_vote'``. |
|
1233 |
|
1234 Methods |
|
1235 ~~~~~~~ |
|
1236 |
|
1237 :class:`~django.contrib.auth.models.Permission` objects have the standard |
|
1238 data-access methods like any other :doc:`Django model </ref/models/instances>`. |
|
1239 |
|
1240 Authentication data in templates |
|
1241 ================================ |
|
1242 |
|
1243 The currently logged-in user and his/her permissions are made available in the |
|
1244 :doc:`template context </ref/templates/api>` when you use |
|
1245 :class:`~django.template.context.RequestContext`. |
|
1246 |
|
1247 .. admonition:: Technicality |
|
1248 |
|
1249 Technically, these variables are only made available in the template context |
|
1250 if you use :class:`~django.template.context.RequestContext` *and* your |
|
1251 :setting:`TEMPLATE_CONTEXT_PROCESSORS` setting contains |
|
1252 ``"django.contrib.auth.context_processors.auth"``, which is default. For |
|
1253 more, see the :ref:`RequestContext docs <subclassing-context-requestcontext>`. |
|
1254 |
|
1255 Users |
|
1256 ----- |
|
1257 |
|
1258 When rendering a template :class:`~django.template.context.RequestContext`, the |
|
1259 currently logged-in user, either a :class:`~django.contrib.auth.models.User` |
|
1260 instance or an :class:`~django.contrib.auth.models.AnonymousUser` instance, is |
|
1261 stored in the template variable ``{{ user }}``: |
|
1262 |
|
1263 .. code-block:: html+django |
|
1264 |
|
1265 {% if user.is_authenticated %} |
|
1266 <p>Welcome, {{ user.username }}. Thanks for logging in.</p> |
|
1267 {% else %} |
|
1268 <p>Welcome, new user. Please log in.</p> |
|
1269 {% endif %} |
|
1270 |
|
1271 This template context variable is not available if a ``RequestContext`` is not |
|
1272 being used. |
|
1273 |
|
1274 Permissions |
|
1275 ----------- |
|
1276 |
|
1277 The currently logged-in user's permissions are stored in the template variable |
|
1278 ``{{ perms }}``. This is an instance of |
|
1279 :class:`django.core.context_processors.PermWrapper`, which is a |
|
1280 template-friendly proxy of permissions. |
|
1281 |
|
1282 In the ``{{ perms }}`` object, single-attribute lookup is a proxy to |
|
1283 :meth:`User.has_module_perms <django.contrib.auth.models.User.has_module_perms>`. |
|
1284 This example would display ``True`` if the logged-in user had any permissions |
|
1285 in the ``foo`` app:: |
|
1286 |
|
1287 {{ perms.foo }} |
|
1288 |
|
1289 Two-level-attribute lookup is a proxy to |
|
1290 :meth:`User.has_perm <django.contrib.auth.models.User.has_perm>`. This example |
|
1291 would display ``True`` if the logged-in user had the permission |
|
1292 ``foo.can_vote``:: |
|
1293 |
|
1294 {{ perms.foo.can_vote }} |
|
1295 |
|
1296 Thus, you can check permissions in template ``{% if %}`` statements: |
|
1297 |
|
1298 .. code-block:: html+django |
|
1299 |
|
1300 {% if perms.foo %} |
|
1301 <p>You have permission to do something in the foo app.</p> |
|
1302 {% if perms.foo.can_vote %} |
|
1303 <p>You can vote!</p> |
|
1304 {% endif %} |
|
1305 {% if perms.foo.can_drive %} |
|
1306 <p>You can drive!</p> |
|
1307 {% endif %} |
|
1308 {% else %} |
|
1309 <p>You don't have permission to do anything in the foo app.</p> |
|
1310 {% endif %} |
|
1311 |
|
1312 Groups |
|
1313 ====== |
|
1314 |
|
1315 Groups are a generic way of categorizing users so you can apply permissions, or |
|
1316 some other label, to those users. A user can belong to any number of groups. |
|
1317 |
|
1318 A user in a group automatically has the permissions granted to that group. For |
|
1319 example, if the group ``Site editors`` has the permission |
|
1320 ``can_edit_home_page``, any user in that group will have that permission. |
|
1321 |
|
1322 Beyond permissions, groups are a convenient way to categorize users to give |
|
1323 them some label, or extended functionality. For example, you could create a |
|
1324 group ``'Special users'``, and you could write code that could, say, give them |
|
1325 access to a members-only portion of your site, or send them members-only e-mail |
|
1326 messages. |
|
1327 |
|
1328 Messages |
|
1329 ======== |
|
1330 |
|
1331 .. deprecated:: 1.2 |
|
1332 This functionality will be removed in Django 1.4. You should use the |
|
1333 :doc:`messages framework </ref/contrib/messages>` for all new projects and |
|
1334 begin to update your existing code immediately. |
|
1335 |
|
1336 The message system is a lightweight way to queue messages for given users. |
|
1337 |
|
1338 A message is associated with a :class:`~django.contrib.auth.models.User`. |
|
1339 There's no concept of expiration or timestamps. |
|
1340 |
|
1341 Messages are used by the Django admin after successful actions. For example, |
|
1342 ``"The poll Foo was created successfully."`` is a message. |
|
1343 |
|
1344 The API is simple: |
|
1345 |
|
1346 .. method:: models.User.message_set.create(message) |
|
1347 |
|
1348 To create a new message, use |
|
1349 ``user_obj.message_set.create(message='message_text')``. |
|
1350 |
|
1351 To retrieve/delete messages, use |
|
1352 :meth:`user_obj.get_and_delete_messages() <django.contrib.auth.models.User.get_and_delete_messages>`, |
|
1353 which returns a list of ``Message`` objects in the user's queue (if any) |
|
1354 and deletes the messages from the queue. |
|
1355 |
|
1356 In this example view, the system saves a message for the user after creating |
|
1357 a playlist:: |
|
1358 |
|
1359 def create_playlist(request, songs): |
|
1360 # Create the playlist with the given songs. |
|
1361 # ... |
|
1362 request.user.message_set.create(message="Your playlist was added successfully.") |
|
1363 return render_to_response("playlists/create.html", |
|
1364 context_instance=RequestContext(request)) |
|
1365 |
|
1366 When you use :class:`~django.template.context.RequestContext`, the currently |
|
1367 logged-in user and his/her messages are made available in the |
|
1368 :doc:`template context </ref/templates/api>` as the template variable |
|
1369 ``{{ messages }}``. Here's an example of template code that displays messages: |
|
1370 |
|
1371 .. code-block:: html+django |
|
1372 |
|
1373 {% if messages %} |
|
1374 <ul> |
|
1375 {% for message in messages %} |
|
1376 <li>{{ message }}</li> |
|
1377 {% endfor %} |
|
1378 </ul> |
|
1379 {% endif %} |
|
1380 |
|
1381 .. versionchanged:: 1.2 |
|
1382 The ``messages`` template variable uses a backwards compatible method in the |
|
1383 :doc:`messages framework </ref/contrib/messages>` to retrieve messages from |
|
1384 both the user ``Message`` model and from the new framework. Unlike in |
|
1385 previous revisions, the messages will not be erased unless they are actually |
|
1386 displayed. |
|
1387 |
|
1388 Finally, note that this messages framework only works with users in the user |
|
1389 database. To send messages to anonymous users, use the |
|
1390 :doc:`messages framework </ref/contrib/messages>`. |
|
1391 |
|
1392 .. _authentication-backends: |
|
1393 |
|
1394 Other authentication sources |
|
1395 ============================ |
|
1396 |
|
1397 The authentication that comes with Django is good enough for most common cases, |
|
1398 but you may have the need to hook into another authentication source -- that |
|
1399 is, another source of usernames and passwords or authentication methods. |
|
1400 |
|
1401 For example, your company may already have an LDAP setup that stores a username |
|
1402 and password for every employee. It'd be a hassle for both the network |
|
1403 administrator and the users themselves if users had separate accounts in LDAP |
|
1404 and the Django-based applications. |
|
1405 |
|
1406 So, to handle situations like this, the Django authentication system lets you |
|
1407 plug in other authentication sources. You can override Django's default |
|
1408 database-based scheme, or you can use the default system in tandem with other |
|
1409 systems. |
|
1410 |
|
1411 See the :doc:`authentication backend reference </ref/authbackends>` |
|
1412 for information on the authentication backends included with Django. |
|
1413 |
|
1414 Specifying authentication backends |
|
1415 ---------------------------------- |
|
1416 |
|
1417 Behind the scenes, Django maintains a list of "authentication backends" that it |
|
1418 checks for authentication. When somebody calls |
|
1419 :func:`django.contrib.auth.authenticate()` -- as described in :ref:`How to log |
|
1420 a user in <how-to-log-a-user-in>` above -- Django tries authenticating across |
|
1421 all of its authentication backends. If the first authentication method fails, |
|
1422 Django tries the second one, and so on, until all backends have been attempted. |
|
1423 |
|
1424 The list of authentication backends to use is specified in the |
|
1425 :setting:`AUTHENTICATION_BACKENDS` setting. This should be a tuple of Python |
|
1426 path names that point to Python classes that know how to authenticate. These |
|
1427 classes can be anywhere on your Python path. |
|
1428 |
|
1429 By default, :setting:`AUTHENTICATION_BACKENDS` is set to:: |
|
1430 |
|
1431 ('django.contrib.auth.backends.ModelBackend',) |
|
1432 |
|
1433 That's the basic authentication scheme that checks the Django users database. |
|
1434 |
|
1435 The order of :setting:`AUTHENTICATION_BACKENDS` matters, so if the same |
|
1436 username and password is valid in multiple backends, Django will stop |
|
1437 processing at the first positive match. |
|
1438 |
|
1439 .. note:: |
|
1440 |
|
1441 Once a user has authenticated, Django stores which backend was used to |
|
1442 authenticate the user in the user's session, and re-uses the same backend |
|
1443 for subsequent authentication attempts for that user. This effectively means |
|
1444 that authentication sources are cached, so if you change |
|
1445 :setting:`AUTHENTICATION_BACKENDS`, you'll need to clear out session data if |
|
1446 you need to force users to re-authenticate using different methods. A simple |
|
1447 way to do that is simply to execute ``Session.objects.all().delete()``. |
|
1448 |
|
1449 Writing an authentication backend |
|
1450 --------------------------------- |
|
1451 |
|
1452 An authentication backend is a class that implements two methods: |
|
1453 ``get_user(user_id)`` and ``authenticate(**credentials)``. |
|
1454 |
|
1455 The ``get_user`` method takes a ``user_id`` -- which could be a username, |
|
1456 database ID or whatever -- and returns a ``User`` object. |
|
1457 |
|
1458 The ``authenticate`` method takes credentials as keyword arguments. Most of |
|
1459 the time, it'll just look like this:: |
|
1460 |
|
1461 class MyBackend: |
|
1462 def authenticate(self, username=None, password=None): |
|
1463 # Check the username/password and return a User. |
|
1464 |
|
1465 But it could also authenticate a token, like so:: |
|
1466 |
|
1467 class MyBackend: |
|
1468 def authenticate(self, token=None): |
|
1469 # Check the token and return a User. |
|
1470 |
|
1471 Either way, ``authenticate`` should check the credentials it gets, and it |
|
1472 should return a ``User`` object that matches those credentials, if the |
|
1473 credentials are valid. If they're not valid, it should return ``None``. |
|
1474 |
|
1475 The Django admin system is tightly coupled to the Django ``User`` object |
|
1476 described at the beginning of this document. For now, the best way to deal with |
|
1477 this is to create a Django ``User`` object for each user that exists for your |
|
1478 backend (e.g., in your LDAP directory, your external SQL database, etc.) You |
|
1479 can either write a script to do this in advance, or your ``authenticate`` |
|
1480 method can do it the first time a user logs in. |
|
1481 |
|
1482 Here's an example backend that authenticates against a username and password |
|
1483 variable defined in your ``settings.py`` file and creates a Django ``User`` |
|
1484 object the first time a user authenticates:: |
|
1485 |
|
1486 from django.conf import settings |
|
1487 from django.contrib.auth.models import User, check_password |
|
1488 |
|
1489 class SettingsBackend: |
|
1490 """ |
|
1491 Authenticate against the settings ADMIN_LOGIN and ADMIN_PASSWORD. |
|
1492 |
|
1493 Use the login name, and a hash of the password. For example: |
|
1494 |
|
1495 ADMIN_LOGIN = 'admin' |
|
1496 ADMIN_PASSWORD = 'sha1$4e987$afbcf42e21bd417fb71db8c66b321e9fc33051de' |
|
1497 """ |
|
1498 def authenticate(self, username=None, password=None): |
|
1499 login_valid = (settings.ADMIN_LOGIN == username) |
|
1500 pwd_valid = check_password(password, settings.ADMIN_PASSWORD) |
|
1501 if login_valid and pwd_valid: |
|
1502 try: |
|
1503 user = User.objects.get(username=username) |
|
1504 except User.DoesNotExist: |
|
1505 # Create a new user. Note that we can set password |
|
1506 # to anything, because it won't be checked; the password |
|
1507 # from settings.py will. |
|
1508 user = User(username=username, password='get from settings.py') |
|
1509 user.is_staff = True |
|
1510 user.is_superuser = True |
|
1511 user.save() |
|
1512 return user |
|
1513 return None |
|
1514 |
|
1515 def get_user(self, user_id): |
|
1516 try: |
|
1517 return User.objects.get(pk=user_id) |
|
1518 except User.DoesNotExist: |
|
1519 return None |
|
1520 |
|
1521 Handling authorization in custom backends |
|
1522 ----------------------------------------- |
|
1523 |
|
1524 Custom auth backends can provide their own permissions. |
|
1525 |
|
1526 The user model will delegate permission lookup functions |
|
1527 (:meth:`~django.contrib.auth.models.User.get_group_permissions()`, |
|
1528 :meth:`~django.contrib.auth.models.User.get_all_permissions()`, |
|
1529 :meth:`~django.contrib.auth.models.User.has_perm()`, and |
|
1530 :meth:`~django.contrib.auth.models.User.has_module_perms()`) to any |
|
1531 authentication backend that implements these functions. |
|
1532 |
|
1533 The permissions given to the user will be the superset of all permissions |
|
1534 returned by all backends. That is, Django grants a permission to a user that |
|
1535 any one backend grants. |
|
1536 |
|
1537 The simple backend above could implement permissions for the magic admin |
|
1538 fairly simply:: |
|
1539 |
|
1540 class SettingsBackend: |
|
1541 |
|
1542 # ... |
|
1543 |
|
1544 def has_perm(self, user_obj, perm): |
|
1545 if user_obj.username == settings.ADMIN_LOGIN: |
|
1546 return True |
|
1547 else: |
|
1548 return False |
|
1549 |
|
1550 This gives full permissions to the user granted access in the above example. |
|
1551 Notice that the backend auth functions all take the user object as an argument, |
|
1552 and they also accept the same arguments given to the associated |
|
1553 :class:`django.contrib.auth.models.User` functions. |
|
1554 |
|
1555 A full authorization implementation can be found in |
|
1556 `django/contrib/auth/backends.py`_, which is the default backend and queries |
|
1557 the ``auth_permission`` table most of the time. |
|
1558 |
|
1559 .. _django/contrib/auth/backends.py: http://code.djangoproject.com/browser/django/trunk/django/contrib/auth/backends.py |
|
1560 |
|
1561 Authorization for anonymous users |
|
1562 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ |
|
1563 |
|
1564 .. versionchanged:: 1.2 |
|
1565 |
|
1566 An anonymous user is one that is not authenticated i.e. they have provided no |
|
1567 valid authentication details. However, that does not necessarily mean they are |
|
1568 not authorized to do anything. At the most basic level, most Web sites |
|
1569 authorize anonymous users to browse most of the site, and many allow anonymous |
|
1570 posting of comments etc. |
|
1571 |
|
1572 Django's permission framework does not have a place to store permissions for |
|
1573 anonymous users. However, it has a foundation that allows custom authentication |
|
1574 backends to specify authorization for anonymous users. This is especially useful |
|
1575 for the authors of re-usable apps, who can delegate all questions of authorization |
|
1576 to the auth backend, rather than needing settings, for example, to control |
|
1577 anonymous access. |
|
1578 |
|
1579 To enable this in your own backend, you must set the class attribute |
|
1580 ``supports_anonymous_user`` to ``True``. (This precaution is to maintain |
|
1581 compatibility with backends that assume that all user objects are actual |
|
1582 instances of the :class:`django.contrib.auth.models.User` class). With this |
|
1583 in place, :class:`django.contrib.auth.models.AnonymousUser` will delegate all |
|
1584 the relevant permission methods to the authentication backends. |
|
1585 |
|
1586 A nonexistent ``supports_anonymous_user`` attribute will raise a hidden |
|
1587 ``PendingDeprecationWarning`` if used in Django 1.2. In Django 1.3, this |
|
1588 warning will be upgraded to a ``DeprecationWarning``, which will be displayed |
|
1589 loudly. Additionally ``supports_anonymous_user`` will be set to ``False``. |
|
1590 Django 1.4 will assume that every backend supports anonymous users being |
|
1591 passed to the authorization methods. |
|
1592 |
|
1593 Handling object permissions |
|
1594 --------------------------- |
|
1595 |
|
1596 Django's permission framework has a foundation for object permissions, though |
|
1597 there is no implementation for it in the core. That means that checking for |
|
1598 object permissions will always return ``False`` or an empty list (depending on |
|
1599 the check performed). |
|
1600 |
|
1601 To enable object permissions in your own |
|
1602 :doc:`authentication backend </ref/authbackends>` you'll just have |
|
1603 to allow passing an ``obj`` parameter to the permission methods and set the |
|
1604 ``supports_object_permissions`` class attribute to ``True``. |
|
1605 |
|
1606 A nonexistent ``supports_object_permissions`` will raise a hidden |
|
1607 ``PendingDeprecationWarning`` if used in Django 1.2. In Django 1.3, this |
|
1608 warning will be upgraded to a ``DeprecationWarning``, which will be displayed |
|
1609 loudly. Additionally ``supports_object_permissions`` will be set to ``False``. |
|
1610 Django 1.4 will assume that every backend supports object permissions and |
|
1611 won't check for the existence of ``supports_object_permissions``, which |
|
1612 means not supporting ``obj`` as a parameter will raise a ``TypeError``. |