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.

95 lines
2.6 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. from simplejson import JSONDecodeError
  19. class KeycloakError(Exception):
  20. def __init__(self, error_message="", response_code=None,
  21. response_body=None):
  22. Exception.__init__(self, error_message)
  23. self.response_code = response_code
  24. self.response_body = response_body
  25. self.error_message = error_message
  26. def __str__(self):
  27. if self.response_code is not None:
  28. return "{0}: {1}".format(self.response_code, self.error_message)
  29. else:
  30. return "{0}".format(self.error_message)
  31. class KeycloakAuthenticationError(KeycloakError):
  32. pass
  33. class KeycloakConnectionError(KeycloakError):
  34. pass
  35. class KeycloakOperationError(KeycloakError):
  36. pass
  37. class KeycloakGetError(KeycloakOperationError):
  38. pass
  39. class KeycloakSecretNotFound(KeycloakOperationError):
  40. pass
  41. class KeycloakRPTNotFound(KeycloakOperationError):
  42. pass
  43. class KeycloakAuthorizationConfigError(KeycloakOperationError):
  44. pass
  45. class KeycloakInvalidTokenError(KeycloakOperationError):
  46. pass
  47. def raise_error_from_response(response, error, expected_code=200):
  48. if expected_code == response.status_code:
  49. if expected_code == requests.codes.no_content:
  50. return {}
  51. try:
  52. return response.json()
  53. except JSONDecodeError as e:
  54. return response.content
  55. try:
  56. message = response.json()['message']
  57. except (KeyError, ValueError):
  58. message = response.content
  59. if isinstance(error, dict):
  60. error = error.get(response.status_code, KeycloakOperationError)
  61. else:
  62. if response.status_code == 401:
  63. error = KeycloakAuthenticationError
  64. raise error(error_message=message,
  65. response_code=response.status_code,
  66. response_body=response.content)