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.

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