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.
 
 
 
 

161 lines
6.0 KiB

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