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.

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