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.

304 lines
10 KiB

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. from .urls_patterns import URL_ADMIN_USERS_COUNT, URL_ADMIN_USER, URL_ADMIN_USER_CONSENTS, \
  18. URL_ADMIN_SEND_UPDATE_ACCOUNT, URL_ADMIN_RESET_PASSWORD, URL_ADMIN_SEND_VERIFY_EMAIL, URL_ADMIN_GET_SESSIONS, \
  19. URL_ADMIN_SERVER_INFO, URL_ADMIN_CLIENTS, URL_ADMIN_CLIENT, URL_ADMIN_CLIENT_ROLES, URL_ADMIN_REALM_ROLES
  20. from .keycloak_openid import KeycloakOpenID
  21. from .exceptions import raise_error_from_response, KeycloakGetError
  22. from .urls_patterns import (
  23. URL_ADMIN_USERS,
  24. )
  25. from .connection import ConnectionManager
  26. import json
  27. class KeycloakAdmin:
  28. def __init__(self, server_url, username, password, realm_name='master', client_id='admin-cli'):
  29. self._username = username
  30. self._password = password
  31. self._client_id = client_id
  32. self._realm_name = realm_name
  33. # Get token Admin
  34. keycloak_openid = KeycloakOpenID(server_url, client_id, realm_name)
  35. self._token = keycloak_openid.token(username, password)
  36. self._connection = ConnectionManager(base_url=server_url,
  37. headers={'Authorization': 'Bearer ' + self.token.get('access_token'),
  38. 'Content-Type': 'application/json'},
  39. timeout=60)
  40. @property
  41. def realm_name(self):
  42. return self._realm_name
  43. @realm_name.setter
  44. def realm_name(self, value):
  45. self._realm_name = value
  46. @property
  47. def connection(self):
  48. return self._connection
  49. @connection.setter
  50. def connection(self, value):
  51. self._connection = value
  52. @property
  53. def client_id(self):
  54. return self._client_id
  55. @client_id.setter
  56. def client_id(self, value):
  57. self._client_id = value
  58. @property
  59. def username(self):
  60. return self._username
  61. @username.setter
  62. def username(self, value):
  63. self._username = value
  64. @property
  65. def password(self):
  66. return self._password
  67. @password.setter
  68. def password(self, value):
  69. self._password = value
  70. @property
  71. def token(self):
  72. return self._token
  73. @token.setter
  74. def token(self, value):
  75. self._token = value
  76. def get_users(self, query=None):
  77. """
  78. Get users Returns a list of users, filtered according to query parameters
  79. :return: users list
  80. """
  81. params_path = {"realm-name": self.realm_name}
  82. data_raw = self.connection.raw_get(URL_ADMIN_USERS.format(**params_path), **query)
  83. return raise_error_from_response(data_raw, KeycloakGetError)
  84. def create_user(self, payload):
  85. """
  86. Create a new user Username must be unique
  87. UserRepresentation
  88. http://www.keycloak.org/docs-api/3.3/rest-api/index.html#_userrepresentation
  89. :param payload: UserRepresentation
  90. :return: UserRepresentation
  91. """
  92. params_path = {"realm-name": self.realm_name}
  93. data_raw = self.connection.raw_post(URL_ADMIN_USERS.format(**params_path),
  94. data=json.dumps(payload))
  95. return raise_error_from_response(data_raw, KeycloakGetError, expected_code=201)
  96. def users_count(self):
  97. """
  98. User counter
  99. :return: counter
  100. """
  101. params_path = {"realm-name": self.realm_name}
  102. data_raw = self.connection.raw_get(URL_ADMIN_USERS_COUNT.format(**params_path))
  103. return raise_error_from_response(data_raw, KeycloakGetError)
  104. def get_user(self, user_id):
  105. """
  106. Get representation of the user
  107. :param user_id: User id
  108. UserRepresentation: http://www.keycloak.org/docs-api/3.3/rest-api/index.html#_userrepresentation
  109. :return: UserRepresentation
  110. """
  111. params_path = {"realm-name": self.realm_name, "id": user_id}
  112. data_raw = self.connection.raw_get(URL_ADMIN_USER.format(**params_path))
  113. return raise_error_from_response(data_raw, KeycloakGetError)
  114. def update_user(self, user_id, payload):
  115. """
  116. Update the user
  117. :param user_id: User id
  118. :param payload: UserRepresentation
  119. :return: Http response
  120. """
  121. params_path = {"realm-name": self.realm_name, "id": user_id}
  122. data_raw = self.connection.raw_put(URL_ADMIN_USER.format(**params_path),
  123. data=json.dumps(payload))
  124. return raise_error_from_response(data_raw, KeycloakGetError, expected_code=204)
  125. def delete_user(self, user_id):
  126. """
  127. Delete the user
  128. :param user_id: User id
  129. :return: Http response
  130. """
  131. params_path = {"realm-name": self.realm_name, "id": user_id}
  132. data_raw = self.connection.raw_delete(URL_ADMIN_USER.format(**params_path))
  133. return raise_error_from_response(data_raw, KeycloakGetError, expected_code=204)
  134. def consents_user(self, user_id):
  135. """
  136. Get consents granted by the user
  137. :param user_id: User id
  138. :return: consents
  139. """
  140. params_path = {"realm-name": self.realm_name, "id": user_id}
  141. data_raw = self.connection.raw_get(URL_ADMIN_USER_CONSENTS.format(**params_path))
  142. return raise_error_from_response(data_raw, KeycloakGetError)
  143. def send_update_account(self, user_id, payload, client_id=None, lifespan=None, redirect_uri=None):
  144. """
  145. Send a update account email to the user An email contains a
  146. link the user can click to perform a set of required actions.
  147. :param user_id:
  148. :param payload:
  149. :param client_id:
  150. :param lifespan:
  151. :param redirect_uri:
  152. :return:
  153. """
  154. params_path = {"realm-name": self.realm_name, "id": user_id}
  155. params_query = {"client_id": client_id, "lifespan": lifespan, "redirect_uri": redirect_uri}
  156. data_raw = self.connection.raw_put(URL_ADMIN_SEND_UPDATE_ACCOUNT.format(**params_path),
  157. data=payload, **params_query)
  158. return raise_error_from_response(data_raw, KeycloakGetError)
  159. def send_verify_email(self, user_id, client_id=None, redirect_uri=None):
  160. """
  161. Send a update account email to the user An email contains a
  162. link the user can click to perform a set of required actions.
  163. :param user_id: User id
  164. :param client_id: Client id
  165. :param redirect_uri: Redirect uri
  166. :return:
  167. """
  168. params_path = {"realm-name": self.realm_name, "id": user_id}
  169. params_query = {"client_id": client_id, "redirect_uri": redirect_uri}
  170. data_raw = self.connection.raw_put(URL_ADMIN_SEND_VERIFY_EMAIL.format(**params_path),
  171. data={}, **params_query)
  172. return raise_error_from_response(data_raw, KeycloakGetError)
  173. def get_sessions(self, user_id):
  174. """
  175. Get sessions associated with the user
  176. :param user_id: User id
  177. UserSessionRepresentation
  178. http://www.keycloak.org/docs-api/3.3/rest-api/index.html#_usersessionrepresentation
  179. :return: UserSessionRepresentation
  180. """
  181. params_path = {"realm-name": self.realm_name, "id": user_id}
  182. data_raw = self.connection.raw_get(URL_ADMIN_GET_SESSIONS.format(**params_path))
  183. return raise_error_from_response(data_raw, KeycloakGetError)
  184. def get_server_info(self):
  185. """
  186. Get themes, social providers, auth providers, and event listeners available on this server
  187. ServerInfoRepresentation
  188. http://www.keycloak.org/docs-api/3.3/rest-api/index.html#_serverinforepresentation
  189. :return: ServerInfoRepresentation
  190. """
  191. data_raw = self.connection.raw_get(URL_ADMIN_SERVER_INFO)
  192. return raise_error_from_response(data_raw, KeycloakGetError)
  193. def get_clients(self):
  194. """
  195. Get clients belonging to the realm Returns a list of clients belonging to the realm
  196. ClientRepresentation
  197. http://www.keycloak.org/docs-api/3.3/rest-api/index.html#_clientrepresentation
  198. :return: ClientRepresentation
  199. """
  200. params_path = {"realm-name": self.realm_name}
  201. data_raw = self.connection.raw_get(URL_ADMIN_CLIENTS.format(**params_path))
  202. return raise_error_from_response(data_raw, KeycloakGetError)
  203. def get_client(self, client_id):
  204. """
  205. Get representation of the client
  206. ClientRepresentation
  207. http://www.keycloak.org/docs-api/3.3/rest-api/index.html#_clientrepresentation
  208. :param client_id: id of client (not client-id)
  209. :return: ClientRepresentation
  210. """
  211. params_path = {"realm-name": self.realm_name, "id": client_id}
  212. data_raw = self.connection.raw_get(URL_ADMIN_CLIENT.format(**params_path))
  213. return raise_error_from_response(data_raw, KeycloakGetError)
  214. def get_client_role(self, client_id):
  215. """
  216. Get all roles for the client
  217. RoleRepresentation
  218. http://www.keycloak.org/docs-api/3.3/rest-api/index.html#_rolerepresentation
  219. :param client_id: id of client (not client-id)
  220. :return: RoleRepresentation
  221. """
  222. params_path = {"realm-name": self.realm_name, "id": client_id}
  223. data_raw = self.connection.raw_get(URL_ADMIN_CLIENT_ROLES.format(**params_path))
  224. return raise_error_from_response(data_raw, KeycloakGetError)
  225. def get_roles(self):
  226. """
  227. Get all roles for the realm or client
  228. RoleRepresentation
  229. http://www.keycloak.org/docs-api/3.3/rest-api/index.html#_rolerepresentation
  230. :return: RoleRepresentation
  231. """
  232. params_path = {"realm-name": self.realm_name}
  233. data_raw = self.connection.raw_get(URL_ADMIN_REALM_ROLES.format(**params_path))
  234. return raise_error_from_response(data_raw, KeycloakGetError)