conf.py 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  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 copy
  16. from importlib import import_module
  17. from django.conf import settings
  18. from django.core.exceptions import ImproperlyConfigured
  19. from saml2.config import SPConfig
  20. from djangosaml2.utils import get_custom_setting
  21. def get_config_loader(path, request=None):
  22. i = path.rfind('.')
  23. module, attr = path[:i], path[i + 1:]
  24. try:
  25. mod = import_module(module)
  26. except ImportError as e:
  27. raise ImproperlyConfigured(
  28. 'Error importing SAML config loader %s: "%s"' % (path, e))
  29. except ValueError as e:
  30. raise ImproperlyConfigured(
  31. 'Error importing SAML config loader. Is SAML_CONFIG_LOADER '
  32. 'a correctly string with a callable path?'
  33. )
  34. try:
  35. config_loader = getattr(mod, attr)
  36. except AttributeError:
  37. raise ImproperlyConfigured(
  38. 'Module "%s" does not define a "%s" config loader' %
  39. (module, attr)
  40. )
  41. if not hasattr(config_loader, '__call__'):
  42. raise ImproperlyConfigured(
  43. "SAML config loader must be a callable object.")
  44. return config_loader
  45. def config_settings_loader(request=None):
  46. """Utility function to load the pysaml2 configuration.
  47. This is also the default config loader.
  48. """
  49. conf = SPConfig()
  50. conf.load(copy.deepcopy(settings.SAML_CONFIG))
  51. return conf
  52. def get_config(config_loader_path=None, request=None):
  53. config_loader_path = config_loader_path or get_custom_setting(
  54. 'SAML_CONFIG_LOADER', 'djangosaml2.conf.config_settings_loader')
  55. config_loader = get_config_loader(config_loader_path)
  56. return config_loader(request)