PageRenderTime 61ms CodeModel.GetById 20ms RepoModel.GetById 0ms app.codeStats 0ms

/docs/topics/auth.txt

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