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.

791 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. # Copyright (C) 2017 Marcos Pereira <marcospereira.mpj@gmail.com>
  4. #
  5. # This program is free software: you can redistribute it and/or modify
  6. # it under the terms of the GNU Lesser General Public License as published by
  7. # the Free Software Foundation, either version 3 of the License, or
  8. # (at your option) any later version.
  9. #
  10. # This program is distributed in the hope that it will be useful,
  11. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. # GNU Lesser General Public License for more details.
  14. #
  15. # You should have received a copy of the GNU Lesser General Public License
  16. # along with this program. If not, see <http://www.gnu.org/licenses/>.
  17. # Unless otherwise stated in the comments, "id", in e.g. user_id, refers to the
  18. # internal Keycloak server ID, usually a uuid string
  19. from .urls_patterns import *
  20. from .keycloak_openid import KeycloakOpenID
  21. from .exceptions import raise_error_from_response, KeycloakGetError
  22. from .urls_patterns import (
  23. URL_ADMIN_USERS,
  24. )
  25. from .connection import ConnectionManager
  26. import json
  27. class KeycloakAdmin:
  28. def __init__(self, server_url, username, password, realm_name='master', client_id='admin-cli', verify=True):
  29. """
  30. :param server_url: Keycloak server url
  31. :param username: admin username
  32. :param password: admin password
  33. :param realm_name: realm name
  34. :param client_id: client id
  35. :param verify: True if want check connection SSL
  36. """
  37. self._username = username
  38. self._password = password
  39. self._client_id = client_id
  40. self._realm_name = realm_name
  41. # Get token Admin
  42. keycloak_openid = KeycloakOpenID(server_url=server_url, client_id=client_id, realm_name=realm_name,
  43. verify=verify)
  44. self._token = keycloak_openid.token(username, password)
  45. self._connection = ConnectionManager(base_url=server_url,
  46. headers={'Authorization': 'Bearer ' + self.token.get('access_token'),
  47. 'Content-Type': 'application/json'},
  48. timeout=60,
  49. verify=verify)
  50. @property
  51. def realm_name(self):
  52. return self._realm_name
  53. @realm_name.setter
  54. def realm_name(self, value):
  55. self._realm_name = value
  56. @property
  57. def connection(self):
  58. return self._connection
  59. @connection.setter
  60. def connection(self, value):
  61. self._connection = value
  62. @property
  63. def client_id(self):
  64. return self._client_id
  65. @client_id.setter
  66. def client_id(self, value):
  67. self._client_id = value
  68. @property
  69. def username(self):
  70. return self._username
  71. @username.setter
  72. def username(self, value):
  73. self._username = value
  74. @property
  75. def password(self):
  76. return self._password
  77. @password.setter
  78. def password(self, value):
  79. self._password = value
  80. @property
  81. def token(self):
  82. return self._token
  83. @token.setter
  84. def token(self, value):
  85. self._token = value
  86. def get_users(self, query=None):
  87. """
  88. Get users Returns a list of users, filtered according to query parameters
  89. :return: users list
  90. """
  91. params_path = {"realm-name": self.realm_name}
  92. data_raw = self.connection.raw_get(URL_ADMIN_USERS.format(**params_path), **query)
  93. return raise_error_from_response(data_raw, KeycloakGetError)
  94. def get_idps(self):
  95. """
  96. Returns a list of ID Providers,
  97. IdentityProviderRepresentation
  98. https://www.keycloak.org/docs-api/3.3/rest-api/index.html#_identityproviderrepresentation
  99. :return: array IdentityProviderRepresentation
  100. """
  101. params_path = {"realm-name": self.realm_name}
  102. data_raw = self.connection.raw_get(URL_ADMIN_IDPS.format(**params_path))
  103. return raise_error_from_response(data_raw, KeycloakGetError)
  104. def create_user(self, payload):
  105. """
  106. Create a new user Username must be unique
  107. UserRepresentation
  108. http://www.keycloak.org/docs-api/3.3/rest-api/index.html#_userrepresentation
  109. :param payload: UserRepresentation
  110. :return: UserRepresentation
  111. """
  112. params_path = {"realm-name": self.realm_name}
  113. exists = self.get_user_id(username=payload['username'])
  114. if exists is not None:
  115. return str(exists)
  116. data_raw = self.connection.raw_post(URL_ADMIN_USERS.format(**params_path),
  117. data=json.dumps(payload))
  118. return raise_error_from_response(data_raw, KeycloakGetError, expected_code=201)
  119. def users_count(self):
  120. """
  121. User counter
  122. :return: counter
  123. """
  124. params_path = {"realm-name": self.realm_name}
  125. data_raw = self.connection.raw_get(URL_ADMIN_USERS_COUNT.format(**params_path))
  126. return raise_error_from_response(data_raw, KeycloakGetError)
  127. def get_user_id(self, username):
  128. """
  129. Get internal keycloak user id from username
  130. This is required for further actions against this user.
  131. UserRepresentation
  132. http://www.keycloak.org/docs-api/3.3/rest-api/index.html#_userrepresentation
  133. :param username: id in UserRepresentation
  134. :return: user_id
  135. """
  136. params_path = {"realm-name": self.realm_name, "username": username}
  137. data_raw = self.connection.raw_get(URL_ADMIN_USERS.format(**params_path))
  138. data_content = raise_error_from_response(data_raw, KeycloakGetError)
  139. for user in data_content:
  140. this_use_rname = json.dumps(user["username"]).strip('"')
  141. if this_use_rname == username:
  142. return json.dumps(user["id"]).strip('"')
  143. return 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):
  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))
  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 sync_users(self, storage_id, action):
  597. """
  598. Function to trigger user sync from provider
  599. :param storage_id:
  600. :param action:
  601. :return:
  602. """
  603. data = {'action': action}
  604. params_query = {"action": action}
  605. params_path = {"realm-name": self.realm_name, "id": storage_id}
  606. data_raw = self.connection.raw_post(URL_ADMIN_USER_STORAGE.format(**params_path),
  607. data=json.dumps(data), **params_query)
  608. return raise_error_from_response(data_raw, KeycloakGetError)