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.

848 lines
32 KiB

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