auth.txt 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861
  1. =======================
  2. ``django.contrib.auth``
  3. =======================
  4. This document provides API reference material for the components of Django's
  5. authentication system. For more details on the usage of these components or
  6. how to customize authentication and authorization see the :doc:`authentication
  7. topic guide </topics/auth/index>`.
  8. .. currentmodule:: django.contrib.auth
  9. ``User`` model
  10. ==============
  11. .. class:: models.User
  12. Fields
  13. ------
  14. .. class:: models.User
  15. :noindex:
  16. :class:`~django.contrib.auth.models.User` objects have the following
  17. fields:
  18. .. attribute:: username
  19. Required. 150 characters or fewer. Usernames may contain alphanumeric,
  20. ``_``, ``@``, ``+``, ``.`` and ``-`` characters.
  21. The ``max_length`` should be sufficient for many use cases. If you need
  22. a longer length, please use a :ref:`custom user model
  23. <specifying-custom-user-model>`. If you use MySQL with the ``utf8mb4``
  24. encoding (recommended for proper Unicode support), specify at most
  25. ``max_length=191`` because MySQL can only create unique indexes with
  26. 191 characters in that case by default.
  27. .. attribute:: first_name
  28. Optional (:attr:`blank=True <django.db.models.Field.blank>`). 150
  29. characters or fewer.
  30. .. attribute:: last_name
  31. Optional (:attr:`blank=True <django.db.models.Field.blank>`). 150
  32. characters or fewer.
  33. .. attribute:: email
  34. Optional (:attr:`blank=True <django.db.models.Field.blank>`). Email
  35. address.
  36. .. attribute:: password
  37. Required. A hash of, and metadata about, the password. (Django doesn't
  38. store the raw password.) Raw passwords can be arbitrarily long and can
  39. contain any character. See the :doc:`password documentation
  40. </topics/auth/passwords>`.
  41. .. attribute:: groups
  42. Many-to-many relationship to :class:`~django.contrib.auth.models.Group`
  43. .. attribute:: user_permissions
  44. Many-to-many relationship to :class:`~django.contrib.auth.models.Permission`
  45. .. attribute:: is_staff
  46. Boolean. Allows this user to access the admin site.
  47. .. attribute:: is_active
  48. Boolean. Marks this user account as active. We recommend that you set
  49. this flag to ``False`` instead of deleting accounts. That way, if your
  50. applications have any foreign keys to users, the foreign keys won't
  51. break.
  52. This doesn't necessarily control whether or not the user can log in.
  53. Authentication backends aren't required to check for the ``is_active``
  54. flag but the default backend
  55. (:class:`~django.contrib.auth.backends.ModelBackend`) and the
  56. :class:`~django.contrib.auth.backends.RemoteUserBackend` do. You can
  57. use :class:`~django.contrib.auth.backends.AllowAllUsersModelBackend`
  58. or :class:`~django.contrib.auth.backends.AllowAllUsersRemoteUserBackend`
  59. if you want to allow inactive users to login. In this case, you'll also
  60. want to customize the
  61. :class:`~django.contrib.auth.forms.AuthenticationForm` used by the
  62. :class:`~django.contrib.auth.views.LoginView` as it rejects inactive
  63. users. Be aware that the permission-checking methods such as
  64. :meth:`~django.contrib.auth.models.User.has_perm` and the
  65. authentication in the Django admin all return ``False`` for inactive
  66. users.
  67. .. attribute:: is_superuser
  68. Boolean. Treats this user as having all permissions without assigning
  69. any permission to it in particular.
  70. .. attribute:: last_login
  71. A datetime of the user's last login.
  72. .. attribute:: date_joined
  73. The date/time when the account was created.
  74. Attributes
  75. ----------
  76. .. class:: models.User
  77. :noindex:
  78. .. attribute:: is_authenticated
  79. Read-only attribute which is always ``True`` (as opposed to
  80. ``AnonymousUser.is_authenticated`` which is always ``False``). This is
  81. a way to tell if the user has been authenticated. This does not imply
  82. any permissions and doesn't check if the user is active or has a valid
  83. session. Even though normally you will check this attribute on
  84. ``request.user`` to find out whether it has been populated by the
  85. :class:`~django.contrib.auth.middleware.AuthenticationMiddleware`
  86. (representing the currently logged-in user), you should know this
  87. attribute is ``True`` for any :class:`~models.User` instance.
  88. .. attribute:: is_anonymous
  89. Read-only attribute which is always ``False``. This is a way of
  90. differentiating :class:`~models.User` and :class:`~models.AnonymousUser`
  91. objects. Generally, you should prefer using
  92. :attr:`~django.contrib.auth.models.User.is_authenticated` to this
  93. attribute.
  94. Methods
  95. -------
  96. .. class:: models.User
  97. :noindex:
  98. .. method:: get_username()
  99. Returns the username for the user. Since the ``User`` model can be
  100. swapped out, you should use this method instead of referencing the
  101. username attribute directly.
  102. .. method:: get_full_name()
  103. Returns the :attr:`~django.contrib.auth.models.User.first_name` plus
  104. the :attr:`~django.contrib.auth.models.User.last_name`, with a space in
  105. between.
  106. .. method:: get_short_name()
  107. Returns the :attr:`~django.contrib.auth.models.User.first_name`.
  108. .. method:: set_password(raw_password)
  109. Sets the user's password to the given raw string, taking care of the
  110. password hashing. Doesn't save the
  111. :class:`~django.contrib.auth.models.User` object.
  112. When the ``raw_password`` is ``None``, the password will be set to an
  113. unusable password, as if
  114. :meth:`~django.contrib.auth.models.User.set_unusable_password()`
  115. were used.
  116. .. method:: check_password(raw_password)
  117. .. method:: acheck_password(raw_password)
  118. *Asynchronous version*: ``acheck_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:: set_unusable_password()
  123. Marks the user as having no password set. This isn't the same as
  124. having a blank string for a password.
  125. :meth:`~django.contrib.auth.models.User.check_password()` for this user
  126. will never return ``True``. Doesn't save the
  127. :class:`~django.contrib.auth.models.User` object.
  128. You may need this if authentication for your application takes place
  129. against an existing external source such as an LDAP directory.
  130. .. admonition:: Password reset restriction
  131. Users having an unusable password will not able to request a
  132. password reset email via
  133. :class:`~django.contrib.auth.views.PasswordResetView`.
  134. .. method:: has_usable_password()
  135. Returns ``False`` if
  136. :meth:`~django.contrib.auth.models.User.set_unusable_password()` has
  137. been called for this user.
  138. .. method:: get_user_permissions(obj=None)
  139. .. method:: aget_user_permissions(obj=None)
  140. *Asynchronous version*: ``aget_user_permissions()``
  141. Returns a set of permission strings that the user has directly.
  142. If ``obj`` is passed in, only returns the user permissions for this
  143. specific object.
  144. .. versionchanged:: 5.2
  145. ``aget_user_permissions()`` method was added.
  146. .. method:: get_group_permissions(obj=None)
  147. .. method:: aget_group_permissions(obj=None)
  148. *Asynchronous version*: ``aget_group_permissions()``
  149. Returns a set of permission strings that the user has, through their
  150. groups.
  151. If ``obj`` is passed in, only returns the group permissions for
  152. this specific object.
  153. .. versionchanged:: 5.2
  154. ``aget_group_permissions()`` method was added.
  155. .. method:: get_all_permissions(obj=None)
  156. .. method:: aget_all_permissions(obj=None)
  157. *Asynchronous version*: ``aget_all_permissions()``
  158. Returns a set of permission strings that the user has, both through
  159. group and user permissions.
  160. If ``obj`` is passed in, only returns the permissions for this
  161. specific object.
  162. .. versionchanged:: 5.2
  163. ``aget_all_permissions()`` method was added.
  164. .. method:: has_perm(perm, obj=None)
  165. .. method:: ahas_perm(perm, obj=None)
  166. *Asynchronous version*: ``ahas_perm()``
  167. Returns ``True`` if the user has the specified permission, where perm
  168. is in the format ``"<app label>.<permission codename>"``. (see
  169. documentation on :ref:`permissions <topic-authorization>`). If the user is
  170. inactive, this method will always return ``False``. For an active
  171. superuser, this method will always return ``True``.
  172. If ``obj`` is passed in, this method won't check for a permission for
  173. the model, but for this specific object.
  174. .. versionchanged:: 5.2
  175. ``ahas_perm()`` method was added.
  176. .. method:: has_perms(perm_list, obj=None)
  177. .. method:: ahas_perms(perm_list, obj=None)
  178. *Asynchronous version*: ``ahas_perms()``
  179. Returns ``True`` if the user has each of the specified permissions,
  180. where each perm is in the format
  181. ``"<app label>.<permission codename>"``. If the user is inactive,
  182. this method will always return ``False``. For an active superuser, this
  183. method will always return ``True``.
  184. If ``obj`` is passed in, this method won't check for permissions for
  185. the model, but for the specific object.
  186. .. versionchanged:: 5.2
  187. ``ahas_perms()`` method was added.
  188. .. method:: has_module_perms(package_name)
  189. .. method:: ahas_module_perms(package_name)
  190. *Asynchronous version*: ``ahas_module_perms()``
  191. Returns ``True`` if the user has any permissions in the given package
  192. (the Django app label). If the user is inactive, this method will
  193. always return ``False``. For an active superuser, this method will
  194. always return ``True``.
  195. .. versionchanged:: 5.2
  196. ``ahas_module_perms()`` method was added.
  197. .. method:: email_user(subject, message, from_email=None, **kwargs)
  198. Sends an email to the user. If ``from_email`` is ``None``, Django uses
  199. the :setting:`DEFAULT_FROM_EMAIL`. Any ``**kwargs`` are passed to the
  200. underlying :meth:`~django.core.mail.send_mail()` call.
  201. Manager methods
  202. ---------------
  203. .. class:: models.UserManager
  204. The :class:`~django.contrib.auth.models.User` model has a custom manager
  205. that has the following helper methods (in addition to the methods provided
  206. by :class:`~django.contrib.auth.models.BaseUserManager`):
  207. .. method:: create_user(username, email=None, password=None, **extra_fields)
  208. .. method:: acreate_user(username, email=None, password=None, **extra_fields)
  209. *Asynchronous version*: ``acreate_user()``
  210. Creates, saves and returns a :class:`~django.contrib.auth.models.User`.
  211. The :attr:`~django.contrib.auth.models.User.username` and
  212. :attr:`~django.contrib.auth.models.User.password` are set as given. The
  213. domain portion of :attr:`~django.contrib.auth.models.User.email` is
  214. automatically converted to lowercase, and the returned
  215. :class:`~django.contrib.auth.models.User` object will have
  216. :attr:`~django.contrib.auth.models.User.is_active` set to ``True``.
  217. If no password is provided,
  218. :meth:`~django.contrib.auth.models.User.set_unusable_password()` will
  219. be called.
  220. The ``extra_fields`` keyword arguments are passed through to the
  221. :class:`~django.contrib.auth.models.User`’s ``__init__`` method to
  222. allow setting arbitrary fields on a :ref:`custom user model
  223. <auth-custom-user>`.
  224. See :ref:`Creating users <topics-auth-creating-users>` for example usage.
  225. .. versionchanged:: 5.2
  226. ``acreate_user()`` method was added.
  227. .. method:: create_superuser(username, email=None, password=None, **extra_fields)
  228. .. method:: acreate_superuser(username, email=None, password=None, **extra_fields)
  229. *Asynchronous version*: ``acreate_superuser()``
  230. Same as :meth:`create_user`, but sets :attr:`~models.User.is_staff` and
  231. :attr:`~models.User.is_superuser` to ``True``.
  232. .. versionchanged:: 5.2
  233. ``acreate_superuser()`` method was added.
  234. .. method:: with_perm(perm, is_active=True, include_superusers=True, backend=None, obj=None)
  235. Returns users that have the given permission ``perm`` either in the
  236. ``"<app label>.<permission codename>"`` format or as a
  237. :class:`~django.contrib.auth.models.Permission` instance. Returns an
  238. empty queryset if no users who have the ``perm`` found.
  239. If ``is_active`` is ``True`` (default), returns only active users, or
  240. if ``False``, returns only inactive users. Use ``None`` to return all
  241. users irrespective of active state.
  242. If ``include_superusers`` is ``True`` (default), the result will
  243. include superusers.
  244. If ``backend`` is passed in and it's defined in
  245. :setting:`AUTHENTICATION_BACKENDS`, then this method will use it.
  246. Otherwise, it will use the ``backend`` in
  247. :setting:`AUTHENTICATION_BACKENDS`, if there is only one, or raise an
  248. exception.
  249. ``AnonymousUser`` object
  250. ========================
  251. .. class:: models.AnonymousUser
  252. :class:`django.contrib.auth.models.AnonymousUser` is a class that
  253. implements the :class:`django.contrib.auth.models.User` interface, with
  254. these differences:
  255. * :ref:`id <automatic-primary-key-fields>` is always ``None``.
  256. * :attr:`~django.contrib.auth.models.User.username` is always the empty
  257. string.
  258. * :meth:`~django.contrib.auth.models.User.get_username()` always returns
  259. the empty string.
  260. * :attr:`~django.contrib.auth.models.User.is_anonymous` is ``True``
  261. instead of ``False``.
  262. * :attr:`~django.contrib.auth.models.User.is_authenticated` is
  263. ``False`` instead of ``True``.
  264. * :attr:`~django.contrib.auth.models.User.is_staff` and
  265. :attr:`~django.contrib.auth.models.User.is_superuser` are always
  266. ``False``.
  267. * :attr:`~django.contrib.auth.models.User.is_active` is always ``False``.
  268. * :attr:`~django.contrib.auth.models.User.groups` and
  269. :attr:`~django.contrib.auth.models.User.user_permissions` are always
  270. empty.
  271. * :meth:`~django.contrib.auth.models.User.set_password()`,
  272. :meth:`~django.contrib.auth.models.User.check_password()`,
  273. :meth:`~django.db.models.Model.save` and
  274. :meth:`~django.db.models.Model.delete()` raise :exc:`NotImplementedError`.
  275. In practice, you probably won't need to use
  276. :class:`~django.contrib.auth.models.AnonymousUser` objects on your own, but
  277. they're used by web requests, as explained in the next section.
  278. ``Permission`` model
  279. ====================
  280. .. class:: models.Permission
  281. Fields
  282. ------
  283. :class:`~django.contrib.auth.models.Permission` objects have the following
  284. fields:
  285. .. class:: models.Permission
  286. :noindex:
  287. .. attribute:: name
  288. Required. 255 characters or fewer. Example: ``'Can vote'``.
  289. .. attribute:: content_type
  290. Required. A reference to the ``django_content_type`` database table,
  291. which contains a record for each installed model.
  292. .. attribute:: codename
  293. Required. 100 characters or fewer. Example: ``'can_vote'``.
  294. Methods
  295. -------
  296. :class:`~django.contrib.auth.models.Permission` objects have the standard
  297. data-access methods like any other :doc:`Django model </ref/models/instances>`.
  298. ``Group`` model
  299. ===============
  300. .. class:: models.Group
  301. Fields
  302. ------
  303. :class:`~django.contrib.auth.models.Group` objects have the following fields:
  304. .. class:: models.Group
  305. :noindex:
  306. .. attribute:: name
  307. Required. 150 characters or fewer. Any characters are permitted.
  308. Example: ``'Awesome Users'``.
  309. .. attribute:: permissions
  310. Many-to-many field to :class:`~django.contrib.auth.models.Permission`::
  311. group.permissions.set([permission_list])
  312. group.permissions.add(permission, permission, ...)
  313. group.permissions.remove(permission, permission, ...)
  314. group.permissions.clear()
  315. Validators
  316. ==========
  317. .. class:: validators.ASCIIUsernameValidator
  318. A field validator allowing only ASCII letters and numbers, in addition to
  319. ``@``, ``.``, ``+``, ``-``, and ``_``.
  320. .. class:: validators.UnicodeUsernameValidator
  321. A field validator allowing Unicode characters, in addition to ``@``, ``.``,
  322. ``+``, ``-``, and ``_``. The default validator for ``User.username``.
  323. .. _topics-auth-signals:
  324. Login and logout signals
  325. ========================
  326. .. module:: django.contrib.auth.signals
  327. The auth framework uses the following :doc:`signals </topics/signals>` that
  328. can be used for notification when a user logs in or out.
  329. .. data:: user_logged_in
  330. Sent when a user logs in successfully.
  331. Arguments sent with this signal:
  332. ``sender``
  333. The class of the user that just logged in.
  334. ``request``
  335. The current :class:`~django.http.HttpRequest` instance.
  336. ``user``
  337. The user instance that just logged in.
  338. .. data:: user_logged_out
  339. Sent when the logout method is called.
  340. ``sender``
  341. As above: the class of the user that just logged out or ``None``
  342. if the user was not authenticated.
  343. ``request``
  344. The current :class:`~django.http.HttpRequest` instance.
  345. ``user``
  346. The user instance that just logged out or ``None`` if the
  347. user was not authenticated.
  348. .. data:: user_login_failed
  349. Sent when the user failed to login successfully
  350. ``sender``
  351. The name of the module used for authentication.
  352. ``credentials``
  353. A dictionary of keyword arguments containing the user credentials that were
  354. passed to :func:`~django.contrib.auth.authenticate()` or your own custom
  355. authentication backend. Credentials matching a set of 'sensitive' patterns,
  356. (including password) will not be sent in the clear as part of the signal.
  357. ``request``
  358. The :class:`~django.http.HttpRequest` object, if one was provided to
  359. :func:`~django.contrib.auth.authenticate`.
  360. .. _authentication-backends-reference:
  361. Authentication backends
  362. =======================
  363. .. module:: django.contrib.auth.backends
  364. :synopsis: Django's built-in authentication backend classes.
  365. This section details the authentication backends that come with Django. For
  366. information on how to use them and how to write your own authentication
  367. backends, see the :ref:`Other authentication sources section
  368. <authentication-backends>` of the :doc:`User authentication guide
  369. </topics/auth/index>`.
  370. Available authentication backends
  371. ---------------------------------
  372. The following backends are available in :mod:`django.contrib.auth.backends`:
  373. .. class:: BaseBackend
  374. A base class that provides default implementations for all required
  375. methods. By default, it will reject any user and provide no permissions.
  376. .. method:: get_user_permissions(user_obj, obj=None)
  377. .. method:: aget_user_permissions(user_obj, obj=None)
  378. *Asynchronous version*: ``aget_user_permissions()``
  379. Returns an empty set.
  380. .. versionchanged:: 5.2
  381. ``aget_user_permissions()`` function was added.
  382. .. method:: get_group_permissions(user_obj, obj=None)
  383. .. method:: aget_group_permissions(user_obj, obj=None)
  384. *Asynchronous version*: ``aget_group_permissions()``
  385. Returns an empty set.
  386. .. versionchanged:: 5.2
  387. ``aget_group_permissions()`` function was added.
  388. .. method:: get_all_permissions(user_obj, obj=None)
  389. .. method:: aget_all_permissions(user_obj, obj=None)
  390. *Asynchronous version*: ``aget_all_permissions()``
  391. Uses :meth:`get_user_permissions` and :meth:`get_group_permissions` to
  392. get the set of permission strings the ``user_obj`` has.
  393. .. versionchanged:: 5.2
  394. ``aget_all_permissions()`` function was added.
  395. .. method:: has_perm(user_obj, perm, obj=None)
  396. .. method:: ahas_perm(user_obj, perm, obj=None)
  397. *Asynchronous version*: ``ahas_perm()``
  398. Uses :meth:`get_all_permissions` to check if ``user_obj`` has the
  399. permission string ``perm``.
  400. .. versionchanged:: 5.2
  401. ``ahas_perm()`` function was added.
  402. .. class:: ModelBackend
  403. This is the default authentication backend used by Django. It
  404. authenticates using credentials consisting of a user identifier and
  405. password. For Django's default user model, the user identifier is the
  406. username, for custom user models it is the field specified by
  407. USERNAME_FIELD (see :doc:`Customizing Users and authentication
  408. </topics/auth/customizing>`).
  409. It also handles the default permissions model as defined for
  410. :class:`~django.contrib.auth.models.User` and
  411. :class:`~django.contrib.auth.models.PermissionsMixin`.
  412. :meth:`has_perm`, :meth:`get_all_permissions`, :meth:`get_user_permissions`,
  413. and :meth:`get_group_permissions` allow an object to be passed as a
  414. parameter for object-specific permissions, but this backend does not
  415. implement them other than returning an empty set of permissions if
  416. ``obj is not None``.
  417. :meth:`with_perm` also allows an object to be passed as a parameter, but
  418. unlike others methods it returns an empty queryset if ``obj is not None``.
  419. .. method:: authenticate(request, username=None, password=None, **kwargs)
  420. .. method:: aauthenticate(request, username=None, password=None, **kwargs)
  421. *Asynchronous version*: ``aauthenticate()``
  422. Tries to authenticate ``username`` with ``password`` by calling
  423. :meth:`User.check_password
  424. <django.contrib.auth.models.User.check_password>`. If no ``username``
  425. is provided, it tries to fetch a username from ``kwargs`` using the
  426. key :attr:`CustomUser.USERNAME_FIELD
  427. <django.contrib.auth.models.CustomUser.USERNAME_FIELD>`. Returns an
  428. authenticated user or ``None``.
  429. ``request`` is an :class:`~django.http.HttpRequest` and may be ``None``
  430. if it wasn't provided to :func:`~django.contrib.auth.authenticate`
  431. (which passes it on to the backend).
  432. .. versionchanged:: 5.2
  433. ``aauthenticate()`` function was added.
  434. .. method:: get_user_permissions(user_obj, obj=None)
  435. .. method:: aget_user_permissions(user_obj, obj=None)
  436. *Asynchronous version*: ``aget_user_permissions()``
  437. Returns the set of permission strings the ``user_obj`` has from their
  438. own user permissions. Returns an empty set if
  439. :attr:`~django.contrib.auth.models.AbstractBaseUser.is_anonymous` or
  440. :attr:`~django.contrib.auth.models.CustomUser.is_active` is ``False``.
  441. .. versionchanged:: 5.2
  442. ``aget_user_permissions()`` function was added.
  443. .. method:: get_group_permissions(user_obj, obj=None)
  444. .. method:: aget_group_permissions(user_obj, obj=None)
  445. *Asynchronous version*: ``aget_group_permissions()``
  446. Returns the set of permission strings the ``user_obj`` has from the
  447. permissions of the groups they belong. Returns an empty set if
  448. :attr:`~django.contrib.auth.models.AbstractBaseUser.is_anonymous` or
  449. :attr:`~django.contrib.auth.models.CustomUser.is_active` is ``False``.
  450. .. versionchanged:: 5.2
  451. ``aget_group_permissions()`` function was added.
  452. .. method:: get_all_permissions(user_obj, obj=None)
  453. .. method:: aget_all_permissions(user_obj, obj=None)
  454. *Asynchronous version*: ``aget_all_permissions()``
  455. Returns the set of permission strings the ``user_obj`` has, including both
  456. user permissions and group permissions. Returns an empty set if
  457. :attr:`~django.contrib.auth.models.AbstractBaseUser.is_anonymous` or
  458. :attr:`~django.contrib.auth.models.CustomUser.is_active` is ``False``.
  459. .. versionchanged:: 5.2
  460. ``aget_all_permissions()`` function was added.
  461. .. method:: has_perm(user_obj, perm, obj=None)
  462. .. method:: ahas_perm(user_obj, perm, obj=None)
  463. *Asynchronous version*: ``ahas_perm()``
  464. Uses :meth:`get_all_permissions` to check if ``user_obj`` has the
  465. permission string ``perm``. Returns ``False`` if the user is not
  466. :attr:`~django.contrib.auth.models.CustomUser.is_active`.
  467. .. versionchanged:: 5.2
  468. ``ahas_perm()`` function was added.
  469. .. method:: has_module_perms(user_obj, app_label)
  470. .. method:: ahas_module_perms(user_obj, app_label)
  471. *Asynchronous version*: ``ahas_module_perms()``
  472. Returns whether the ``user_obj`` has any permissions on the app
  473. ``app_label``.
  474. .. versionchanged:: 5.2
  475. ``ahas_module_perms()`` function was added.
  476. .. method:: user_can_authenticate()
  477. Returns whether the user is allowed to authenticate. To match the
  478. behavior of :class:`~django.contrib.auth.forms.AuthenticationForm`
  479. which :meth:`prohibits inactive users from logging in
  480. <django.contrib.auth.forms.AuthenticationForm.confirm_login_allowed>`,
  481. this method returns ``False`` for users with :attr:`is_active=False
  482. <django.contrib.auth.models.User.is_active>`. Custom user models that
  483. don't have an :attr:`~django.contrib.auth.models.CustomUser.is_active`
  484. field are allowed.
  485. .. method:: with_perm(perm, is_active=True, include_superusers=True, obj=None)
  486. Returns all active users who have the permission ``perm`` either in
  487. the form of ``"<app label>.<permission codename>"`` or a
  488. :class:`~django.contrib.auth.models.Permission` instance. Returns an
  489. empty queryset if no users who have the ``perm`` found.
  490. If ``is_active`` is ``True`` (default), returns only active users, or
  491. if ``False``, returns only inactive users. Use ``None`` to return all
  492. users irrespective of active state.
  493. If ``include_superusers`` is ``True`` (default), the result will
  494. include superusers.
  495. .. class:: AllowAllUsersModelBackend
  496. Same as :class:`ModelBackend` except that it doesn't reject inactive users
  497. because :meth:`~ModelBackend.user_can_authenticate` always returns ``True``.
  498. When using this backend, you'll likely want to customize the
  499. :class:`~django.contrib.auth.forms.AuthenticationForm` used by the
  500. :class:`~django.contrib.auth.views.LoginView` by overriding the
  501. :meth:`~django.contrib.auth.forms.AuthenticationForm.confirm_login_allowed`
  502. method as it rejects inactive users.
  503. .. class:: RemoteUserBackend
  504. Use this backend to take advantage of external-to-Django-handled
  505. authentication. It authenticates using usernames passed in
  506. :attr:`request.META['REMOTE_USER'] <django.http.HttpRequest.META>`. See
  507. the :doc:`Authenticating against REMOTE_USER </howto/auth-remote-user>`
  508. documentation.
  509. If you need more control, you can create your own authentication backend
  510. that inherits from this class and override these attributes or methods:
  511. .. attribute:: create_unknown_user
  512. ``True`` or ``False``. Determines whether or not a user object is
  513. created if not already in the database Defaults to ``True``.
  514. .. method:: authenticate(request, remote_user)
  515. .. method:: aauthenticate(request, remote_user)
  516. *Asynchronous version*: ``aauthenticate()``
  517. The username passed as ``remote_user`` is considered trusted. This
  518. method returns the user object with the given username, creating a new
  519. user object if :attr:`~RemoteUserBackend.create_unknown_user` is
  520. ``True``.
  521. Returns ``None`` if :attr:`~RemoteUserBackend.create_unknown_user` is
  522. ``False`` and a ``User`` object with the given username is not found in
  523. the database.
  524. ``request`` is an :class:`~django.http.HttpRequest` and may be ``None``
  525. if it wasn't provided to :func:`~django.contrib.auth.authenticate`
  526. (which passes it on to the backend).
  527. .. versionchanged:: 5.2
  528. ``aauthenticate()`` function was added.
  529. .. method:: clean_username(username)
  530. Performs any cleaning on the ``username`` (e.g. stripping LDAP DN
  531. information) prior to using it to get or create a user object. Returns
  532. the cleaned username.
  533. .. method:: configure_user(request, user, created=True)
  534. .. method:: aconfigure_user(request, user, created=True)
  535. *Asynchronous version*: ``aconfigure_user()``
  536. Configures the user on each authentication attempt. This method is
  537. called immediately after fetching or creating the user being
  538. authenticated, and can be used to perform custom setup actions, such as
  539. setting the user's groups based on attributes in an LDAP directory.
  540. Returns the user object. When fetching or creating an user is called
  541. from a synchronous context, ``configure_user`` is called,
  542. ``aconfigure_user`` is called from async contexts.
  543. The setup can be performed either once when the user is created
  544. (``created`` is ``True``) or on existing users (``created`` is
  545. ``False``) as a way of synchronizing attributes between the remote and
  546. the local systems.
  547. ``request`` is an :class:`~django.http.HttpRequest` and may be ``None``
  548. if it wasn't provided to :func:`~django.contrib.auth.authenticate`
  549. (which passes it on to the backend).
  550. .. versionchanged:: 5.2
  551. ``aconfigure_user()`` function was added.
  552. .. method:: user_can_authenticate()
  553. Returns whether the user is allowed to authenticate. This method
  554. returns ``False`` for users with :attr:`is_active=False
  555. <django.contrib.auth.models.User.is_active>`. Custom user models that
  556. don't have an :attr:`~django.contrib.auth.models.CustomUser.is_active`
  557. field are allowed.
  558. .. class:: AllowAllUsersRemoteUserBackend
  559. Same as :class:`RemoteUserBackend` except that it doesn't reject inactive
  560. users because :attr:`~RemoteUserBackend.user_can_authenticate` always
  561. returns ``True``.
  562. Utility functions
  563. =================
  564. .. currentmodule:: django.contrib.auth
  565. .. function:: get_user(request)
  566. .. function:: aget_user(request)
  567. *Asynchronous version*: ``aget_user()``
  568. Returns the user model instance associated with the given ``request``’s
  569. session.
  570. It checks if the authentication backend stored in the session is present in
  571. :setting:`AUTHENTICATION_BACKENDS`. If so, it uses the backend's
  572. ``get_user()`` method to retrieve the user model instance and then verifies
  573. the session by calling the user model's
  574. :meth:`~django.contrib.auth.models.AbstractBaseUser.get_session_auth_hash`
  575. method. If the verification fails and :setting:`SECRET_KEY_FALLBACKS` are
  576. provided, it verifies the session against each fallback key using
  577. :meth:`~django.contrib.auth.models.AbstractBaseUser.\
  578. get_session_auth_fallback_hash`.
  579. Returns an instance of :class:`~django.contrib.auth.models.AnonymousUser`
  580. if the authentication backend stored in the session is no longer in
  581. :setting:`AUTHENTICATION_BACKENDS`, if a user isn't returned by the
  582. backend's ``get_user()`` method, or if the session auth hash doesn't
  583. validate.