auth.txt 54 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463
  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 is
  144. in the format ``"<application name>.<lowercased model name>"``. If the
  145. user is inactive, this 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 name of the application (case sensitive) in which the user
  317. profile model is defined (in other words, the
  318. name which was passed to :djadmin:`manage.py startapp <startapp>` to create
  319. the application).
  320. 2. The name of the model (not case sensitive) 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. The method :class:`~django.contrib.auth.models.User.get_profile()`
  331. does not create the profile, if it does not exist. You need to
  332. register a handler for the signal
  333. :attr:`django.db.models.signals.post_save` on the User model, and, in
  334. the handler, if created=True, create the associated user profile.
  335. For more information, see `Chapter 12 of the Django book`_.
  336. .. _Chapter 12 of the Django book: http://www.djangobook.com/en/1.0/chapter12/#cn222
  337. Authentication in Web requests
  338. ==============================
  339. Until now, this document has dealt with the low-level APIs for manipulating
  340. authentication-related objects. On a higher level, Django can hook this
  341. authentication framework into its system of
  342. :class:`request objects <django.http.HttpRequest>`.
  343. First, install the
  344. :class:`~django.contrib.sessions.middleware.SessionMiddleware` and
  345. :class:`~django.contrib.auth.middleware.AuthenticationMiddleware`
  346. middlewares by adding them to your :setting:`MIDDLEWARE_CLASSES` setting. See
  347. the :ref:`session documentation <topics-http-sessions>` for more information.
  348. Once you have those middlewares installed, you'll be able to access
  349. :attr:`request.user <django.http.HttpRequest.user>` in views.
  350. :attr:`request.user <django.http.HttpRequest.user>` will give you a
  351. :class:`~django.contrib.auth.models.User` object representing the currently
  352. logged-in user. If a user isn't currently logged in,
  353. :attr:`request.user <django.http.HttpRequest.user>` will be set to an instance
  354. of :class:`~django.contrib.auth.models.AnonymousUser` (see the previous
  355. section). You can tell them apart with
  356. :meth:`~django.contrib.auth.models.User.is_authenticated()`, like so::
  357. if request.user.is_authenticated():
  358. # Do something for authenticated users.
  359. else:
  360. # Do something for anonymous users.
  361. .. _howtologauserin:
  362. How to log a user in
  363. --------------------
  364. Django provides two functions in :mod:`django.contrib.auth`:
  365. :func:`~django.contrib.auth.authenticate()` and
  366. :func:`~django.contrib.auth.login()`.
  367. .. function:: authenticate()
  368. To authenticate a given username and password, use
  369. :func:`~django.contrib.auth.authenticate()`. It takes two keyword
  370. arguments, ``username`` and ``password``, and it returns a
  371. :class:`~django.contrib.auth.models.User` object if the password is valid
  372. for the given username. If the password is invalid,
  373. :func:`~django.contrib.auth.authenticate()` returns ``None``. Example::
  374. from django.contrib.auth import authenticate
  375. user = authenticate(username='john', password='secret')
  376. if user is not None:
  377. if user.is_active:
  378. print "You provided a correct username and password!"
  379. else:
  380. print "Your account has been disabled!"
  381. else:
  382. print "Your username and password were incorrect."
  383. .. function:: login()
  384. To log a user in, in a view, use :func:`~django.contrib.auth.login()`. It
  385. takes an :class:`~django.http.HttpRequest` object and a
  386. :class:`~django.contrib.auth.models.User` object.
  387. :func:`~django.contrib.auth.login()` saves the user's ID in the session,
  388. using Django's session framework, so, as mentioned above, you'll need to
  389. make sure to have the session middleware installed.
  390. This example shows how you might use both
  391. :func:`~django.contrib.auth.authenticate()` and
  392. :func:`~django.contrib.auth.login()`::
  393. from django.contrib.auth import authenticate, login
  394. def my_view(request):
  395. username = request.POST['username']
  396. password = request.POST['password']
  397. user = authenticate(username=username, password=password)
  398. if user is not None:
  399. if user.is_active:
  400. login(request, user)
  401. # Redirect to a success page.
  402. else:
  403. # Return a 'disabled account' error message
  404. else:
  405. # Return an 'invalid login' error message.
  406. .. admonition:: Calling ``authenticate()`` first
  407. When you're manually logging a user in, you *must* call
  408. :func:`~django.contrib.auth.authenticate()` before you call
  409. :func:`~django.contrib.auth.login()`.
  410. :func:`~django.contrib.auth.authenticate()`
  411. sets an attribute on the :class:`~django.contrib.auth.models.User` noting
  412. which authentication backend successfully authenticated that user (see the
  413. `backends documentation`_ for details), and this information is needed
  414. later during the login process.
  415. .. _backends documentation: #other-authentication-sources
  416. Manually checking a user's password
  417. -----------------------------------
  418. .. function:: check_password()
  419. If you'd like to manually authenticate a user by comparing a plain-text
  420. password to the hashed password in the database, use the convenience
  421. function :func:`django.contrib.auth.models.check_password`. It takes two
  422. arguments: the plain-text password to check, and the full value of a user's
  423. ``password`` field in the database to check against, and returns ``True``
  424. if they match, ``False`` otherwise.
  425. How to log a user out
  426. ---------------------
  427. .. function:: logout()
  428. To log out a user who has been logged in via
  429. :func:`django.contrib.auth.login()`, use
  430. :func:`django.contrib.auth.logout()` within your view. It takes an
  431. :class:`~django.http.HttpRequest` object and has no return value.
  432. Example::
  433. from django.contrib.auth import logout
  434. def logout_view(request):
  435. logout(request)
  436. # Redirect to a success page.
  437. Note that :func:`~django.contrib.auth.logout()` doesn't throw any errors if
  438. the user wasn't logged in.
  439. .. versionchanged:: 1.0
  440. Calling ``logout()`` now cleans session data.
  441. When you call :func:`~django.contrib.auth.logout()`, the session data for
  442. the current request is completely cleaned out. All existing data is
  443. removed. This is to prevent another person from using the same web browser
  444. to log in and have access to the previous user's session data. If you want
  445. to put anything into the session that will be available to the user
  446. immediately after logging out, do that *after* calling
  447. :func:`django.contrib.auth.logout()`.
  448. Limiting access to logged-in users
  449. ----------------------------------
  450. The raw way
  451. ~~~~~~~~~~~
  452. The simple, raw way to limit access to pages is to check
  453. :meth:`request.user.is_authenticated()
  454. <django.contrib.auth.models.User.is_authenticated()>` and either redirect to a
  455. login page::
  456. from django.http import HttpResponseRedirect
  457. def my_view(request):
  458. if not request.user.is_authenticated():
  459. return HttpResponseRedirect('/login/?next=%s' % request.path)
  460. # ...
  461. ...or display an error message::
  462. def my_view(request):
  463. if not request.user.is_authenticated():
  464. return render_to_response('myapp/login_error.html')
  465. # ...
  466. The login_required decorator
  467. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  468. .. function:: decorators.login_required()
  469. As a shortcut, you can use the convenient
  470. :func:`~django.contrib.auth.decorators.login_required` decorator::
  471. from django.contrib.auth.decorators import login_required
  472. def my_view(request):
  473. # ...
  474. my_view = login_required(my_view)
  475. Here's an equivalent example, using the more compact decorator syntax
  476. introduced in Python 2.4::
  477. from django.contrib.auth.decorators import login_required
  478. @login_required
  479. def my_view(request):
  480. # ...
  481. :func:`~django.contrib.auth.decorators.login_required` also takes an
  482. optional ``redirect_field_name`` parameter. Example::
  483. from django.contrib.auth.decorators import login_required
  484. def my_view(request):
  485. # ...
  486. my_view = login_required(redirect_field_name='redirect_to')(my_view)
  487. Again, an equivalent example of the more compact decorator syntax
  488. introduced in Python 2.4::
  489. from django.contrib.auth.decorators import login_required
  490. @login_required(redirect_field_name='redirect_to')
  491. def my_view(request):
  492. # ...
  493. :func:`~django.contrib.auth.decorators.login_required` does the following:
  494. * If the user isn't logged in, redirect to
  495. :setting:`settings.LOGIN_URL <LOGIN_URL>` (``/accounts/login/`` by
  496. default), passing the current absolute URL in the query string as
  497. ``next`` or the value of ``redirect_field_name``. For example:
  498. ``/accounts/login/?next=/polls/3/``.
  499. * If the user is logged in, execute the view normally. The view code is
  500. free to assume the user is logged in.
  501. Note that you'll need to map the appropriate Django view to
  502. :setting:`settings.LOGIN_URL <LOGIN_URL>`. For example, using the defaults, add
  503. the following line to your URLconf::
  504. (r'^accounts/login/$', 'django.contrib.auth.views.login'),
  505. .. function:: views.login()
  506. Here's what ``django.contrib.auth.views.login`` does:
  507. * If called via ``GET``, it displays a login form that POSTs to the
  508. same URL. More on this in a bit.
  509. * If called via ``POST``, it tries to log the user in. If login is
  510. successful, the view redirects to the URL specified in ``next``. If
  511. ``next`` isn't provided, it redirects to
  512. :setting:`settings.LOGIN_REDIRECT_URL <LOGIN_REDIRECT_URL>` (which
  513. defaults to ``/accounts/profile/``). If login isn't successful, it
  514. redisplays the login form.
  515. It's your responsibility to provide the login form in a template called
  516. ``registration/login.html`` by default. This template gets passed three
  517. template context variables:
  518. * ``form``: A :class:`~django.forms.Form` object representing the login
  519. form. See the :ref:`forms documentation <topics-forms-index>` for
  520. more on ``Form`` objects.
  521. * ``next``: The URL to redirect to after successful login. This may
  522. contain a query string, too.
  523. * ``site_name``: The name of the current
  524. :class:`~django.contrib.sites.models.Site`, according to the
  525. :setting:`SITE_ID` setting. If you're using the Django development
  526. version and you don't have the site framework installed, this will be
  527. set to the value of :attr:`request.META['SERVER_NAME']
  528. <django.http.HttpRequest.META>`. For more on sites, see
  529. :ref:`ref-contrib-sites`.
  530. If you'd prefer not to call the template :file:`registration/login.html`,
  531. you can pass the ``template_name`` parameter via the extra arguments to
  532. the view in your URLconf. For example, this URLconf line would use
  533. :file:`myapp/login.html` instead::
  534. (r'^accounts/login/$', 'django.contrib.auth.views.login', {'template_name': 'myapp/login.html'}),
  535. Here's a sample :file:`registration/login.html` template you can use as a
  536. starting point. It assumes you have a :file:`base.html` template that
  537. defines a ``content`` block:
  538. .. code-block:: html
  539. {% extends "base.html" %}
  540. {% block content %}
  541. {% if form.errors %}
  542. <p>Your username and password didn't match. Please try again.</p>
  543. {% endif %}
  544. <form method="post" action="{% url django.contrib.auth.views.login %}">
  545. <table>
  546. <tr>
  547. <td>{{ form.username.label_tag }}</td>
  548. <td>{{ form.username }}</td>
  549. </tr>
  550. <tr>
  551. <td>{{ form.password.label_tag }}</td>
  552. <td>{{ form.password }}</td>
  553. </tr>
  554. </table>
  555. <input type="submit" value="login" />
  556. <input type="hidden" name="next" value="{{ next }}" />
  557. </form>
  558. {% endblock %}
  559. .. _forms documentation: ../forms/
  560. .. _site framework docs: ../sites/
  561. Other built-in views
  562. --------------------
  563. In addition to the :func:`~views.login` view, the authentication system
  564. includes a few other useful built-in views located in
  565. :mod:`django.contrib.auth.views`:
  566. .. function:: views.logout(request, [next_page, template_name, redirect_field_name])
  567. Logs a user out.
  568. **Optional arguments:**
  569. * ``next_page``: The URL to redirect to after logout.
  570. * ``template_name``: The full name of a template to display after
  571. logging the user out. This will default to
  572. :file:`registration/logged_out.html` if no argument is supplied.
  573. * ``redirect_field_name``: The name of a ``GET`` field containing the
  574. URL to redirect to after log out. Overrides ``next_page`` if the given
  575. ``GET`` parameter is passed.
  576. **Template context:**
  577. * ``title``: The string "Logged out", localized.
  578. .. function:: views.logout_then_login(request[, login_url])
  579. Logs a user out, then redirects to the login page.
  580. **Optional arguments:**
  581. * ``login_url``: The URL of the login page to redirect to. This will
  582. default to :setting:`settings.LOGIN_URL <LOGIN_URL>` if not supplied.
  583. .. function:: views.password_change(request[, template_name, post_change_redirect])
  584. Allows a user to change their password.
  585. **Optional arguments:**
  586. * ``template_name``: The full name of a template to use for
  587. displaying the password change form. This will default to
  588. :file:`registration/password_change_form.html` if not supplied.
  589. * ``post_change_redirect``: The URL to redirect to after successful
  590. password change.
  591. **Template context:**
  592. * ``form``: The password change form.
  593. .. function:: views.password_change_done(request[, template_name])
  594. The page shown after a user has changed their password.
  595. **Optional arguments:**
  596. * ``template_name``: The full name of a template to use. This will
  597. default to :file:`registration/password_change_done.html` if not
  598. supplied.
  599. .. function:: views.password_reset
  600. Allows a user to reset their password, and sends them the new password
  601. in an e-mail.
  602. **Optional arguments:**
  603. * ``template_name``: The full name of a template to use for
  604. displaying the password reset form. This will default to
  605. :file:`registration/password_reset_form.html` if not supplied.
  606. * ``email_template_name``: The full name of a template to use for
  607. generating the e-mail with the new password. This will default to
  608. :file:`registration/password_reset_email.html` if not supplied.
  609. **Template context:**
  610. * ``form``: The form for resetting the user's password.
  611. .. function:: views.password_reset_done
  612. The page shown after a user has reset their password.
  613. **Optional arguments:**
  614. * ``template_name``: The full name of a template to use. This will
  615. default to :file:`registration/password_reset_done.html` if not
  616. supplied.
  617. .. function:: views.redirect_to_login
  618. Redirects to the login page, and then back to another URL after a
  619. successful login.
  620. **Required arguments:**
  621. * ``next``: The URL to redirect to after a successful login.
  622. **Optional arguments:**
  623. * ``login_url``: The URL of the login page to redirect to. This will
  624. default to :setting:`settings.LOGIN_URL <LOGIN_URL>` if not supplied.
  625. .. function:: password_reset_confirm(request[,uidb36, token, template_name, token_generator, set_password_form, post_reset_redirect])
  626. Presents a form for entering a new password.
  627. **Optional arguments:**
  628. * ``uidb36``: The user's id encoded in base 36. This will default to
  629. ``None``.
  630. * ``token``: Token to check that the password is valid. This will default to ``None``.
  631. * ``template_name``: The full name of a template to display the confirm
  632. password view. Default value is :file:`registration/password_reset_confirm.html`.
  633. * ``token_generator``: Instance of the class to check the password. This
  634. will default to ``default_token_generator``, it's an instance of
  635. ``django.contrib.auth.tokens.PasswordResetTokenGenerator``.
  636. * ``set_password_form``: Form that will use to set the password. This will
  637. default to ``SetPasswordForm``.
  638. * ``post_reset_redirect``: URL to redirect after the password reset
  639. done. This will default to ``None``.
  640. .. function:: password_reset_complete(request[,template_name])
  641. Presents a view that informs that the password has been changed very well.
  642. **Optional arguments:**
  643. * ``template_name``: The full name of a template to display the view.
  644. This will default to :file:`registration/password_reset_complete.html`.
  645. Built-in forms
  646. --------------
  647. .. module:: django.contrib.auth.forms
  648. If you don't want to use the built-in views, but want the convenience of not
  649. having to write forms for this functionality, the authentication system
  650. provides several built-in forms located in :mod:`django.contrib.auth.forms`:
  651. .. class:: AdminPasswordChangeForm
  652. A form used in the admin interface to change a user's password.
  653. .. class:: AuthenticationForm
  654. A form for logging a user in.
  655. .. class:: PasswordChangeForm
  656. A form for allowing a user to change their password.
  657. .. class:: PasswordResetForm
  658. A form for resetting a user's password and e-mailing the new password to
  659. them.
  660. .. class:: UserCreationForm
  661. A form for creating a new user.
  662. Limiting access to logged-in users that pass a test
  663. ---------------------------------------------------
  664. .. currentmodule:: django.contrib.auth
  665. To limit access based on certain permissions or some other test, you'd do
  666. essentially the same thing as described in the previous section.
  667. The simple way is to run your test on :attr:`request.user
  668. <django.http.HttpRequest.user>` in the view directly. For example, this view
  669. checks to make sure the user is logged in and has the permission
  670. ``polls.can_vote``::
  671. def my_view(request):
  672. if not (request.user.is_authenticated() and request.user.has_perm('polls.can_vote')):
  673. return HttpResponse("You can't vote in this poll.")
  674. # ...
  675. .. function:: decorators.user_passes_test()
  676. As a shortcut, you can use the convenient ``user_passes_test`` decorator::
  677. from django.contrib.auth.decorators import user_passes_test
  678. def my_view(request):
  679. # ...
  680. my_view = user_passes_test(lambda u: u.has_perm('polls.can_vote'))(my_view)
  681. We're using this particular test as a relatively simple example. However,
  682. if you just want to test whether a permission is available to a user, you
  683. can use the :func:`~django.contrib.auth.decorators.permission_required()`
  684. decorator, described later in this document.
  685. Here's the same thing, using Python 2.4's decorator syntax::
  686. from django.contrib.auth.decorators import user_passes_test
  687. @user_passes_test(lambda u: u.has_perm('polls.can_vote'))
  688. def my_view(request):
  689. # ...
  690. :func:`~django.contrib.auth.decorators.user_passes_test` takes a required
  691. argument: a callable that takes a
  692. :class:`~django.contrib.auth.models.User` object and returns ``True`` if
  693. the user is allowed to view the page. Note that
  694. :func:`~django.contrib.auth.decorators.user_passes_test` does not
  695. automatically check that the :class:`~django.contrib.auth.models.User` is
  696. not anonymous.
  697. :func:`~django.contrib.auth.decorators.user_passes_test()` takes an
  698. optional ``login_url`` argument, which lets you specify the URL for your
  699. login page (:setting:`settings.LOGIN_URL <LOGIN_URL>` by default).
  700. Example in Python 2.3 syntax::
  701. from django.contrib.auth.decorators import user_passes_test
  702. def my_view(request):
  703. # ...
  704. my_view = user_passes_test(lambda u: u.has_perm('polls.can_vote'), login_url='/login/')(my_view)
  705. Example in Python 2.4 syntax::
  706. from django.contrib.auth.decorators import user_passes_test
  707. @user_passes_test(lambda u: u.has_perm('polls.can_vote'), login_url='/login/')
  708. def my_view(request):
  709. # ...
  710. The permission_required decorator
  711. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  712. .. function:: decorators.permission_required()
  713. It's a relatively common task to check whether a user has a particular
  714. permission. For that reason, Django provides a shortcut for that case: the
  715. :func:`~django.contrib.auth.decorators.permission_required()` decorator.
  716. Using this decorator, the earlier example can be written as::
  717. from django.contrib.auth.decorators import permission_required
  718. def my_view(request):
  719. # ...
  720. my_view = permission_required('polls.can_vote')(my_view)
  721. As for the :meth:`User.has_perm` method, permission names take the form
  722. ``"<application name>.<lowercased model name>"`` (i.e. ``polls.choice`` for
  723. a ``Choice`` model in the ``polls`` application).
  724. Note that :func:`~django.contrib.auth.decorators.permission_required()`
  725. also takes an optional ``login_url`` parameter. Example::
  726. from django.contrib.auth.decorators import permission_required
  727. def my_view(request):
  728. # ...
  729. my_view = permission_required('polls.can_vote', login_url='/loginpage/')(my_view)
  730. As in the :func:`~decorators.login_required` decorator, ``login_url``
  731. defaults to :setting:`settings.LOGIN_URL <LOGIN_URL>`.
  732. Limiting access to generic views
  733. --------------------------------
  734. To limit access to a :ref:`generic view <ref-generic-views>`, write a thin
  735. wrapper around the view, and point your URLconf to your wrapper instead of the
  736. generic view itself. For example::
  737. from django.views.generic.date_based import object_detail
  738. @login_required
  739. def limited_object_detail(*args, **kwargs):
  740. return object_detail(*args, **kwargs)
  741. Permissions
  742. ===========
  743. Django comes with a simple permissions system. It provides a way to assign
  744. permissions to specific users and groups of users.
  745. It's used by the Django admin site, but you're welcome to use it in your own
  746. code.
  747. The Django admin site uses permissions as follows:
  748. * Access to view the "add" form and add an object is limited to users with
  749. the "add" permission for that type of object.
  750. * Access to view the change list, view the "change" form and change an
  751. object is limited to users with the "change" permission for that type of
  752. object.
  753. * Access to delete an object is limited to users with the "delete"
  754. permission for that type of object.
  755. Permissions are set globally per type of object, not per specific object
  756. instance. For example, it's possible to say "Mary may change news stories," but
  757. it's not currently possible to say "Mary may change news stories, but only the
  758. ones she created herself" or "Mary may only change news stories that have a
  759. certain status, publication date or ID." The latter functionality is something
  760. Django developers are currently discussing.
  761. Default permissions
  762. -------------------
  763. When ``django.contrib.auth`` is listed in your :setting:`INSTALLED_APPS`
  764. setting, it will ensure that three default permissions -- add, change and
  765. delete -- are created for each Django model defined in one of your installed
  766. applications.
  767. These permissions will be created when you run :djadmin:`manage.py syncdb
  768. <syncdb>`; the first time you run ``syncdb`` after adding
  769. ``django.contrib.auth`` to :setting:`INSTALLED_APPS`, the default permissions
  770. will be created for all previously-installed models, as well as for any new
  771. models being installed at that time. Afterward, it will create default
  772. permissions for new models each time you run :djadmin:`manage.py syncdb
  773. <syncdb>`.
  774. .. _custom-permissions:
  775. Custom permissions
  776. ------------------
  777. To create custom permissions for a given model object, use the ``permissions``
  778. :ref:`model Meta attribute <meta-options>`.
  779. This example model creates three custom permissions::
  780. class USCitizen(models.Model):
  781. # ...
  782. class Meta:
  783. permissions = (
  784. ("can_drive", "Can drive"),
  785. ("can_vote", "Can vote in elections"),
  786. ("can_drink", "Can drink alcohol"),
  787. )
  788. The only thing this does is create those extra permissions when you run
  789. :djadmin:`manage.py syncdb <syncdb>`.
  790. API reference
  791. -------------
  792. .. class:: models.Permission
  793. Just like users, permissions are implemented in a Django model that lives
  794. in `django/contrib/auth/models.py`_.
  795. .. _django/contrib/auth/models.py: http://code.djangoproject.com/browser/django/trunk/django/contrib/auth/models.py
  796. Fields
  797. ~~~~~~
  798. :class:`~django.contrib.auth.models.Permission` objects have the following
  799. fields:
  800. .. attribute:: models.Permission.name
  801. Required. 50 characters or fewer. Example: ``'Can vote'``.
  802. .. attribute:: models.Permission.content_type
  803. Required. A reference to the ``django_content_type`` database table, which
  804. contains a record for each installed Django model.
  805. .. attribute:: models.Permission.codename
  806. Required. 100 characters or fewer. Example: ``'can_vote'``.
  807. Methods
  808. ~~~~~~~
  809. :class:`~django.contrib.auth.models.Permission` objects have the standard
  810. data-access methods like any other :ref:`Django model <ref-models-instances>`.
  811. Authentication data in templates
  812. ================================
  813. The currently logged-in user and his/her permissions are made available in the
  814. :ref:`template context <ref-templates-api>` when you use
  815. :class:`~django.template.context.RequestContext`.
  816. .. admonition:: Technicality
  817. Technically, these variables are only made available in the template context
  818. if you use :class:`~django.template.context.RequestContext` *and* your
  819. :setting:`TEMPLATE_CONTEXT_PROCESSORS` setting contains
  820. ``"django.core.context_processors.auth"``, which is default. For more, see
  821. the :ref:`RequestContext docs <subclassing-context-requestcontext>`.
  822. Users
  823. -----
  824. When rendering a template :class:`~django.template.context.RequestContext`, the
  825. currently logged-in user, either a :class:`~django.contrib.auth.models.User`
  826. instance or an :class:`~django.contrib.auth.models.AnonymousUser` instance, is
  827. stored in the template variable ``{{ user }}``:
  828. .. code-block:: html
  829. {% if user.is_authenticated %}
  830. <p>Welcome, {{ user.username }}. Thanks for logging in.</p>
  831. {% else %}
  832. <p>Welcome, new user. Please log in.</p>
  833. {% endif %}
  834. This template context variable is not available if a ``RequestContext`` is not
  835. being used.
  836. Permissions
  837. -----------
  838. The currently logged-in user's permissions are stored in the template variable
  839. ``{{ perms }}``. This is an instance of
  840. :class:`django.core.context_processors.PermWrapper`, which is a
  841. template-friendly proxy of permissions.
  842. In the ``{{ perms }}`` object, single-attribute lookup is a proxy to
  843. :meth:`User.has_module_perms <django.contrib.auth.models.User.has_module_perms>`.
  844. This example would display ``True`` if the logged-in user had any permissions
  845. in the ``foo`` app::
  846. {{ perms.foo }}
  847. Two-level-attribute lookup is a proxy to
  848. :meth:`User.has_perm <django.contrib.auth.models.User.has_perm>`. This example
  849. would display ``True`` if the logged-in user had the permission
  850. ``foo.can_vote``::
  851. {{ perms.foo.can_vote }}
  852. Thus, you can check permissions in template ``{% if %}`` statements:
  853. .. code-block:: html
  854. {% if perms.foo %}
  855. <p>You have permission to do something in the foo app.</p>
  856. {% if perms.foo.can_vote %}
  857. <p>You can vote!</p>
  858. {% endif %}
  859. {% if perms.foo.can_drive %}
  860. <p>You can drive!</p>
  861. {% endif %}
  862. {% else %}
  863. <p>You don't have permission to do anything in the foo app.</p>
  864. {% endif %}
  865. Groups
  866. ======
  867. Groups are a generic way of categorizing users so you can apply permissions, or
  868. some other label, to those users. A user can belong to any number of groups.
  869. A user in a group automatically has the permissions granted to that group. For
  870. example, if the group ``Site editors`` has the permission
  871. ``can_edit_home_page``, any user in that group will have that permission.
  872. Beyond permissions, groups are a convenient way to categorize users to give
  873. them some label, or extended functionality. For example, you could create a
  874. group ``'Special users'``, and you could write code that could, say, give them
  875. access to a members-only portion of your site, or send them members-only e-mail
  876. messages.
  877. Messages
  878. ========
  879. The message system is a lightweight way to queue messages for given users.
  880. A message is associated with a :class:`~django.contrib.auth.models.User`.
  881. There's no concept of expiration or timestamps.
  882. Messages are used by the Django admin after successful actions. For example,
  883. ``"The poll Foo was created successfully."`` is a message.
  884. The API is simple:
  885. .. method:: models.User.message_set.create(message)
  886. To create a new message, use
  887. ``user_obj.message_set.create(message='message_text')``.
  888. To retrieve/delete messages, use
  889. :meth:`user_obj.get_and_delete_messages() <django.contrib.auth.models.User.get_and_delete_messages>`,
  890. which returns a list of ``Message`` objects in the user's queue (if any)
  891. and deletes the messages from the queue.
  892. In this example view, the system saves a message for the user after creating
  893. a playlist::
  894. def create_playlist(request, songs):
  895. # Create the playlist with the given songs.
  896. # ...
  897. request.user.message_set.create(message="Your playlist was added successfully.")
  898. return render_to_response("playlists/create.html",
  899. context_instance=RequestContext(request))
  900. When you use :class:`~django.template.context.RequestContext`, the currently
  901. logged-in user and his/her messages are made available in the
  902. :ref:`template context <ref-templates-api>` as the template variable
  903. ``{{ messages }}``. Here's an example of template code that displays messages:
  904. .. code-block:: html
  905. {% if messages %}
  906. <ul>
  907. {% for message in messages %}
  908. <li>{{ message }}</li>
  909. {% endfor %}
  910. </ul>
  911. {% endif %}
  912. Note that :class:`~django.template.context.RequestContext` calls
  913. :meth:`~django.contrib.auth.models.User.get_and_delete_messages` behind the
  914. scenes, so any messages will be deleted even if you don't display them.
  915. Finally, note that this messages framework only works with users in the user
  916. database. To send messages to anonymous users, use the
  917. :ref:`session framework <topics-http-sessions>`.
  918. .. _authentication-backends:
  919. Other authentication sources
  920. ============================
  921. The authentication that comes with Django is good enough for most common cases,
  922. but you may have the need to hook into another authentication source -- that
  923. is, another source of usernames and passwords or authentication methods.
  924. For example, your company may already have an LDAP setup that stores a username
  925. and password for every employee. It'd be a hassle for both the network
  926. administrator and the users themselves if users had separate accounts in LDAP
  927. and the Django-based applications.
  928. So, to handle situations like this, the Django authentication system lets you
  929. plug in other authentication sources. You can override Django's default
  930. database-based scheme, or you can use the default system in tandem with other
  931. systems.
  932. See the :ref:`authentication backend reference <ref-authentication-backends>`
  933. for information on the authentication backends included with Django.
  934. Specifying authentication backends
  935. ----------------------------------
  936. Behind the scenes, Django maintains a list of "authentication backends" that it
  937. checks for authentication. When somebody calls
  938. :func:`django.contrib.auth.authenticate()` -- as described in :ref:`How to log
  939. a user in` above -- Django tries authenticating across all of its
  940. authentication backends. If the first authentication method fails, Django tries
  941. the second one, and so on, until all backends have been attempted.
  942. The list of authentication backends to use is specified in the
  943. :setting:`AUTHENTICATION_BACKENDS` setting. This should be a tuple of Python
  944. path names that point to Python classes that know how to authenticate. These
  945. classes can be anywhere on your Python path.
  946. By default, :setting:`AUTHENTICATION_BACKENDS` is set to::
  947. ('django.contrib.auth.backends.ModelBackend',)
  948. That's the basic authentication scheme that checks the Django users database.
  949. The order of :setting:`AUTHENTICATION_BACKENDS` matters, so if the same
  950. username and password is valid in multiple backends, Django will stop
  951. processing at the first positive match.
  952. .. note::
  953. Once a user has authenticated, Django stores which backend was used to
  954. authenticate the user in the user's session, and re-uses the same backend
  955. for subsequent authentication attempts for that user. This effectively means
  956. that authentication sources are cached, so if you change
  957. :setting:`AUTHENTICATION_BACKENDS`, you'll need to clear out session data if
  958. you need to force users to re-authenticate using different methods. A simple
  959. way to do that is simply to execute ``Session.objects.all().delete()``.
  960. Writing an authentication backend
  961. ---------------------------------
  962. An authentication backend is a class that implements two methods:
  963. ``get_user(user_id)`` and ``authenticate(**credentials)``.
  964. The ``get_user`` method takes a ``user_id`` -- which could be a username,
  965. database ID or whatever -- and returns a ``User`` object.
  966. The ``authenticate`` method takes credentials as keyword arguments. Most of
  967. the time, it'll just look like this::
  968. class MyBackend:
  969. def authenticate(self, username=None, password=None):
  970. # Check the username/password and return a User.
  971. But it could also authenticate a token, like so::
  972. class MyBackend:
  973. def authenticate(self, token=None):
  974. # Check the token and return a User.
  975. Either way, ``authenticate`` should check the credentials it gets, and it
  976. should return a ``User`` object that matches those credentials, if the
  977. credentials are valid. If they're not valid, it should return ``None``.
  978. The Django admin system is tightly coupled to the Django ``User`` object
  979. described at the beginning of this document. For now, the best way to deal with
  980. this is to create a Django ``User`` object for each user that exists for your
  981. backend (e.g., in your LDAP directory, your external SQL database, etc.) You
  982. can either write a script to do this in advance, or your ``authenticate``
  983. method can do it the first time a user logs in.
  984. Here's an example backend that authenticates against a username and password
  985. variable defined in your ``settings.py`` file and creates a Django ``User``
  986. object the first time a user authenticates::
  987. from django.conf import settings
  988. from django.contrib.auth.models import User, check_password
  989. class SettingsBackend:
  990. """
  991. Authenticate against the settings ADMIN_LOGIN and ADMIN_PASSWORD.
  992. Use the login name, and a hash of the password. For example:
  993. ADMIN_LOGIN = 'admin'
  994. ADMIN_PASSWORD = 'sha1$4e987$afbcf42e21bd417fb71db8c66b321e9fc33051de'
  995. """
  996. def authenticate(self, username=None, password=None):
  997. login_valid = (settings.ADMIN_LOGIN == username)
  998. pwd_valid = check_password(password, settings.ADMIN_PASSWORD)
  999. if login_valid and pwd_valid:
  1000. try:
  1001. user = User.objects.get(username=username)
  1002. except User.DoesNotExist:
  1003. # Create a new user. Note that we can set password
  1004. # to anything, because it won't be checked; the password
  1005. # from settings.py will.
  1006. user = User(username=username, password='get from settings.py')
  1007. user.is_staff = True
  1008. user.is_superuser = True
  1009. user.save()
  1010. return user
  1011. return None
  1012. def get_user(self, user_id):
  1013. try:
  1014. return User.objects.get(pk=user_id)
  1015. except User.DoesNotExist:
  1016. return None
  1017. Handling authorization in custom backends
  1018. -----------------------------------------
  1019. Custom auth backends can provide their own permissions.
  1020. The user model will delegate permission lookup functions
  1021. (:meth:`~django.contrib.auth.models.User.get_group_permissions()`,
  1022. :meth:`~django.contrib.auth.models.User.get_all_permissions()`,
  1023. :meth:`~django.contrib.auth.models.User.has_perm()`, and
  1024. :meth:`~django.contrib.auth.models.User.has_module_perms()`) to any
  1025. authentication backend that implements these functions.
  1026. The permissions given to the user will be the superset of all permissions
  1027. returned by all backends. That is, Django grants a permission to a user that
  1028. any one backend grants.
  1029. The simple backend above could implement permissions for the magic admin
  1030. fairly simply::
  1031. class SettingsBackend:
  1032. # ...
  1033. def has_perm(self, user_obj, perm):
  1034. if user_obj.username == settings.ADMIN_LOGIN:
  1035. return True
  1036. else:
  1037. return False
  1038. This gives full permissions to the user granted access in the above example.
  1039. Notice that the backend auth functions all take the user object as an argument,
  1040. and they also accept the same arguments given to the associated
  1041. :class:`django.contrib.auth.models.User` functions.
  1042. A full authorization implementation can be found in
  1043. `django/contrib/auth/backends.py`_, which is the default backend and queries
  1044. the ``auth_permission`` table most of the time.
  1045. .. _django/contrib/auth/backends.py: http://code.djangoproject.com/browser/django/trunk/django/contrib/auth/backends.py