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.

861 lines
32 KiB

8 years ago
7 years ago
6 years ago
6 years ago
8 years ago
6 years ago
7 years ago
7 years ago
8 years ago
7 years ago
7 years ago
8 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
7 years ago
7 years ago
6 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
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
7 years ago
7 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. for group in group["subGroups"]:
  333. if group['path'] == path:
  334. return group
  335. res = self.get_subgroups(group, path)
  336. if res != None:
  337. return res
  338. return None
  339. def create_group(self, payload, parent=None, skip_exists=False):
  340. """
  341. Creates a group in the Realm
  342. :param payload: GroupRepresentation
  343. :param parent: parent group's id. Required to create a sub-group.
  344. GroupRepresentation
  345. http://www.keycloak.org/docs-api/3.2/rest-api/#_grouprepresentation
  346. :return: Http response
  347. """
  348. name = payload['name']
  349. path = payload['path']
  350. exists = None
  351. if name is None and path is not None:
  352. path = "/" + name
  353. elif path is not None:
  354. exists = self.get_group_by_path(path=path, search_in_subgroups=True)
  355. if exists is not None:
  356. return str(exists)
  357. if parent is None:
  358. params_path = {"realm-name": self.realm_name}
  359. data_raw = self.connection.raw_post(URL_ADMIN_GROUPS.format(**params_path),
  360. data=json.dumps(payload))
  361. else:
  362. params_path = {"realm-name": self.realm_name, "id": parent, }
  363. data_raw = self.connection.raw_post(URL_ADMIN_GROUP_CHILD.format(**params_path),
  364. data=json.dumps(payload))
  365. return raise_error_from_response(data_raw, KeycloakGetError, expected_code=201, skip_exists=skip_exists)
  366. def group_set_permissions(self, group_id, enabled=True):
  367. """
  368. Enable/Disable permissions for a group. Cannot delete group if disabled
  369. :param group_id: id of group
  370. :param enabled: boolean
  371. :return: Keycloak server response
  372. """
  373. params_path = {"realm-name": self.realm_name, "id": group_id}
  374. data_raw = self.connection.raw_put(URL_ADMIN_GROUP_PERMISSIONS.format(**params_path),
  375. data=json.dumps({"enabled": enabled}))
  376. return raise_error_from_response(data_raw, KeycloakGetError)
  377. def group_user_add(self, user_id, group_id):
  378. """
  379. Add user to group (user_id and group_id)
  380. :param group_id: id of group
  381. :param user_id: id of user
  382. :param group_id: id of group to add to
  383. :return: Keycloak server response
  384. """
  385. params_path = {"realm-name": self.realm_name, "id": user_id, "group-id": group_id}
  386. data_raw = self.connection.raw_put(URL_ADMIN_USER_GROUP.format(**params_path), data=None)
  387. return raise_error_from_response(data_raw, KeycloakGetError, expected_code=204)
  388. def group_user_remove(self, user_id, group_id):
  389. """
  390. Remove user from group (user_id and group_id)
  391. :param group_id: id of group
  392. :param user_id: id of user
  393. :param group_id: id of group to add to
  394. :return: Keycloak server response
  395. """
  396. params_path = {"realm-name": self.realm_name, "id": user_id, "group-id": group_id}
  397. data_raw = self.connection.raw_delete(URL_ADMIN_USER_GROUP.format(**params_path))
  398. return raise_error_from_response(data_raw, KeycloakGetError, expected_code=204)
  399. def delete_group(self, group_id):
  400. """
  401. Deletes a group in the Realm
  402. :param group_id: id of group to delete
  403. :return: Keycloak server response
  404. """
  405. params_path = {"realm-name": self.realm_name, "id": group_id}
  406. data_raw = self.connection.raw_delete(URL_ADMIN_GROUP.format(**params_path))
  407. return raise_error_from_response(data_raw, KeycloakGetError, expected_code=204)
  408. def get_clients(self):
  409. """
  410. Get clients belonging to the realm Returns a list of clients belonging to the realm
  411. ClientRepresentation
  412. http://www.keycloak.org/docs-api/3.3/rest-api/index.html#_clientrepresentation
  413. :return: Keycloak server response (ClientRepresentation)
  414. """
  415. params_path = {"realm-name": self.realm_name}
  416. data_raw = self.connection.raw_get(URL_ADMIN_CLIENTS.format(**params_path))
  417. return raise_error_from_response(data_raw, KeycloakGetError)
  418. def get_client(self, client_id):
  419. """
  420. Get representation of the client
  421. ClientRepresentation
  422. http://www.keycloak.org/docs-api/3.3/rest-api/index.html#_clientrepresentation
  423. :param client_id: id of client (not client-id)
  424. :return: Keycloak server response (ClientRepresentation)
  425. """
  426. params_path = {"realm-name": self.realm_name, "id": client_id}
  427. data_raw = self.connection.raw_get(URL_ADMIN_CLIENT.format(**params_path))
  428. return raise_error_from_response(data_raw, KeycloakGetError)
  429. def get_client_id(self, client_name):
  430. """
  431. Get internal keycloak client id from client-id.
  432. This is required for further actions against this client.
  433. :param client_name: name in ClientRepresentation
  434. http://www.keycloak.org/docs-api/3.3/rest-api/index.html#_clientrepresentation
  435. :return: client_id (uuid as string)
  436. """
  437. clients = self.get_clients()
  438. for client in clients:
  439. if client_name == client.get('name') or client_name == client.get('clientId'):
  440. return client["id"]
  441. return None
  442. def get_client_authz_settings(self, client_id):
  443. """
  444. Get authorization json from client.
  445. :param client_id: id in ClientRepresentation
  446. http://www.keycloak.org/docs-api/3.3/rest-api/index.html#_clientrepresentation
  447. :return: Keycloak server response
  448. """
  449. params_path = {"realm-name": self.realm_name, "id": client_id}
  450. data_raw = self.connection.raw_get(URL_ADMIN_CLIENT_AUTHZ_SETTINGS.format(**params_path))
  451. return data_raw
  452. def get_client_authz_resources(self, client_id):
  453. """
  454. Get resources from client.
  455. :param client_id: id in ClientRepresentation
  456. http://www.keycloak.org/docs-api/3.3/rest-api/index.html#_clientrepresentation
  457. :return: Keycloak server response
  458. """
  459. params_path = {"realm-name": self.realm_name, "id": client_id}
  460. data_raw = self.connection.raw_get(URL_ADMIN_CLIENT_AUTHZ_RESOURCES.format(**params_path))
  461. return data_raw
  462. def create_client(self, payload, skip_exists=False):
  463. """
  464. Create a client
  465. ClientRepresentation: http://www.keycloak.org/docs-api/3.3/rest-api/index.html#_clientrepresentation
  466. :param skip_exists: Skip if client already exist.
  467. :param payload: ClientRepresentation
  468. :return: Keycloak server response (UserRepresentation)
  469. """
  470. params_path = {"realm-name": self.realm_name}
  471. data_raw = self.connection.raw_post(URL_ADMIN_CLIENTS.format(**params_path),
  472. data=json.dumps(payload))
  473. return raise_error_from_response(data_raw, KeycloakGetError, expected_code=201, skip_exists=skip_exists)
  474. def delete_client(self, client_id):
  475. """
  476. Get representation of the client
  477. ClientRepresentation
  478. http://www.keycloak.org/docs-api/3.3/rest-api/index.html#_clientrepresentation
  479. :param client_id: keycloak client id (not oauth client-id)
  480. :return: Keycloak server response (ClientRepresentation)
  481. """
  482. params_path = {"realm-name": self.realm_name, "id": client_id}
  483. data_raw = self.connection.raw_delete(URL_ADMIN_CLIENT.format(**params_path))
  484. return raise_error_from_response(data_raw, KeycloakGetError, expected_code=204)
  485. def get_realm_roles(self):
  486. """
  487. Get all roles for the realm or client
  488. RoleRepresentation
  489. http://www.keycloak.org/docs-api/3.3/rest-api/index.html#_rolerepresentation
  490. :return: Keycloak server response (RoleRepresentation)
  491. """
  492. params_path = {"realm-name": self.realm_name}
  493. data_raw = self.connection.raw_get(URL_ADMIN_REALM_ROLES.format(**params_path))
  494. return raise_error_from_response(data_raw, KeycloakGetError)
  495. def get_client_roles(self, client_id):
  496. """
  497. Get all roles for the client
  498. :param client_id: id of client (not client-id)
  499. RoleRepresentation
  500. http://www.keycloak.org/docs-api/3.3/rest-api/index.html#_rolerepresentation
  501. :return: Keycloak server response (RoleRepresentation)
  502. """
  503. params_path = {"realm-name": self.realm_name, "id": client_id}
  504. data_raw = self.connection.raw_get(URL_ADMIN_CLIENT_ROLES.format(**params_path))
  505. return raise_error_from_response(data_raw, KeycloakGetError)
  506. def get_client_role(self, client_id, role_name):
  507. """
  508. Get client role id by name
  509. This is required for further actions with this role.
  510. :param client_id: id of client (not client-id)
  511. :param role_name: roles name (not id!)
  512. RoleRepresentation
  513. http://www.keycloak.org/docs-api/3.3/rest-api/index.html#_rolerepresentation
  514. :return: role_id
  515. """
  516. params_path = {"realm-name": self.realm_name, "id": client_id, "role-name": role_name}
  517. data_raw = self.connection.raw_get(URL_ADMIN_CLIENT_ROLE.format(**params_path))
  518. return raise_error_from_response(data_raw, KeycloakGetError)
  519. def get_client_role_id(self, client_id, role_name):
  520. """
  521. Warning: Deprecated
  522. Get client role id by name
  523. This is required for further actions with this role.
  524. :param client_id: id of client (not client-id)
  525. :param role_name: roles name (not id!)
  526. RoleRepresentation
  527. http://www.keycloak.org/docs-api/3.3/rest-api/index.html#_rolerepresentation
  528. :return: role_id
  529. """
  530. role = self.get_client_role(client_id, role_name)
  531. return role.get("id")
  532. def create_client_role(self, payload, skip_exists=False):
  533. """
  534. Create a client role
  535. RoleRepresentation
  536. http://www.keycloak.org/docs-api/3.3/rest-api/index.html#_rolerepresentation
  537. :param payload: id of client (not client-id), role_name: name of role
  538. :return: Keycloak server response (RoleRepresentation)
  539. """
  540. params_path = {"realm-name": self.realm_name, "id": self.client_id}
  541. data_raw = self.connection.raw_post(URL_ADMIN_CLIENT_ROLES.format(**params_path),
  542. data=json.dumps(payload))
  543. return raise_error_from_response(data_raw, KeycloakGetError, expected_code=201, skip_exists=skip_exists)
  544. def delete_client_role(self, role_name):
  545. """
  546. Create a client role
  547. RoleRepresentation
  548. http://www.keycloak.org/docs-api/3.3/rest-api/index.html#_rolerepresentation
  549. :param role_name: roles name (not id!)
  550. """
  551. params_path = {"realm-name": self.realm_name, "id": self.client_id, "role-name": role_name}
  552. data_raw = self.connection.raw_delete(URL_ADMIN_CLIENT_ROLE.format(**params_path))
  553. return raise_error_from_response(data_raw, KeycloakGetError, expected_code=204)
  554. def assign_client_role(self, user_id, client_id, roles):
  555. """
  556. Assign a client role to a user
  557. :param client_id: id of client (not client-id)
  558. :param user_id: id of user
  559. :param client_id: id of client containing role,
  560. :param roles: roles list or role (use RoleRepresentation)
  561. :return Keycloak server response
  562. """
  563. payload = roles if isinstance(roles, list) else [roles]
  564. params_path = {"realm-name": self.realm_name, "id": user_id, "client-id": client_id}
  565. data_raw = self.connection.raw_post(URL_ADMIN_USER_CLIENT_ROLES.format(**params_path),
  566. data=json.dumps(payload))
  567. return raise_error_from_response(data_raw, KeycloakGetError, expected_code=204)
  568. def get_client_roles_of_user(self, user_id, client_id):
  569. """
  570. Get all client roles for a user.
  571. :param client_id: id of client (not client-id)
  572. :param user_id: id of user
  573. :return: Keycloak server response (array RoleRepresentation)
  574. """
  575. return self._get_client_roles_of_user(URL_ADMIN_USER_CLIENT_ROLES, user_id, client_id)
  576. def get_available_client_roles_of_user(self, user_id, client_id):
  577. """
  578. Get available client role-mappings for a user.
  579. :param client_id: id of client (not client-id)
  580. :param user_id: id of user
  581. :return: Keycloak server response (array RoleRepresentation)
  582. """
  583. return self._get_client_roles_of_user(URL_ADMIN_USER_CLIENT_ROLES_AVAILABLE, user_id, client_id)
  584. def get_composite_client_roles_of_user(self, user_id, client_id):
  585. """
  586. Get composite client role-mappings for a user.
  587. :param client_id: id of client (not client-id)
  588. :param user_id: id of user
  589. :return: Keycloak server response (array RoleRepresentation)
  590. """
  591. return self._get_client_roles_of_user(URL_ADMIN_USER_CLIENT_ROLES_COMPOSITE, user_id, client_id)
  592. def _get_client_roles_of_user(self, client_level_role_mapping_url, user_id, client_id):
  593. params_path = {"realm-name": self.realm_name, "id": user_id, "client-id": client_id}
  594. data_raw = self.connection.raw_get(client_level_role_mapping_url.format(**params_path))
  595. return raise_error_from_response(data_raw, KeycloakGetError)
  596. def delete_client_roles_of_user(self, user_id, client_id, roles):
  597. """
  598. Delete client roles from a user.
  599. :param client_id: id of client (not client-id)
  600. :param user_id: id of user
  601. :param client_id: id of client containing role,
  602. :param roles: roles list or role to delete (use RoleRepresentation)
  603. :return: Keycloak server response
  604. """
  605. payload = roles if isinstance(roles, list) else [roles]
  606. params_path = {"realm-name": self.realm_name, "id": user_id, "client-id": client_id}
  607. data_raw = self.connection.raw_delete(URL_ADMIN_USER_CLIENT_ROLES.format(**params_path),
  608. data=json.dumps(payload))
  609. return raise_error_from_response(data_raw, KeycloakGetError, expected_code=204)
  610. def get_authentication_flows(self):
  611. """
  612. Get authentication flows. Returns all flow details
  613. AuthenticationFlowRepresentation
  614. https://www.keycloak.org/docs-api/4.1/rest-api/index.html#_authenticationflowrepresentation
  615. :return: Keycloak server response (AuthenticationFlowRepresentation)
  616. """
  617. params_path = {"realm-name": self.realm_name}
  618. data_raw = self.connection.raw_get(URL_ADMIN_FLOWS.format(**params_path))
  619. return raise_error_from_response(data_raw, KeycloakGetError)
  620. def create_authentication_flow(self, payload, skip_exists=False):
  621. """
  622. Create a new authentication flow
  623. AuthenticationFlowRepresentation
  624. https://www.keycloak.org/docs-api/4.1/rest-api/index.html#_authenticationflowrepresentation
  625. :param payload: AuthenticationFlowRepresentation
  626. :return: Keycloak server response (RoleRepresentation)
  627. """
  628. params_path = {"realm-name": self.realm_name}
  629. data_raw = self.connection.raw_post(URL_ADMIN_FLOWS.format(**params_path),
  630. data=payload)
  631. return raise_error_from_response(data_raw, KeycloakGetError, expected_code=201, skip_exists=skip_exists)
  632. def get_authentication_flow_executions(self, flow_alias):
  633. """
  634. Get authentication flow executions. Returns all execution steps
  635. :return: Response(json)
  636. """
  637. params_path = {"realm-name": self.realm_name, "flow-alias": flow_alias}
  638. data_raw = self.connection.raw_get(URL_ADMIN_FLOWS_EXECUTIONS.format(**params_path))
  639. return raise_error_from_response(data_raw, KeycloakGetError)
  640. def update_authentication_flow_executions(self, payload, flow_alias):
  641. """
  642. Update an authentication flow execution
  643. AuthenticationExecutionInfoRepresentation
  644. https://www.keycloak.org/docs-api/4.1/rest-api/index.html#_authenticationexecutioninforepresentation
  645. :param payload: AuthenticationExecutionInfoRepresentation
  646. :return: Keycloak server response
  647. """
  648. params_path = {"realm-name": self.realm_name, "flow-alias": flow_alias}
  649. data_raw = self.connection.raw_put(URL_ADMIN_FLOWS_EXECUTIONS.format(**params_path),
  650. data=payload)
  651. return raise_error_from_response(data_raw, KeycloakGetError, expected_code=204)
  652. def sync_users(self, storage_id, action):
  653. """
  654. Function to trigger user sync from provider
  655. :param storage_id:
  656. :param action:
  657. :return:
  658. """
  659. data = {'action': action}
  660. params_query = {"action": action}
  661. params_path = {"realm-name": self.realm_name, "id": storage_id}
  662. data_raw = self.connection.raw_post(URL_ADMIN_USER_STORAGE.format(**params_path),
  663. data=json.dumps(data), **params_query)
  664. return raise_error_from_response(data_raw, KeycloakGetError)