You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

backends.py 7.0KB

5 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188
  1. import inspect
  2. import warnings
  3. from django.contrib.auth import get_user_model
  4. from django.contrib.auth.models import Permission
  5. from django.utils.deprecation import RemovedInDjango31Warning
  6. UserModel = get_user_model()
  7. class ModelBackend:
  8. """
  9. Authenticates against settings.AUTH_USER_MODEL.
  10. """
  11. def authenticate(self, request, username=None, password=None, **kwargs):
  12. if username is None:
  13. username = kwargs.get(UserModel.USERNAME_FIELD)
  14. try:
  15. user = UserModel._default_manager.get_by_natural_key(username)
  16. except UserModel.DoesNotExist:
  17. # Run the default password hasher once to reduce the timing
  18. # difference between an existing and a nonexistent user (#20760).
  19. UserModel().set_password(password)
  20. else:
  21. if user.check_password(password) and self.user_can_authenticate(user):
  22. return user
  23. def user_can_authenticate(self, user):
  24. """
  25. Reject users with is_active=False. Custom user models that don't have
  26. that attribute are allowed.
  27. """
  28. is_active = getattr(user, 'is_active', None)
  29. return is_active or is_active is None
  30. def _get_user_permissions(self, user_obj):
  31. return user_obj.user_permissions.all()
  32. def _get_group_permissions(self, user_obj):
  33. user_groups_field = get_user_model()._meta.get_field('groups')
  34. user_groups_query = 'group__%s' % user_groups_field.related_query_name()
  35. return Permission.objects.filter(**{user_groups_query: user_obj})
  36. def _get_permissions(self, user_obj, obj, from_name):
  37. """
  38. Return the permissions of `user_obj` from `from_name`. `from_name` can
  39. be either "group" or "user" to return permissions from
  40. `_get_group_permissions` or `_get_user_permissions` respectively.
  41. """
  42. if not user_obj.is_active or user_obj.is_anonymous or obj is not None:
  43. return set()
  44. perm_cache_name = '_%s_perm_cache' % from_name
  45. if not hasattr(user_obj, perm_cache_name):
  46. if user_obj.is_superuser:
  47. perms = Permission.objects.all()
  48. else:
  49. perms = getattr(self, '_get_%s_permissions' % from_name)(user_obj)
  50. perms = perms.values_list('content_type__app_label', 'codename').order_by()
  51. setattr(user_obj, perm_cache_name, {"%s.%s" % (ct, name) for ct, name in perms})
  52. return getattr(user_obj, perm_cache_name)
  53. def get_user_permissions(self, user_obj, obj=None):
  54. """
  55. Return a set of permission strings the user `user_obj` has from their
  56. `user_permissions`.
  57. """
  58. return self._get_permissions(user_obj, obj, 'user')
  59. def get_group_permissions(self, user_obj, obj=None):
  60. """
  61. Return a set of permission strings the user `user_obj` has from the
  62. groups they belong.
  63. """
  64. return self._get_permissions(user_obj, obj, 'group')
  65. def get_all_permissions(self, user_obj, obj=None):
  66. if not user_obj.is_active or user_obj.is_anonymous or obj is not None:
  67. return set()
  68. if not hasattr(user_obj, '_perm_cache'):
  69. user_obj._perm_cache = {
  70. *self.get_user_permissions(user_obj),
  71. *self.get_group_permissions(user_obj),
  72. }
  73. return user_obj._perm_cache
  74. def has_perm(self, user_obj, perm, obj=None):
  75. return user_obj.is_active and perm in self.get_all_permissions(user_obj, obj)
  76. def has_module_perms(self, user_obj, app_label):
  77. """
  78. Return True if user_obj has any permissions in the given app_label.
  79. """
  80. return user_obj.is_active and any(
  81. perm[:perm.index('.')] == app_label
  82. for perm in self.get_all_permissions(user_obj)
  83. )
  84. def get_user(self, user_id):
  85. try:
  86. user = UserModel._default_manager.get(pk=user_id)
  87. except UserModel.DoesNotExist:
  88. return None
  89. return user if self.user_can_authenticate(user) else None
  90. class AllowAllUsersModelBackend(ModelBackend):
  91. def user_can_authenticate(self, user):
  92. return True
  93. class RemoteUserBackend(ModelBackend):
  94. """
  95. This backend is to be used in conjunction with the ``RemoteUserMiddleware``
  96. found in the middleware module of this package, and is used when the server
  97. is handling authentication outside of Django.
  98. By default, the ``authenticate`` method creates ``User`` objects for
  99. usernames that don't already exist in the database. Subclasses can disable
  100. this behavior by setting the ``create_unknown_user`` attribute to
  101. ``False``.
  102. """
  103. # Create a User object if not already in the database?
  104. create_unknown_user = True
  105. def authenticate(self, request, remote_user):
  106. """
  107. The username passed as ``remote_user`` is considered trusted. Return
  108. the ``User`` object with the given username. Create a new ``User``
  109. object if ``create_unknown_user`` is ``True``.
  110. Return None if ``create_unknown_user`` is ``False`` and a ``User``
  111. object with the given username is not found in the database.
  112. """
  113. if not remote_user:
  114. return
  115. user = None
  116. username = self.clean_username(remote_user)
  117. # Note that this could be accomplished in one try-except clause, but
  118. # instead we use get_or_create when creating unknown users since it has
  119. # built-in safeguards for multiple threads.
  120. if self.create_unknown_user:
  121. user, created = UserModel._default_manager.get_or_create(**{
  122. UserModel.USERNAME_FIELD: username
  123. })
  124. if created:
  125. args = (request, user)
  126. try:
  127. inspect.getcallargs(self.configure_user, request, user)
  128. except TypeError:
  129. args = (user,)
  130. warnings.warn(
  131. 'Update %s.configure_user() to accept `request` as '
  132. 'the first argument.'
  133. % self.__class__.__name__, RemovedInDjango31Warning
  134. )
  135. user = self.configure_user(*args)
  136. else:
  137. try:
  138. user = UserModel._default_manager.get_by_natural_key(username)
  139. except UserModel.DoesNotExist:
  140. pass
  141. return user if self.user_can_authenticate(user) else None
  142. def clean_username(self, username):
  143. """
  144. Perform any cleaning on the "username" prior to using it to get or
  145. create the user object. Return the cleaned username.
  146. By default, return the username unchanged.
  147. """
  148. return username
  149. def configure_user(self, request, user):
  150. """
  151. Configure a user after creation and return the updated user.
  152. By default, return the user unmodified.
  153. """
  154. return user
  155. class AllowAllUsersRemoteUserBackend(RemoteUserBackend):
  156. def user_can_authenticate(self, user):
  157. return True