backends.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278
  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,
  76. attributes,
  77. attribute_mapping)
  78. if saml_user is None:
  79. logger.error('Could not find saml_user value')
  80. return None
  81. if not self.is_authorized(attributes, attribute_mapping):
  82. return None
  83. main_attribute = self.clean_user_main_attribute(saml_user)
  84. # Note that this could be accomplished in one try-except clause, but
  85. # instead we use get_or_create when creating unknown users since it has
  86. # built-in safeguards for multiple threads.
  87. return self.get_saml2_user(
  88. create_unknown_user, main_attribute, attributes, attribute_mapping)
  89. def get_attribute_value(self, django_field, attributes, attribute_mapping):
  90. saml_user = None
  91. logger.debug('attribute_mapping: %s', attribute_mapping)
  92. for saml_attr, django_fields in attribute_mapping.items():
  93. if django_field in django_fields and saml_attr in attributes:
  94. saml_user = attributes.get('saml_attr', [None])[0]
  95. if not saml_user:
  96. logger.error('attributes[saml_attr] attribute '
  97. 'value is missing. Probably the user '
  98. 'session is expired.')
  99. return saml_user
  100. def is_authorized(self, attributes, attribute_mapping):
  101. """Hook to allow custom authorization policies based on
  102. SAML attributes.
  103. """
  104. return True
  105. def clean_attributes(self, attributes):
  106. """Hook to clean attributes from the SAML response."""
  107. return attributes
  108. def clean_user_main_attribute(self, main_attribute):
  109. """Performs any cleaning on the user main attribute (which
  110. usually is "username") prior to using it to get or
  111. create the user object. Returns the cleaned attribute.
  112. By default, returns the attribute unchanged.
  113. """
  114. return main_attribute
  115. def get_django_user_main_attribute(self):
  116. return getattr(
  117. settings,
  118. 'SAML_DJANGO_USER_MAIN_ATTRIBUTE',
  119. getattr(get_saml_user_model(), 'USERNAME_FIELD', 'username'))
  120. def get_django_user_main_attribute_lookup(self):
  121. return getattr(settings, 'SAML_DJANGO_USER_MAIN_ATTRIBUTE_LOOKUP', '')
  122. def get_user_query_args(self, main_attribute):
  123. lookup = (self.get_django_user_main_attribute() +
  124. self.get_django_user_main_attribute_lookup())
  125. return {lookup: main_attribute}
  126. def get_saml2_user(self, create, main_attribute, attributes, attribute_mapping):
  127. if create:
  128. return self._get_or_create_saml2_user(main_attribute, attributes, attribute_mapping)
  129. return self._get_saml2_user(main_attribute, attributes, attribute_mapping)
  130. def _get_or_create_saml2_user(self, main_attribute, attributes, attribute_mapping):
  131. logger.debug('Check if the user "%s" exists or create otherwise',
  132. main_attribute)
  133. django_user_main_attribute = self.get_django_user_main_attribute()
  134. user_query_args = self.get_user_query_args(main_attribute)
  135. user_create_defaults = {django_user_main_attribute: main_attribute}
  136. User = get_saml_user_model()
  137. try:
  138. user, created = User.objects.get_or_create(
  139. defaults=user_create_defaults, **user_query_args)
  140. except MultipleObjectsReturned:
  141. logger.error("There are more than one user with %s = %s",
  142. django_user_main_attribute, main_attribute)
  143. return None
  144. if created:
  145. logger.debug('New user created')
  146. user = self.configure_user(user, attributes, attribute_mapping)
  147. else:
  148. logger.debug('User updated')
  149. user = self.update_user(user, attributes, attribute_mapping)
  150. return user
  151. def _get_saml2_user(self, main_attribute, attributes, attribute_mapping):
  152. User = get_saml_user_model()
  153. django_user_main_attribute = self.get_django_user_main_attribute()
  154. user_query_args = self.get_user_query_args(main_attribute)
  155. logger.debug('Retrieving existing user "%s"', main_attribute)
  156. try:
  157. user = User.objects.get(**user_query_args)
  158. user = self.update_user(user, attributes, attribute_mapping)
  159. except User.DoesNotExist:
  160. logger.error('The user "%s" does not exist, searched %s', main_attribute, django_user_main_attribute)
  161. return None
  162. except MultipleObjectsReturned:
  163. logger.error("There are more than one user with %s = %s",
  164. django_user_main_attribute, main_attribute)
  165. return None
  166. return user
  167. def configure_user(self, user, attributes, attribute_mapping):
  168. """Configures a user after creation and returns the updated user.
  169. By default, returns the user with his attributes updated.
  170. """
  171. user.set_unusable_password()
  172. return self.update_user(user, attributes, attribute_mapping,
  173. force_save=True)
  174. def update_user(self, user, attributes, attribute_mapping,
  175. force_save=False):
  176. """Update a user with a set of attributes and returns the updated user.
  177. By default it uses a mapping defined in the settings constant
  178. SAML_ATTRIBUTE_MAPPING. For each attribute, if the user object has
  179. that field defined it will be set.
  180. """
  181. if not attribute_mapping:
  182. return user
  183. user_modified = False
  184. for saml_attr, django_attrs in attribute_mapping.items():
  185. attr_value_list = attributes.get(saml_attr)
  186. if not attr_value_list:
  187. logger.debug(
  188. 'Could not find value for "%s", not updating fields "%s"',
  189. saml_attr, django_attrs)
  190. continue
  191. for attr in django_attrs:
  192. if hasattr(user, attr):
  193. user_attr = getattr(user, attr)
  194. if callable(user_attr):
  195. modified = user_attr(attr_value_list)
  196. else:
  197. modified = self._set_attribute(user, attr, attr_value_list[0])
  198. user_modified = user_modified or modified
  199. else:
  200. logger.debug(
  201. 'Could not find attribute "%s" on user "%s"', attr, user)
  202. logger.debug('Sending the pre_save signal')
  203. signal_modified = any(
  204. [response for receiver, response
  205. in pre_user_save.send_robust(sender=user.__class__,
  206. instance=user,
  207. attributes=attributes,
  208. user_modified=user_modified)]
  209. )
  210. if user_modified or signal_modified or force_save:
  211. user.save()
  212. return user
  213. def _set_attribute(self, obj, attr, value):
  214. """Set an attribute of an object to a specific value.
  215. Return True if the attribute was changed and False otherwise.
  216. """
  217. field = obj._meta.get_field(attr)
  218. if field.max_length is not None and len(value) > field.max_length:
  219. cleaned_value = value[:field.max_length]
  220. logger.warn('The attribute "%s" was trimmed from "%s" to "%s"',
  221. attr, value, cleaned_value)
  222. else:
  223. cleaned_value = value
  224. old_value = getattr(obj, attr)
  225. if cleaned_value != old_value:
  226. setattr(obj, attr, cleaned_value)
  227. return True
  228. return False