Funktionierender Prototyp des Serious Games zur Vermittlung von Wissen zu Software-Engineering-Arbeitsmodellen.
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 9.1KB

1 year ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250
  1. import warnings
  2. from django.contrib.auth import get_user_model
  3. from django.contrib.auth.models import Permission
  4. from django.db.models import Exists, OuterRef, Q
  5. from django.utils.deprecation import RemovedInDjango50Warning
  6. from django.utils.inspect import func_supports_parameter
  7. UserModel = get_user_model()
  8. class BaseBackend:
  9. def authenticate(self, request, **kwargs):
  10. return None
  11. def get_user(self, user_id):
  12. return None
  13. def get_user_permissions(self, user_obj, obj=None):
  14. return set()
  15. def get_group_permissions(self, user_obj, obj=None):
  16. return set()
  17. def get_all_permissions(self, user_obj, obj=None):
  18. return {
  19. *self.get_user_permissions(user_obj, obj=obj),
  20. *self.get_group_permissions(user_obj, obj=obj),
  21. }
  22. def has_perm(self, user_obj, perm, obj=None):
  23. return perm in self.get_all_permissions(user_obj, obj=obj)
  24. class ModelBackend(BaseBackend):
  25. """
  26. Authenticates against settings.AUTH_USER_MODEL.
  27. """
  28. def authenticate(self, request, username=None, password=None, **kwargs):
  29. if username is None:
  30. username = kwargs.get(UserModel.USERNAME_FIELD)
  31. if username is None or password is None:
  32. return
  33. try:
  34. user = UserModel._default_manager.get_by_natural_key(username)
  35. except UserModel.DoesNotExist:
  36. # Run the default password hasher once to reduce the timing
  37. # difference between an existing and a nonexistent user (#20760).
  38. UserModel().set_password(password)
  39. else:
  40. if user.check_password(password) and self.user_can_authenticate(user):
  41. return user
  42. def user_can_authenticate(self, user):
  43. """
  44. Reject users with is_active=False. Custom user models that don't have
  45. that attribute are allowed.
  46. """
  47. is_active = getattr(user, "is_active", None)
  48. return is_active or is_active is None
  49. def _get_user_permissions(self, user_obj):
  50. return user_obj.user_permissions.all()
  51. def _get_group_permissions(self, user_obj):
  52. user_groups_field = get_user_model()._meta.get_field("groups")
  53. user_groups_query = "group__%s" % user_groups_field.related_query_name()
  54. return Permission.objects.filter(**{user_groups_query: user_obj})
  55. def _get_permissions(self, user_obj, obj, from_name):
  56. """
  57. Return the permissions of `user_obj` from `from_name`. `from_name` can
  58. be either "group" or "user" to return permissions from
  59. `_get_group_permissions` or `_get_user_permissions` respectively.
  60. """
  61. if not user_obj.is_active or user_obj.is_anonymous or obj is not None:
  62. return set()
  63. perm_cache_name = "_%s_perm_cache" % from_name
  64. if not hasattr(user_obj, perm_cache_name):
  65. if user_obj.is_superuser:
  66. perms = Permission.objects.all()
  67. else:
  68. perms = getattr(self, "_get_%s_permissions" % from_name)(user_obj)
  69. perms = perms.values_list("content_type__app_label", "codename").order_by()
  70. setattr(
  71. user_obj, perm_cache_name, {"%s.%s" % (ct, name) for ct, name in perms}
  72. )
  73. return getattr(user_obj, perm_cache_name)
  74. def get_user_permissions(self, user_obj, obj=None):
  75. """
  76. Return a set of permission strings the user `user_obj` has from their
  77. `user_permissions`.
  78. """
  79. return self._get_permissions(user_obj, obj, "user")
  80. def get_group_permissions(self, user_obj, obj=None):
  81. """
  82. Return a set of permission strings the user `user_obj` has from the
  83. groups they belong.
  84. """
  85. return self._get_permissions(user_obj, obj, "group")
  86. def get_all_permissions(self, user_obj, obj=None):
  87. if not user_obj.is_active or user_obj.is_anonymous or obj is not None:
  88. return set()
  89. if not hasattr(user_obj, "_perm_cache"):
  90. user_obj._perm_cache = super().get_all_permissions(user_obj)
  91. return user_obj._perm_cache
  92. def has_perm(self, user_obj, perm, obj=None):
  93. return user_obj.is_active and super().has_perm(user_obj, perm, obj=obj)
  94. def has_module_perms(self, user_obj, app_label):
  95. """
  96. Return True if user_obj has any permissions in the given app_label.
  97. """
  98. return user_obj.is_active and any(
  99. perm[: perm.index(".")] == app_label
  100. for perm in self.get_all_permissions(user_obj)
  101. )
  102. def with_perm(self, perm, is_active=True, include_superusers=True, obj=None):
  103. """
  104. Return users that have permission "perm". By default, filter out
  105. inactive users and include superusers.
  106. """
  107. if isinstance(perm, str):
  108. try:
  109. app_label, codename = perm.split(".")
  110. except ValueError:
  111. raise ValueError(
  112. "Permission name should be in the form "
  113. "app_label.permission_codename."
  114. )
  115. elif not isinstance(perm, Permission):
  116. raise TypeError(
  117. "The `perm` argument must be a string or a permission instance."
  118. )
  119. if obj is not None:
  120. return UserModel._default_manager.none()
  121. permission_q = Q(group__user=OuterRef("pk")) | Q(user=OuterRef("pk"))
  122. if isinstance(perm, Permission):
  123. permission_q &= Q(pk=perm.pk)
  124. else:
  125. permission_q &= Q(codename=codename, content_type__app_label=app_label)
  126. user_q = Exists(Permission.objects.filter(permission_q))
  127. if include_superusers:
  128. user_q |= Q(is_superuser=True)
  129. if is_active is not None:
  130. user_q &= Q(is_active=is_active)
  131. return UserModel._default_manager.filter(user_q)
  132. def get_user(self, user_id):
  133. try:
  134. user = UserModel._default_manager.get(pk=user_id)
  135. except UserModel.DoesNotExist:
  136. return None
  137. return user if self.user_can_authenticate(user) else None
  138. class AllowAllUsersModelBackend(ModelBackend):
  139. def user_can_authenticate(self, user):
  140. return True
  141. class RemoteUserBackend(ModelBackend):
  142. """
  143. This backend is to be used in conjunction with the ``RemoteUserMiddleware``
  144. found in the middleware module of this package, and is used when the server
  145. is handling authentication outside of Django.
  146. By default, the ``authenticate`` method creates ``User`` objects for
  147. usernames that don't already exist in the database. Subclasses can disable
  148. this behavior by setting the ``create_unknown_user`` attribute to
  149. ``False``.
  150. """
  151. # Create a User object if not already in the database?
  152. create_unknown_user = True
  153. def authenticate(self, request, remote_user):
  154. """
  155. The username passed as ``remote_user`` is considered trusted. Return
  156. the ``User`` object with the given username. Create a new ``User``
  157. object if ``create_unknown_user`` is ``True``.
  158. Return None if ``create_unknown_user`` is ``False`` and a ``User``
  159. object with the given username is not found in the database.
  160. """
  161. if not remote_user:
  162. return
  163. created = False
  164. user = None
  165. username = self.clean_username(remote_user)
  166. # Note that this could be accomplished in one try-except clause, but
  167. # instead we use get_or_create when creating unknown users since it has
  168. # built-in safeguards for multiple threads.
  169. if self.create_unknown_user:
  170. user, created = UserModel._default_manager.get_or_create(
  171. **{UserModel.USERNAME_FIELD: username}
  172. )
  173. else:
  174. try:
  175. user = UserModel._default_manager.get_by_natural_key(username)
  176. except UserModel.DoesNotExist:
  177. pass
  178. # RemovedInDjango50Warning: When the deprecation ends, replace with:
  179. # user = self.configure_user(request, user, created=created)
  180. if func_supports_parameter(self.configure_user, "created"):
  181. user = self.configure_user(request, user, created=created)
  182. else:
  183. warnings.warn(
  184. f"`created=True` must be added to the signature of "
  185. f"{self.__class__.__qualname__}.configure_user().",
  186. category=RemovedInDjango50Warning,
  187. )
  188. if created:
  189. user = self.configure_user(request, user)
  190. return user if self.user_can_authenticate(user) else None
  191. def clean_username(self, username):
  192. """
  193. Perform any cleaning on the "username" prior to using it to get or
  194. create the user object. Return the cleaned username.
  195. By default, return the username unchanged.
  196. """
  197. return username
  198. def configure_user(self, request, user, created=True):
  199. """
  200. Configure a user and return the updated user.
  201. By default, return the user unmodified.
  202. """
  203. return user
  204. class AllowAllUsersRemoteUserBackend(RemoteUserBackend):
  205. def user_can_authenticate(self, user):
  206. return True