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.

93 lines
2.5 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
  1. # -*- coding: utf-8 -*-
  2. #
  3. # Copyright (C) 2017 Marcos Pereira <marcospereira.mpj@gmail.com>
  4. #
  5. # This program is free software: you can redistribute it and/or modify
  6. # it under the terms of the GNU Lesser General Public License as published by
  7. # the Free Software Foundation, either version 3 of the License, or
  8. # (at your option) any later version.
  9. #
  10. # This program is distributed in the hope that it will be useful,
  11. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. # GNU Lesser General Public License for more details.
  14. #
  15. # You should have received a copy of the GNU Lesser General Public License
  16. # along with this program. If not, see <http://www.gnu.org/licenses/>.
  17. import requests
  18. class KeycloakError(Exception):
  19. def __init__(self, error_message="", response_code=None,
  20. response_body=None):
  21. Exception.__init__(self, error_message)
  22. self.response_code = response_code
  23. self.response_body = response_body
  24. self.error_message = error_message
  25. def __str__(self):
  26. if self.response_code is not None:
  27. return "{0}: {1}".format(self.response_code, self.error_message)
  28. else:
  29. return "{0}".format(self.error_message)
  30. class KeycloakAuthenticationError(KeycloakError):
  31. pass
  32. class KeycloakConnectionError(KeycloakError):
  33. pass
  34. class KeycloakOperationError(KeycloakError):
  35. pass
  36. class KeycloakGetError(KeycloakOperationError):
  37. pass
  38. class KeycloakSecretNotFound(KeycloakOperationError):
  39. pass
  40. class KeycloakRPTNotFound(KeycloakOperationError):
  41. pass
  42. class KeycloakAuthorizationConfigError(KeycloakOperationError):
  43. pass
  44. class KeycloakInvalidTokenError(KeycloakOperationError):
  45. pass
  46. def raise_error_from_response(response, error, expected_code=200):
  47. if expected_code == response.status_code:
  48. if expected_code == requests.codes.no_content:
  49. return {}
  50. try:
  51. return response.json()
  52. except ValueError:
  53. return response.content
  54. try:
  55. message = response.json()['message']
  56. except (KeyError, ValueError):
  57. message = response.content
  58. if isinstance(error, dict):
  59. error = error.get(response.status_code, KeycloakOperationError)
  60. else:
  61. if response.status_code == 401:
  62. error = KeycloakAuthenticationError
  63. raise error(error_message=message,
  64. response_code=response.status_code,
  65. response_body=response.content)