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.

194 lines
5.3 KiB

7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
6 years ago
7 years ago
6 years ago
6 years ago
7 years ago
7 years ago
  1. # -*- coding: utf-8 -*-
  2. #
  3. # The MIT License (MIT)
  4. #
  5. # Copyright (C) 2017 Marcos Pereira <marcospereira.mpj@gmail.com>
  6. #
  7. # Permission is hereby granted, free of charge, to any person obtaining a copy of
  8. # this software and associated documentation files (the "Software"), to deal in
  9. # the Software without restriction, including without limitation the rights to
  10. # use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
  11. # the Software, and to permit persons to whom the Software is furnished to do so,
  12. # subject to the following conditions:
  13. #
  14. # The above copyright notice and this permission notice shall be included in all
  15. # copies or substantial portions of the Software.
  16. #
  17. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  18. # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
  19. # FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
  20. # COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
  21. # IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
  22. # CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  23. """Keycloak custom exceptions module."""
  24. import requests
  25. class KeycloakError(Exception):
  26. """Base class for custom Keycloak errors.
  27. :param error_message: The error message
  28. :type error_message: str
  29. :param response_code: The response status code
  30. :type response_code: int
  31. """
  32. def __init__(self, error_message="", response_code=None, response_body=None):
  33. """Init method.
  34. :param error_message: The error message
  35. :type error_message: str
  36. :param response_code: The code of the response
  37. :type response_code: int
  38. :param response_body: Body of the response
  39. :type response_body: bytes
  40. """
  41. Exception.__init__(self, error_message)
  42. self.response_code = response_code
  43. self.response_body = response_body
  44. self.error_message = error_message
  45. def __str__(self):
  46. """Str method.
  47. :returns: String representation of the object
  48. :rtype: str
  49. """
  50. if self.response_code is not None:
  51. return "{0}: {1}".format(self.response_code, self.error_message)
  52. else:
  53. return "{0}".format(self.error_message)
  54. class KeycloakAuthenticationError(KeycloakError):
  55. """Keycloak authentication error exception."""
  56. pass
  57. class KeycloakConnectionError(KeycloakError):
  58. """Keycloak connection error exception."""
  59. pass
  60. class KeycloakOperationError(KeycloakError):
  61. """Keycloak operation error exception."""
  62. pass
  63. class KeycloakDeprecationError(KeycloakError):
  64. """Keycloak deprecation error exception."""
  65. pass
  66. class KeycloakGetError(KeycloakOperationError):
  67. """Keycloak request get error exception."""
  68. pass
  69. class KeycloakPostError(KeycloakOperationError):
  70. """Keycloak request post error exception."""
  71. pass
  72. class KeycloakPutError(KeycloakOperationError):
  73. """Keycloak request put error exception."""
  74. pass
  75. class KeycloakDeleteError(KeycloakOperationError):
  76. """Keycloak request delete error exception."""
  77. pass
  78. class KeycloakSecretNotFound(KeycloakOperationError):
  79. """Keycloak secret not found exception."""
  80. pass
  81. class KeycloakRPTNotFound(KeycloakOperationError):
  82. """Keycloak RPT not found exception."""
  83. pass
  84. class KeycloakAuthorizationConfigError(KeycloakOperationError):
  85. """Keycloak authorization config exception."""
  86. pass
  87. class KeycloakInvalidTokenError(KeycloakOperationError):
  88. """Keycloak invalid token exception."""
  89. pass
  90. class KeycloakPermissionFormatError(KeycloakOperationError):
  91. """Keycloak permission format exception."""
  92. pass
  93. class PermissionDefinitionError(Exception):
  94. """Keycloak permission definition exception."""
  95. pass
  96. def raise_error_from_response(response, error, expected_codes=None, skip_exists=False):
  97. """Raise an exception for the response.
  98. :param response: The response object
  99. :type response: Response
  100. :param error: Error object to raise
  101. :type error: dict or Exception
  102. :param expected_codes: Set of expected codes, which should not raise the exception
  103. :type expected_codes: Sequence[int]
  104. :param skip_exists: Indicates whether the response on already existing object should be ignored
  105. :type skip_exists: bool
  106. :returns: Content of the response message
  107. :type: bytes or dict
  108. :raises KeycloakError: In case of unexpected status codes
  109. """ # noqa: DAR401,DAR402
  110. if expected_codes is None:
  111. expected_codes = [200, 201, 204]
  112. if response.status_code in expected_codes:
  113. if response.status_code == requests.codes.no_content:
  114. return {}
  115. try:
  116. return response.json()
  117. except ValueError:
  118. return response.content
  119. if skip_exists and response.status_code == 409:
  120. return {"msg": "Already exists"}
  121. try:
  122. message = response.json()["message"]
  123. except (KeyError, ValueError):
  124. message = response.content
  125. if isinstance(error, dict):
  126. error = error.get(response.status_code, KeycloakOperationError)
  127. else:
  128. if response.status_code == 401:
  129. error = KeycloakAuthenticationError
  130. raise error(
  131. error_message=message, response_code=response.status_code, response_body=response.content
  132. )