utils.py 3.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. # Copyright (C) 2012 Yaco Sistemas (http://www.yaco.es)
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. import django
  15. from django.conf import settings
  16. from django.core.exceptions import ImproperlyConfigured
  17. from django.utils.http import is_safe_url
  18. from django.utils.module_loading import import_string
  19. from saml2.s_utils import UnknownSystemEntity
  20. def get_custom_setting(name, default=None):
  21. return getattr(settings, name, default)
  22. def available_idps(config, langpref=None):
  23. if langpref is None:
  24. langpref = "en"
  25. idps = set()
  26. for metadata_name, metadata in config.metadata.metadata.items():
  27. result = metadata.any('idpsso_descriptor', 'single_sign_on_service')
  28. if result:
  29. idps = idps.union(set(result.keys()))
  30. return dict([(idp, config.metadata.name(idp, langpref)) for idp in idps])
  31. def get_idp_sso_supported_bindings(idp_entity_id=None, config=None):
  32. """Returns the list of bindings supported by an IDP
  33. This is not clear in the pysaml2 code, so wrapping it in a util"""
  34. if config is None:
  35. # avoid circular import
  36. from djangosaml2.conf import get_config
  37. config = get_config()
  38. # load metadata store from config
  39. meta = getattr(config, 'metadata', {})
  40. # if idp is None, assume only one exists so just use that
  41. if idp_entity_id is None:
  42. # .keys() returns dict_keys in python3.5+
  43. try:
  44. idp_entity_id = list(available_idps(config).keys())[0]
  45. except IndexError:
  46. raise ImproperlyConfigured("No IdP configured!")
  47. try:
  48. return meta.service(idp_entity_id, 'idpsso_descriptor', 'single_sign_on_service').keys()
  49. except UnknownSystemEntity:
  50. return []
  51. def get_location(http_info):
  52. """Extract the redirect URL from a pysaml2 http_info object"""
  53. try:
  54. headers = dict(http_info['headers'])
  55. return headers['Location']
  56. except KeyError:
  57. return http_info['url']
  58. def fail_acs_response(request, *args, **kwargs):
  59. """ Serves as a common mechanism for ending ACS in case of any SAML related failure.
  60. Handling can be configured by setting the SAML_ACS_FAILURE_RESPONSE_FUNCTION as
  61. suitable for the project.
  62. The default behavior uses SAML specific template that is rendered on any ACS error,
  63. but this can be simply changed so that PermissionDenied exception is raised instead.
  64. """
  65. failure_function = import_string(get_custom_setting('SAML_ACS_FAILURE_RESPONSE_FUNCTION',
  66. 'djangosaml2.acs_failures.template_failure'))
  67. return failure_function(request, *args, **kwargs)
  68. def is_safe_url_compat(url, allowed_hosts=None, require_https=False):
  69. if django.VERSION >= (1, 11):
  70. return is_safe_url(url, allowed_hosts=allowed_hosts, require_https=require_https)
  71. assert len(allowed_hosts) == 1
  72. host = allowed_hosts.pop()
  73. return is_safe_url(url, host=host)