backends.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272
  1. # Copyright (C) 2010-2012 Yaco Sistemas (http://www.yaco.es)
  2. # Copyright (C) 2009 Lorenzo Gil Sanchez <lorenzo.gil.sanchez@gmail.com>
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. import logging
  16. from django.conf import settings
  17. from django.contrib import auth
  18. from django.contrib.auth.backends import ModelBackend
  19. from django.core.exceptions import (
  20. MultipleObjectsReturned, ImproperlyConfigured,
  21. )
  22. from djangosaml2.signals import pre_user_save
  23. logger = logging.getLogger('djangosaml2')
  24. def get_model(model_path):
  25. try:
  26. from django.apps import apps
  27. return apps.get_model(model_path)
  28. except ImportError:
  29. # Django < 1.7 (cannot use the new app loader)
  30. from django.db.models import get_model as django_get_model
  31. try:
  32. app_label, model_name = model_path.split('.')
  33. except ValueError:
  34. raise ImproperlyConfigured("SAML_USER_MODEL must be of the form "
  35. "'app_label.model_name'")
  36. user_model = django_get_model(app_label, model_name)
  37. if user_model is None:
  38. raise ImproperlyConfigured("SAML_USER_MODEL refers to model '%s' "
  39. "that has not been installed" % model_path)
  40. return user_model
  41. def get_saml_user_model():
  42. try:
  43. # djangosaml2 custom user model
  44. return get_model(settings.SAML_USER_MODEL)
  45. except AttributeError:
  46. try:
  47. # Django 1.5 Custom user model
  48. return auth.get_user_model()
  49. except AttributeError:
  50. return auth.models.User
  51. class Saml2Backend(ModelBackend):
  52. def authenticate(self, request, session_info=None, attribute_mapping=None,
  53. create_unknown_user=True, **kwargs):
  54. if session_info is None or attribute_mapping is None:
  55. logger.info('Session info or attribute mapping are None')
  56. return None
  57. if 'ava' not in session_info:
  58. logger.error('"ava" key not found in session_info')
  59. return None
  60. attributes = self.clean_attributes(session_info['ava'])
  61. if not attributes:
  62. logger.error('The attributes dictionary is empty')
  63. use_name_id_as_username = getattr(
  64. settings, 'SAML_USE_NAME_ID_AS_USERNAME', False)
  65. django_user_main_attribute = self.get_django_user_main_attribute()
  66. logger.debug('attributes: %s', attributes)
  67. saml_user = None
  68. if use_name_id_as_username:
  69. if 'name_id' in session_info:
  70. logger.debug('name_id: %s', session_info['name_id'])
  71. saml_user = session_info['name_id'].text
  72. else:
  73. logger.error('The nameid is not available. Cannot find user without a nameid.')
  74. else:
  75. saml_user = self.get_attribute_value(django_user_main_attribute, attributes, attribute_mapping)
  76. if saml_user is None:
  77. logger.error('Could not find saml_user value')
  78. return None
  79. if not self.is_authorized(attributes, attribute_mapping):
  80. return None
  81. main_attribute = self.clean_user_main_attribute(saml_user)
  82. # Note that this could be accomplished in one try-except clause, but
  83. # instead we use get_or_create when creating unknown users since it has
  84. # built-in safeguards for multiple threads.
  85. return self.get_saml2_user(
  86. create_unknown_user, main_attribute, attributes, attribute_mapping)
  87. def get_attribute_value(self, django_field, attributes, attribute_mapping):
  88. saml_user = None
  89. logger.debug('attribute_mapping: %s', attribute_mapping)
  90. for saml_attr, django_fields in attribute_mapping.items():
  91. if django_field in django_fields and saml_attr in attributes:
  92. saml_user = attributes[saml_attr][0]
  93. return saml_user
  94. def is_authorized(self, attributes, attribute_mapping):
  95. """Hook to allow custom authorization policies based on
  96. SAML attributes.
  97. """
  98. return True
  99. def clean_attributes(self, attributes):
  100. """Hook to clean attributes from the SAML response."""
  101. return attributes
  102. def clean_user_main_attribute(self, main_attribute):
  103. """Performs any cleaning on the user main attribute (which
  104. usually is "username") prior to using it to get or
  105. create the user object. Returns the cleaned attribute.
  106. By default, returns the attribute unchanged.
  107. """
  108. return main_attribute
  109. def get_django_user_main_attribute(self):
  110. return getattr(
  111. settings,
  112. 'SAML_DJANGO_USER_MAIN_ATTRIBUTE',
  113. getattr(get_saml_user_model(), 'USERNAME_FIELD', 'username'))
  114. def get_django_user_main_attribute_lookup(self):
  115. return getattr(settings, 'SAML_DJANGO_USER_MAIN_ATTRIBUTE_LOOKUP', '')
  116. def get_user_query_args(self, main_attribute):
  117. lookup = (self.get_django_user_main_attribute() +
  118. self.get_django_user_main_attribute_lookup())
  119. return {lookup: main_attribute}
  120. def get_saml2_user(self, create, main_attribute, attributes, attribute_mapping):
  121. if create:
  122. return self._get_or_create_saml2_user(main_attribute, attributes, attribute_mapping)
  123. return self._get_saml2_user(main_attribute, attributes, attribute_mapping)
  124. def _get_or_create_saml2_user(self, main_attribute, attributes, attribute_mapping):
  125. logger.debug('Check if the user "%s" exists or create otherwise',
  126. main_attribute)
  127. django_user_main_attribute = self.get_django_user_main_attribute()
  128. user_query_args = self.get_user_query_args(main_attribute)
  129. user_create_defaults = {django_user_main_attribute: main_attribute}
  130. User = get_saml_user_model()
  131. try:
  132. user, created = User.objects.get_or_create(
  133. defaults=user_create_defaults, **user_query_args)
  134. except MultipleObjectsReturned:
  135. logger.error("There are more than one user with %s = %s",
  136. django_user_main_attribute, main_attribute)
  137. return None
  138. if created:
  139. logger.debug('New user created')
  140. user = self.configure_user(user, attributes, attribute_mapping)
  141. else:
  142. logger.debug('User updated')
  143. user = self.update_user(user, attributes, attribute_mapping)
  144. return user
  145. def _get_saml2_user(self, main_attribute, attributes, attribute_mapping):
  146. User = get_saml_user_model()
  147. django_user_main_attribute = self.get_django_user_main_attribute()
  148. user_query_args = self.get_user_query_args(main_attribute)
  149. logger.debug('Retrieving existing user "%s"', main_attribute)
  150. try:
  151. user = User.objects.get(**user_query_args)
  152. user = self.update_user(user, attributes, attribute_mapping)
  153. except User.DoesNotExist:
  154. logger.error('The user "%s" does not exist, searched %s', main_attribute, django_user_main_attribute)
  155. return None
  156. except MultipleObjectsReturned:
  157. logger.error("There are more than one user with %s = %s",
  158. django_user_main_attribute, main_attribute)
  159. return None
  160. return user
  161. def configure_user(self, user, attributes, attribute_mapping):
  162. """Configures a user after creation and returns the updated user.
  163. By default, returns the user with his attributes updated.
  164. """
  165. user.set_unusable_password()
  166. return self.update_user(user, attributes, attribute_mapping,
  167. force_save=True)
  168. def update_user(self, user, attributes, attribute_mapping,
  169. force_save=False):
  170. """Update a user with a set of attributes and returns the updated user.
  171. By default it uses a mapping defined in the settings constant
  172. SAML_ATTRIBUTE_MAPPING. For each attribute, if the user object has
  173. that field defined it will be set.
  174. """
  175. if not attribute_mapping:
  176. return user
  177. user_modified = False
  178. for saml_attr, django_attrs in attribute_mapping.items():
  179. attr_value_list = attributes.get(saml_attr)
  180. if not attr_value_list:
  181. logger.debug(
  182. 'Could not find value for "%s", not updating fields "%s"',
  183. saml_attr, django_attrs)
  184. continue
  185. for attr in django_attrs:
  186. if hasattr(user, attr):
  187. user_attr = getattr(user, attr)
  188. if callable(user_attr):
  189. modified = user_attr(attr_value_list)
  190. else:
  191. modified = self._set_attribute(user, attr, attr_value_list[0])
  192. user_modified = user_modified or modified
  193. else:
  194. logger.debug(
  195. 'Could not find attribute "%s" on user "%s"', attr, user)
  196. logger.debug('Sending the pre_save signal')
  197. signal_modified = any(
  198. [response for receiver, response
  199. in pre_user_save.send_robust(sender=user.__class__,
  200. instance=user,
  201. attributes=attributes,
  202. user_modified=user_modified)]
  203. )
  204. if user_modified or signal_modified or force_save:
  205. user.save()
  206. return user
  207. def _set_attribute(self, obj, attr, value):
  208. """Set an attribute of an object to a specific value.
  209. Return True if the attribute was changed and False otherwise.
  210. """
  211. field = obj._meta.get_field(attr)
  212. if field.max_length is not None and len(value) > field.max_length:
  213. cleaned_value = value[:field.max_length]
  214. logger.warn('The attribute "%s" was trimmed from "%s" to "%s"',
  215. attr, value, cleaned_value)
  216. else:
  217. cleaned_value = value
  218. old_value = getattr(obj, attr)
  219. if cleaned_value != old_value:
  220. setattr(obj, attr, cleaned_value)
  221. return True
  222. return False