auth.txt 51 KB

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