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.

797 lines
29 KiB

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