auth.txt 63 KB

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