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.

858 lines
32 KiB

7 years ago
6 years ago
6 years ago
6 years ago
7 years ago
6 years ago
7 years ago
7 years ago
7 years ago
6 years ago
6 years ago
7 years ago
6 years ago
6 years ago
6 years ago
7 years ago
7 years ago
7 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
7 years ago
7 years ago
7 years ago
7 years ago
6 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
6 years ago
7 years ago
7 years ago
7 years ago
6 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. # Unless otherwise stated in the comments, "id", in e.g. user_id, refers to the
  24. # internal Keycloak server ID, usually a uuid string
  25. import json
  26. from .connection import ConnectionManager
  27. from .exceptions import raise_error_from_response, KeycloakGetError
  28. from .keycloak_openid import KeycloakOpenID
  29. from .urls_patterns import *
  30. from .urls_patterns import (
  31. URL_ADMIN_USERS,
  32. )
  33. class KeycloakAdmin:
  34. def __init__(self, server_url, username, password, realm_name='master', client_id='admin-cli', verify=True):
  35. """
  36. :param server_url: Keycloak server url
  37. :param username: admin username
  38. :param password: admin password
  39. :param realm_name: realm name
  40. :param client_id: client id
  41. :param verify: True if want check connection SSL
  42. """
  43. self._username = username
  44. self._password = password
  45. self._client_id = client_id
  46. self._realm_name = realm_name
  47. # Get token Admin
  48. keycloak_openid = KeycloakOpenID(server_url=server_url, client_id=client_id, realm_name=realm_name,
  49. verify=verify)
  50. self._token = keycloak_openid.token(username, password)
  51. self._connection = ConnectionManager(base_url=server_url,
  52. headers={'Authorization': 'Bearer ' + self.token.get('access_token'),
  53. 'Content-Type': 'application/json'},
  54. timeout=60,
  55. verify=verify)
  56. @property
  57. def realm_name(self):
  58. return self._realm_name
  59. @realm_name.setter
  60. def realm_name(self, value):
  61. self._realm_name = value
  62. @property
  63. def connection(self):
  64. return self._connection
  65. @connection.setter
  66. def connection(self, value):
  67. self._connection = value
  68. @property
  69. def client_id(self):
  70. return self._client_id
  71. @client_id.setter
  72. def client_id(self, value):
  73. self._client_id = value
  74. @property
  75. def username(self):
  76. return self._username
  77. @username.setter
  78. def username(self, value):
  79. self._username = value
  80. @property
  81. def password(self):
  82. return self._password
  83. @password.setter
  84. def password(self, value):
  85. self._password = value
  86. @property
  87. def token(self):
  88. return self._token
  89. @token.setter
  90. def token(self, value):
  91. self._token = value
  92. def import_realm(self, payload):
  93. """
  94. Import a new realm from a RealmRepresentation. Realm name must be unique.
  95. RealmRepresentation
  96. https://www.keycloak.org/docs-api/4.4/rest-api/index.html#_realmrepresentation
  97. :param payload: RealmRepresentation
  98. :return: RealmRepresentation
  99. """
  100. data_raw = self.connection.raw_post(URL_ADMIN_REALM_IMPORT,
  101. data=json.dumps(payload))
  102. return raise_error_from_response(data_raw, KeycloakGetError, expected_code=201)
  103. def get_users(self, query=None):
  104. """
  105. Get users Returns a list of users, filtered according to query parameters
  106. :return: users list
  107. """
  108. params_path = {"realm-name": self.realm_name}
  109. data_raw = self.connection.raw_get(URL_ADMIN_USERS.format(**params_path), **query)
  110. return raise_error_from_response(data_raw, KeycloakGetError)
  111. def get_idps(self):
  112. """
  113. Returns a list of ID Providers,
  114. IdentityProviderRepresentation
  115. https://www.keycloak.org/docs-api/3.3/rest-api/index.html#_identityproviderrepresentation
  116. :return: array IdentityProviderRepresentation
  117. """
  118. params_path = {"realm-name": self.realm_name}
  119. data_raw = self.connection.raw_get(URL_ADMIN_IDPS.format(**params_path))
  120. return raise_error_from_response(data_raw, KeycloakGetError)
  121. def create_user(self, payload):
  122. """
  123. Create a new user Username must be unique
  124. UserRepresentation
  125. http://www.keycloak.org/docs-api/3.3/rest-api/index.html#_userrepresentation
  126. :param payload: UserRepresentation
  127. :return: UserRepresentation
  128. """
  129. params_path = {"realm-name": self.realm_name}
  130. exists = self.get_user_id(username=payload['username'])
  131. if exists is not None:
  132. return str(exists)
  133. data_raw = self.connection.raw_post(URL_ADMIN_USERS.format(**params_path),
  134. data=json.dumps(payload))
  135. return raise_error_from_response(data_raw, KeycloakGetError, expected_code=201)
  136. def users_count(self):
  137. """
  138. User counter
  139. :return: counter
  140. """
  141. params_path = {"realm-name": self.realm_name}
  142. data_raw = self.connection.raw_get(URL_ADMIN_USERS_COUNT.format(**params_path))
  143. return raise_error_from_response(data_raw, KeycloakGetError)
  144. def get_user_id(self, username):
  145. """
  146. Get internal keycloak user id from username
  147. This is required for further actions against this user.
  148. UserRepresentation
  149. http://www.keycloak.org/docs-api/3.3/rest-api/index.html#_userrepresentation
  150. :param username: id in UserRepresentation
  151. :return: user_id
  152. """
  153. users = self.get_users(query={"username": username})
  154. return next((user["id"] for user in users if user["username"] == username), None)
  155. def get_user(self, user_id):
  156. """
  157. Get representation of the user
  158. :param user_id: User id
  159. UserRepresentation: http://www.keycloak.org/docs-api/3.3/rest-api/index.html#_userrepresentation
  160. :return: UserRepresentation
  161. """
  162. params_path = {"realm-name": self.realm_name, "id": user_id}
  163. data_raw = self.connection.raw_get(URL_ADMIN_USER.format(**params_path))
  164. return raise_error_from_response(data_raw, KeycloakGetError)
  165. def get_user_groups(self, user_id):
  166. """
  167. Get user groups Returns a list of groups of which the user is a member
  168. :param user_id: User id
  169. :return: user groups list
  170. """
  171. params_path = {"realm-name": self.realm_name, "id": user_id}
  172. data_raw = self.connection.raw_get(URL_ADMIN_USER_GROUPS.format(**params_path))
  173. return raise_error_from_response(data_raw, KeycloakGetError)
  174. def update_user(self, user_id, payload):
  175. """
  176. Update the user
  177. :param user_id: User id
  178. :param payload: UserRepresentation
  179. :return: Http response
  180. """
  181. params_path = {"realm-name": self.realm_name, "id": user_id}
  182. data_raw = self.connection.raw_put(URL_ADMIN_USER.format(**params_path),
  183. data=json.dumps(payload))
  184. return raise_error_from_response(data_raw, KeycloakGetError, expected_code=204)
  185. def delete_user(self, user_id):
  186. """
  187. Delete the user
  188. :param user_id: User id
  189. :return: Http response
  190. """
  191. params_path = {"realm-name": self.realm_name, "id": user_id}
  192. data_raw = self.connection.raw_delete(URL_ADMIN_USER.format(**params_path))
  193. return raise_error_from_response(data_raw, KeycloakGetError, expected_code=204)
  194. def set_user_password(self, user_id, password, temporary=True):
  195. """
  196. Set up a password for the user. If temporary is True, the user will have to reset
  197. the temporary password next time they log in.
  198. http://www.keycloak.org/docs-api/3.2/rest-api/#_users_resource
  199. http://www.keycloak.org/docs-api/3.2/rest-api/#_credentialrepresentation
  200. :param user_id: User id
  201. :param password: New password
  202. :param temporary: True if password is temporary
  203. :return:
  204. """
  205. payload = {"type": "password", "temporary": temporary, "value": password}
  206. params_path = {"realm-name": self.realm_name, "id": user_id}
  207. data_raw = self.connection.raw_put(URL_ADMIN_RESET_PASSWORD.format(**params_path),
  208. data=json.dumps(payload))
  209. return raise_error_from_response(data_raw, KeycloakGetError, expected_code=204)
  210. def consents_user(self, user_id):
  211. """
  212. Get consents granted by the user
  213. :param user_id: User id
  214. :return: consents
  215. """
  216. params_path = {"realm-name": self.realm_name, "id": user_id}
  217. data_raw = self.connection.raw_get(URL_ADMIN_USER_CONSENTS.format(**params_path))
  218. return raise_error_from_response(data_raw, KeycloakGetError)
  219. def send_update_account(self, user_id, payload, client_id=None, lifespan=None, redirect_uri=None):
  220. """
  221. Send a update account email to the user An email contains a
  222. link the user can click to perform a set of required actions.
  223. :param user_id:
  224. :param payload:
  225. :param client_id:
  226. :param lifespan:
  227. :param redirect_uri:
  228. :return:
  229. """
  230. params_path = {"realm-name": self.realm_name, "id": user_id}
  231. params_query = {"client_id": client_id, "lifespan": lifespan, "redirect_uri": redirect_uri}
  232. data_raw = self.connection.raw_put(URL_ADMIN_SEND_UPDATE_ACCOUNT.format(**params_path),
  233. data=payload, **params_query)
  234. return raise_error_from_response(data_raw, KeycloakGetError)
  235. def send_verify_email(self, user_id, client_id=None, redirect_uri=None):
  236. """
  237. Send a update account email to the user An email contains a
  238. link the user can click to perform a set of required actions.
  239. :param user_id: User id
  240. :param client_id: Client id
  241. :param redirect_uri: Redirect uri
  242. :return:
  243. """
  244. params_path = {"realm-name": self.realm_name, "id": user_id}
  245. params_query = {"client_id": client_id, "redirect_uri": redirect_uri}
  246. data_raw = self.connection.raw_put(URL_ADMIN_SEND_VERIFY_EMAIL.format(**params_path),
  247. data={}, **params_query)
  248. return raise_error_from_response(data_raw, KeycloakGetError)
  249. def get_sessions(self, user_id):
  250. """
  251. Get sessions associated with the user
  252. :param user_id: id of user
  253. UserSessionRepresentation
  254. http://www.keycloak.org/docs-api/3.3/rest-api/index.html#_usersessionrepresentation
  255. :return: UserSessionRepresentation
  256. """
  257. params_path = {"realm-name": self.realm_name, "id": user_id}
  258. data_raw = self.connection.raw_get(URL_ADMIN_GET_SESSIONS.format(**params_path))
  259. return raise_error_from_response(data_raw, KeycloakGetError)
  260. def get_server_info(self):
  261. """
  262. Get themes, social providers, auth providers, and event listeners available on this server
  263. ServerInfoRepresentation
  264. http://www.keycloak.org/docs-api/3.3/rest-api/index.html#_serverinforepresentation
  265. :return: ServerInfoRepresentation
  266. """
  267. data_raw = self.connection.raw_get(URL_ADMIN_SERVER_INFO)
  268. return raise_error_from_response(data_raw, KeycloakGetError)
  269. def get_groups(self):
  270. """
  271. Get groups belonging to the realm. Returns a list of groups belonging to the realm
  272. GroupRepresentation
  273. http://www.keycloak.org/docs-api/3.2/rest-api/#_grouprepresentation
  274. :return: array GroupRepresentation
  275. """
  276. params_path = {"realm-name": self.realm_name}
  277. data_raw = self.connection.raw_get(URL_ADMIN_GROUPS.format(**params_path))
  278. return raise_error_from_response(data_raw, KeycloakGetError)
  279. def get_group(self, group_id):
  280. """
  281. Get group by id. Returns full group details
  282. GroupRepresentation
  283. http://www.keycloak.org/docs-api/3.2/rest-api/#_grouprepresentation
  284. :return: Keycloak server response (GroupRepresentation)
  285. """
  286. params_path = {"realm-name": self.realm_name, "id": group_id}
  287. data_raw = self.connection.raw_get(URL_ADMIN_GROUP.format(**params_path))
  288. return raise_error_from_response(data_raw, KeycloakGetError)
  289. def get_subgroups(self, group, path):
  290. """
  291. Utility function to iterate through nested group structures
  292. GroupRepresentation
  293. http://www.keycloak.org/docs-api/3.2/rest-api/#_grouprepresentation
  294. :param name: group (GroupRepresentation)
  295. :param path: group path (string)
  296. :return: Keycloak server response (GroupRepresentation)
  297. """
  298. for subgroup in group["subGroups"]:
  299. if subgroup['path'] == path:
  300. return subgroup
  301. elif subgroup["subGroups"]:
  302. for subgroup in group["subGroups"]:
  303. return self.get_subgroups(subgroup, path)
  304. return None
  305. def get_group_members(self, group_id, **query):
  306. """
  307. Get members by group id. Returns group members
  308. GroupRepresentation
  309. http://www.keycloak.org/docs-api/3.2/rest-api/#_userrepresentation
  310. :return: Keycloak server response (UserRepresentation)
  311. """
  312. params_path = {"realm-name": self.realm_name, "id": group_id}
  313. data_raw = self.connection.raw_get(URL_ADMIN_GROUP_MEMBERS.format(**params_path), **query)
  314. return raise_error_from_response(data_raw, KeycloakGetError)
  315. def get_group_by_path(self, path, search_in_subgroups=False):
  316. """
  317. Get group id based on name or path.
  318. A straight name or path match with a top-level group will return first.
  319. Subgroups are traversed, the first to match path (or name with path) is returned.
  320. GroupRepresentation
  321. http://www.keycloak.org/docs-api/3.2/rest-api/#_grouprepresentation
  322. :param path: group path
  323. :param search_in_subgroups: True if want search in the subgroups
  324. :return: Keycloak server response (GroupRepresentation)
  325. """
  326. groups = self.get_groups()
  327. # TODO: Review this code is necessary
  328. for group in groups:
  329. if group['path'] == path:
  330. return group
  331. elif search_in_subgroups and group["subGroups"]:
  332. res = self.get_subgroups(group, path)
  333. if res != None:
  334. return res
  335. return None
  336. def create_group(self, payload, parent=None, skip_exists=False):
  337. """
  338. Creates a group in the Realm
  339. :param payload: GroupRepresentation
  340. :param parent: parent group's id. Required to create a sub-group.
  341. GroupRepresentation
  342. http://www.keycloak.org/docs-api/3.2/rest-api/#_grouprepresentation
  343. :return: Http response
  344. """
  345. name = payload['name']
  346. path = payload['path']
  347. exists = None
  348. if name is None and path is not None:
  349. path = "/" + name
  350. elif path is not None:
  351. exists = self.get_group_by_path(path=path, search_in_subgroups=True)
  352. if exists is not None:
  353. return str(exists)
  354. if parent is None:
  355. params_path = {"realm-name": self.realm_name}
  356. data_raw = self.connection.raw_post(URL_ADMIN_GROUPS.format(**params_path),
  357. data=json.dumps(payload))
  358. else:
  359. params_path = {"realm-name": self.realm_name, "id": parent, }
  360. data_raw = self.connection.raw_post(URL_ADMIN_GROUP_CHILD.format(**params_path),
  361. data=json.dumps(payload))
  362. return raise_error_from_response(data_raw, KeycloakGetError, expected_code=201, skip_exists=skip_exists)
  363. def group_set_permissions(self, group_id, enabled=True):
  364. """
  365. Enable/Disable permissions for a group. Cannot delete group if disabled
  366. :param group_id: id of group
  367. :param enabled: boolean
  368. :return: Keycloak server response
  369. """
  370. params_path = {"realm-name": self.realm_name, "id": group_id}
  371. data_raw = self.connection.raw_put(URL_ADMIN_GROUP_PERMISSIONS.format(**params_path),
  372. data=json.dumps({"enabled": enabled}))
  373. return raise_error_from_response(data_raw, KeycloakGetError)
  374. def group_user_add(self, user_id, group_id):
  375. """
  376. Add user to group (user_id and group_id)
  377. :param group_id: id of group
  378. :param user_id: id of user
  379. :param group_id: id of group to add to
  380. :return: Keycloak server response
  381. """
  382. params_path = {"realm-name": self.realm_name, "id": user_id, "group-id": group_id}
  383. data_raw = self.connection.raw_put(URL_ADMIN_USER_GROUP.format(**params_path), data=None)
  384. return raise_error_from_response(data_raw, KeycloakGetError, expected_code=204)
  385. def group_user_remove(self, user_id, group_id):
  386. """
  387. Remove user from group (user_id and group_id)
  388. :param group_id: id of group
  389. :param user_id: id of user
  390. :param group_id: id of group to add to
  391. :return: Keycloak server response
  392. """
  393. params_path = {"realm-name": self.realm_name, "id": user_id, "group-id": group_id}
  394. data_raw = self.connection.raw_delete(URL_ADMIN_USER_GROUP.format(**params_path))
  395. return raise_error_from_response(data_raw, KeycloakGetError, expected_code=204)
  396. def delete_group(self, group_id):
  397. """
  398. Deletes a group in the Realm
  399. :param group_id: id of group to delete
  400. :return: Keycloak server response
  401. """
  402. params_path = {"realm-name": self.realm_name, "id": group_id}
  403. data_raw = self.connection.raw_delete(URL_ADMIN_GROUP.format(**params_path))
  404. return raise_error_from_response(data_raw, KeycloakGetError, expected_code=204)
  405. def get_clients(self):
  406. """
  407. Get clients belonging to the realm Returns a list of clients belonging to the realm
  408. ClientRepresentation
  409. http://www.keycloak.org/docs-api/3.3/rest-api/index.html#_clientrepresentation
  410. :return: Keycloak server response (ClientRepresentation)
  411. """
  412. params_path = {"realm-name": self.realm_name}
  413. data_raw = self.connection.raw_get(URL_ADMIN_CLIENTS.format(**params_path))
  414. return raise_error_from_response(data_raw, KeycloakGetError)
  415. def get_client(self, client_id):
  416. """
  417. Get representation of the client
  418. ClientRepresentation
  419. http://www.keycloak.org/docs-api/3.3/rest-api/index.html#_clientrepresentation
  420. :param client_id: id of client (not client-id)
  421. :return: Keycloak server response (ClientRepresentation)
  422. """
  423. params_path = {"realm-name": self.realm_name, "id": client_id}
  424. data_raw = self.connection.raw_get(URL_ADMIN_CLIENT.format(**params_path))
  425. return raise_error_from_response(data_raw, KeycloakGetError)
  426. def get_client_id(self, client_name):
  427. """
  428. Get internal keycloak client id from client-id.
  429. This is required for further actions against this client.
  430. :param client_name: name in ClientRepresentation
  431. http://www.keycloak.org/docs-api/3.3/rest-api/index.html#_clientrepresentation
  432. :return: client_id (uuid as string)
  433. """
  434. clients = self.get_clients()
  435. for client in clients:
  436. if client_name == client.get('name') or client_name == client.get('clientId'):
  437. return client["id"]
  438. return None
  439. def get_client_authz_settings(self, client_id):
  440. """
  441. Get authorization json from client.
  442. :param client_id: id in ClientRepresentation
  443. http://www.keycloak.org/docs-api/3.3/rest-api/index.html#_clientrepresentation
  444. :return: Keycloak server response
  445. """
  446. params_path = {"realm-name": self.realm_name, "id": client_id}
  447. data_raw = self.connection.raw_get(URL_ADMIN_CLIENT_AUTHZ_SETTINGS.format(**params_path))
  448. return data_raw
  449. def get_client_authz_resources(self, client_id):
  450. """
  451. Get resources from client.
  452. :param client_id: id in ClientRepresentation
  453. http://www.keycloak.org/docs-api/3.3/rest-api/index.html#_clientrepresentation
  454. :return: Keycloak server response
  455. """
  456. params_path = {"realm-name": self.realm_name, "id": client_id}
  457. data_raw = self.connection.raw_get(URL_ADMIN_CLIENT_AUTHZ_RESOURCES.format(**params_path))
  458. return data_raw
  459. def create_client(self, payload, skip_exists=False):
  460. """
  461. Create a client
  462. ClientRepresentation: http://www.keycloak.org/docs-api/3.3/rest-api/index.html#_clientrepresentation
  463. :param skip_exists: Skip if client already exist.
  464. :param payload: ClientRepresentation
  465. :return: Keycloak server response (UserRepresentation)
  466. """
  467. params_path = {"realm-name": self.realm_name}
  468. data_raw = self.connection.raw_post(URL_ADMIN_CLIENTS.format(**params_path),
  469. data=json.dumps(payload))
  470. return raise_error_from_response(data_raw, KeycloakGetError, expected_code=201, skip_exists=skip_exists)
  471. def delete_client(self, client_id):
  472. """
  473. Get representation of the client
  474. ClientRepresentation
  475. http://www.keycloak.org/docs-api/3.3/rest-api/index.html#_clientrepresentation
  476. :param client_id: keycloak client id (not oauth client-id)
  477. :return: Keycloak server response (ClientRepresentation)
  478. """
  479. params_path = {"realm-name": self.realm_name, "id": client_id}
  480. data_raw = self.connection.raw_delete(URL_ADMIN_CLIENT.format(**params_path))
  481. return raise_error_from_response(data_raw, KeycloakGetError, expected_code=204)
  482. def get_realm_roles(self):
  483. """
  484. Get all roles for the realm or client
  485. RoleRepresentation
  486. http://www.keycloak.org/docs-api/3.3/rest-api/index.html#_rolerepresentation
  487. :return: Keycloak server response (RoleRepresentation)
  488. """
  489. params_path = {"realm-name": self.realm_name}
  490. data_raw = self.connection.raw_get(URL_ADMIN_REALM_ROLES.format(**params_path))
  491. return raise_error_from_response(data_raw, KeycloakGetError)
  492. def get_client_roles(self, client_id):
  493. """
  494. Get all roles for the client
  495. :param client_id: id of client (not client-id)
  496. RoleRepresentation
  497. http://www.keycloak.org/docs-api/3.3/rest-api/index.html#_rolerepresentation
  498. :return: Keycloak server response (RoleRepresentation)
  499. """
  500. params_path = {"realm-name": self.realm_name, "id": client_id}
  501. data_raw = self.connection.raw_get(URL_ADMIN_CLIENT_ROLES.format(**params_path))
  502. return raise_error_from_response(data_raw, KeycloakGetError)
  503. def get_client_role(self, client_id, role_name):
  504. """
  505. Get client role id by name
  506. This is required for further actions with this role.
  507. :param client_id: id of client (not client-id)
  508. :param role_name: roles name (not id!)
  509. RoleRepresentation
  510. http://www.keycloak.org/docs-api/3.3/rest-api/index.html#_rolerepresentation
  511. :return: role_id
  512. """
  513. params_path = {"realm-name": self.realm_name, "id": client_id, "role-name": role_name}
  514. data_raw = self.connection.raw_get(URL_ADMIN_CLIENT_ROLE.format(**params_path))
  515. return raise_error_from_response(data_raw, KeycloakGetError)
  516. def get_client_role_id(self, client_id, role_name):
  517. """
  518. Warning: Deprecated
  519. Get client role id by name
  520. This is required for further actions with this role.
  521. :param client_id: id of client (not client-id)
  522. :param role_name: roles name (not id!)
  523. RoleRepresentation
  524. http://www.keycloak.org/docs-api/3.3/rest-api/index.html#_rolerepresentation
  525. :return: role_id
  526. """
  527. role = self.get_client_role(client_id, role_name)
  528. return role.get("id")
  529. def create_client_role(self, payload, skip_exists=False):
  530. """
  531. Create a client role
  532. RoleRepresentation
  533. http://www.keycloak.org/docs-api/3.3/rest-api/index.html#_rolerepresentation
  534. :param payload: id of client (not client-id), role_name: name of role
  535. :return: Keycloak server response (RoleRepresentation)
  536. """
  537. params_path = {"realm-name": self.realm_name, "id": self.client_id}
  538. data_raw = self.connection.raw_post(URL_ADMIN_CLIENT_ROLES.format(**params_path),
  539. data=json.dumps(payload))
  540. return raise_error_from_response(data_raw, KeycloakGetError, expected_code=201, skip_exists=skip_exists)
  541. def delete_client_role(self, role_name):
  542. """
  543. Create a client role
  544. RoleRepresentation
  545. http://www.keycloak.org/docs-api/3.3/rest-api/index.html#_rolerepresentation
  546. :param role_name: roles name (not id!)
  547. """
  548. params_path = {"realm-name": self.realm_name, "id": self.client_id, "role-name": role_name}
  549. data_raw = self.connection.raw_delete(URL_ADMIN_CLIENT_ROLE.format(**params_path))
  550. return raise_error_from_response(data_raw, KeycloakGetError, expected_code=204)
  551. def assign_client_role(self, user_id, client_id, roles):
  552. """
  553. Assign a client role to a user
  554. :param client_id: id of client (not client-id)
  555. :param user_id: id of user
  556. :param client_id: id of client containing role,
  557. :param roles: roles list or role (use RoleRepresentation)
  558. :return Keycloak server response
  559. """
  560. payload = roles if isinstance(roles, list) else [roles]
  561. params_path = {"realm-name": self.realm_name, "id": user_id, "client-id": client_id}
  562. data_raw = self.connection.raw_post(URL_ADMIN_USER_CLIENT_ROLES.format(**params_path),
  563. data=json.dumps(payload))
  564. return raise_error_from_response(data_raw, KeycloakGetError, expected_code=204)
  565. def get_client_roles_of_user(self, user_id, client_id):
  566. """
  567. Get all client roles for a user.
  568. :param client_id: id of client (not client-id)
  569. :param user_id: id of user
  570. :return: Keycloak server response (array RoleRepresentation)
  571. """
  572. return self._get_client_roles_of_user(URL_ADMIN_USER_CLIENT_ROLES, user_id, client_id)
  573. def get_available_client_roles_of_user(self, user_id, client_id):
  574. """
  575. Get available client role-mappings for a user.
  576. :param client_id: id of client (not client-id)
  577. :param user_id: id of user
  578. :return: Keycloak server response (array RoleRepresentation)
  579. """
  580. return self._get_client_roles_of_user(URL_ADMIN_USER_CLIENT_ROLES_AVAILABLE, user_id, client_id)
  581. def get_composite_client_roles_of_user(self, user_id, client_id):
  582. """
  583. Get composite client role-mappings for a user.
  584. :param client_id: id of client (not client-id)
  585. :param user_id: id of user
  586. :return: Keycloak server response (array RoleRepresentation)
  587. """
  588. return self._get_client_roles_of_user(URL_ADMIN_USER_CLIENT_ROLES_COMPOSITE, user_id, client_id)
  589. def _get_client_roles_of_user(self, client_level_role_mapping_url, user_id, client_id):
  590. params_path = {"realm-name": self.realm_name, "id": user_id, "client-id": client_id}
  591. data_raw = self.connection.raw_get(client_level_role_mapping_url.format(**params_path))
  592. return raise_error_from_response(data_raw, KeycloakGetError)
  593. def delete_client_roles_of_user(self, user_id, client_id, roles):
  594. """
  595. Delete client roles from a user.
  596. :param client_id: id of client (not client-id)
  597. :param user_id: id of user
  598. :param client_id: id of client containing role,
  599. :param roles: roles list or role to delete (use RoleRepresentation)
  600. :return: Keycloak server response
  601. """
  602. payload = roles if isinstance(roles, list) else [roles]
  603. params_path = {"realm-name": self.realm_name, "id": user_id, "client-id": client_id}
  604. data_raw = self.connection.raw_delete(URL_ADMIN_USER_CLIENT_ROLES.format(**params_path),
  605. data=json.dumps(payload))
  606. return raise_error_from_response(data_raw, KeycloakGetError, expected_code=204)
  607. def get_authentication_flows(self):
  608. """
  609. Get authentication flows. Returns all flow details
  610. AuthenticationFlowRepresentation
  611. https://www.keycloak.org/docs-api/4.1/rest-api/index.html#_authenticationflowrepresentation
  612. :return: Keycloak server response (AuthenticationFlowRepresentation)
  613. """
  614. params_path = {"realm-name": self.realm_name}
  615. data_raw = self.connection.raw_get(URL_ADMIN_FLOWS.format(**params_path))
  616. return raise_error_from_response(data_raw, KeycloakGetError)
  617. def create_authentication_flow(self, payload, skip_exists=False):
  618. """
  619. Create a new authentication flow
  620. AuthenticationFlowRepresentation
  621. https://www.keycloak.org/docs-api/4.1/rest-api/index.html#_authenticationflowrepresentation
  622. :param payload: AuthenticationFlowRepresentation
  623. :return: Keycloak server response (RoleRepresentation)
  624. """
  625. params_path = {"realm-name": self.realm_name}
  626. data_raw = self.connection.raw_post(URL_ADMIN_FLOWS.format(**params_path),
  627. data=payload)
  628. return raise_error_from_response(data_raw, KeycloakGetError, expected_code=201, skip_exists=skip_exists)
  629. def get_authentication_flow_executions(self, flow_alias):
  630. """
  631. Get authentication flow executions. Returns all execution steps
  632. :return: Response(json)
  633. """
  634. params_path = {"realm-name": self.realm_name, "flow-alias": flow_alias}
  635. data_raw = self.connection.raw_get(URL_ADMIN_FLOWS_EXECUTIONS.format(**params_path))
  636. return raise_error_from_response(data_raw, KeycloakGetError)
  637. def update_authentication_flow_executions(self, payload, flow_alias):
  638. """
  639. Update an authentication flow execution
  640. AuthenticationExecutionInfoRepresentation
  641. https://www.keycloak.org/docs-api/4.1/rest-api/index.html#_authenticationexecutioninforepresentation
  642. :param payload: AuthenticationExecutionInfoRepresentation
  643. :return: Keycloak server response
  644. """
  645. params_path = {"realm-name": self.realm_name, "flow-alias": flow_alias}
  646. data_raw = self.connection.raw_put(URL_ADMIN_FLOWS_EXECUTIONS.format(**params_path),
  647. data=payload)
  648. return raise_error_from_response(data_raw, KeycloakGetError, expected_code=204)
  649. def sync_users(self, storage_id, action):
  650. """
  651. Function to trigger user sync from provider
  652. :param storage_id:
  653. :param action:
  654. :return:
  655. """
  656. data = {'action': action}
  657. params_query = {"action": action}
  658. params_path = {"realm-name": self.realm_name, "id": storage_id}
  659. data_raw = self.connection.raw_post(URL_ADMIN_USER_STORAGE.format(**params_path),
  660. data=json.dumps(data), **params_query)
  661. return raise_error_from_response(data_raw, KeycloakGetError)